@cline/core 0.0.45 → 0.0.46

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 pY}from"node:module";var cY=Object.defineProperty;var dY=($)=>$;function lY($,f){this[$]=dY.bind(null,f)}var b4=($,f)=>{for(var J in f)cY($,J,{get:f[J],enumerable:!0,configurable:!0,set:lY.bind(f,J)})};var f1=($,f)=>()=>($&&(f=$($=0)),f);var U9=pY(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as iY}from"@cline/shared";function v($,f,J){$?.capture({event:f,properties:J})}function n2($){if(!$)return;return $.substring(0,nY)}function aY($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function tY($){return typeof $==="string"?$:$.message}function L9($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function sY($){v($,k.CLIENT.EXTENSION_ACTIVATED)}function m4($,f){let J=[...f.vcs_types],W={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:L9(J,new Set(["git"])),has_mercurial:L9(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)W.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)W.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)W.is_remote_workspace=f.is_remote_workspace;v($,k.WORKSPACE.INITIALIZED,W)}function g4($,f,J){v($,k.WORKSPACE.INIT_ERROR,{error_type:aY(f),error_message:n2(tY(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function oY($,f){v($,k.WORKSPACE.PATH_RESOLVED,{...f})}function R$($,f){v($,k.USER.AUTH_STARTED,{provider:f})}function D$($,f){v($,k.USER.AUTH_SUCCEEDED,{provider:f})}function L$($,f,J){v($,k.USER.AUTH_FAILED,{provider:f,errorMessage:n2(J)})}function J1($,f,J){v($,k.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function eY($,f){v($,k.USER.PROVIDER_CONFIGURED,{provider:f})}function O9($,f){$?.captureRequired(k.USER.TELEMETRY_OPT_OUT,f)}function O$($,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 v4($,f){v($,k.TASK.CREATED,f)}function u4($,f){v($,k.TASK.RESTARTED,f)}function a2($,f){v($,k.TASK.COMPLETED,f)}function Nf($,f){v($,k.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function c4($,f){v($,k.TASK.TOKEN_USAGE,f)}function d4($,f,J){v($,k.TASK.MODE_SWITCH,{ulid:f,mode:J})}function l4($,f){v($,k.TASK.TOOL_USED,f)}function p4($,f){v($,k.TASK.SKILL_USED,f)}function r4($,f){v($,k.TASK.DIFF_EDIT_FAILED,f)}function t2($,f){v($,k.TASK.PROVIDER_API_ERROR,{...f,errorMessage:n2(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function z9($,f){v($,k.SDK.TOOL_TIMEOUT,$V(f))}function $V($){let f={};for(let[J,W]of Object.entries($))if(W!==void 0)f[J]=W;return f}function i4($,f,J){v($,k.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function n4($,f,J,W){v($,k.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:n2(W),timestamp:new Date().toISOString()})}function a4($,f,J,W,Z){v($,k.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:W,isEmpty:Z,timestamp:new Date().toISOString()})}function W1($,f){v($,k.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function t4($,f){v($,k.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function s2($,f){v($,f.event==="ended"?k.TASK.SUBAGENT_COMPLETED:k.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function s4($,f,J,W){v($,k.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}function o4($,f){v($,k.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function e4($,f){v($,k.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var nY=500,k;var B0=f1(()=>{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:iY,TOOL_TIMEOUT:"sdk.tool_timeout"}}});import{mkdirSync as IB,readFileSync as xB,statSync as mB,writeFileSync as gB}from"node:fs";import{dirname as vB}from"node:path";import{resolveGlobalSettingsPath as PQ}from"@cline/shared/storage";import{z as p1}from"zod";function U8(){return R8.parse({})}function uB(){F8=void 0}function cB($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function dB($){let f;try{f=xB($,"utf8")}catch{return U8()}try{let J=R8.safeParse(JSON.parse(f));return J.success?J.data:U8()}catch{return U8()}}function lB(){let $=PQ(),f=mB($,{throwIfNoEntry:!1}),J=f?.mtimeMs??0,W=f?.size??0,Z=F8;if(Z&&Z.path===$&&Z.mtimeMs===J&&Z.size===W)return Z;let Q=cB(f?dB($):U8());return F8={path:$,mtimeMs:J,size:W,value:Q},F8}function L0(){return lB().value}function T$($,f={}){let J=PQ(),W=L0();IB(vB(J),{recursive:!0});let Z=R8.parse($);if(!W.telemetryOptOut&&Z.telemetryOptOut)O9(f.telemetry);gB(J,`${JSON.stringify(Z,null,2)}
2
- `,"utf8"),uB()}function N6(){return L0().telemetryOptOut}function pB($,f={}){T$({...L0(),telemetryOptOut:$},f)}function rB(){return L0().autoUpdateEnabled}function iB($,f={}){T$({...L0(),autoUpdateEnabled:$},f)}function Q$($){return new Set($??L0().disabledTools??[])}function D8($){return new Set($??L0().disabledPlugins??[])}function nB($){return Q$().has($)}function M6($){let f=L0(),J=new Set(f.disabledTools??[]),W=J.has($);if(W)J.delete($);else J.add($);return T$({...f,disabledTools:[...J]}),!W}function UQ($,f){let J=[...new Set($.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=L0(),Z=Q$(W.disabledTools);for(let Q of J)if(f)Z.add(Q);else Z.delete(Q);T$({...W,disabledTools:[...Z]})}function FQ($,f){return UQ([$],f),f}function aB($){return D8().has($)}function tB($,f){let J=$.trim();if(!J)return;let W=L0(),Z=D8(W.disabledPlugins);if(f)Z.add(J);else Z.delete(J);T$({...W,disabledPlugins:[...Z]})}function y6($,f){let J=D8(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W))}function r1($,f){let J=Q$(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W.name))}function q6($,f){if(!$||$.length===0)return $;let J=Q$(f);if(J.size===0)return $;return $.map((W)=>{if(!W.setup)return W;return{...W,setup:(Z,Q)=>W.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},Q)}})}var GQ,R8,F8;var n0=f1(()=>{B0();GQ=p1.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,p1.array(p1.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,W)=>J.localeCompare(W));return f.length>0?f:void 0}),R8=p1.object({telemetryOptOut:p1.boolean().default(!1).catch(!1),autoUpdateEnabled:p1.boolean().default(!0).catch(!0),disabledTools:GQ.optional(),disabledPlugins:GQ.optional()}).strip().transform(($)=>{let f={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});var n7={};b4(n7,{normalizeUserMessage:()=>$U,buildInitialUserContent:()=>eP});async function eP($,f,J,W){let Z=fU(f),Q=await WU(J,W);if(Z.length===0&&!Q)return $;let j=[{type:"text",text:$},...Z];if(Q)j.push(...Q);return j}function $U($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let W of f)if(W&&typeof W==="object"&&W.type==="text"){let Z=W.text;if(typeof Z==="string")J.push(Z)}return J.join(`
3
- `)}function fU($){if(!$||$.length===0)return[];let f=[];for(let J of $){let W=JU(J);if(W)f.push(W)}return f}function JU($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let W=J[1],Z=J[2];if(!W||!Z)return;return{type:"image",mediaType:W,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function WU($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all($.map(async(Z)=>{let Q=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:Q,content:j}}catch(j){let H=j instanceof Error?j.message:String(j);return{type:"file",path:Q,content:`Error fetching content: ${H}`}}}));if(W.length===0)return;return W}var m3={};b4(m3,{updateMcpServerOAuthState:()=>$2,setMcpServerDisabled:()=>of,resolveMcpServerRegistrations:()=>C$,resolveDefaultMcpSettingsPath:()=>h0,registerMcpServersFromSettingsFile:()=>f2,normalizeMcpServerOAuthState:()=>Qf,loadMcpSettingsFile:()=>sf,listMcpServerOAuthStatuses:()=>h5,hasMcpSettingsFile:()=>P1,getMcpServerOAuthState:()=>ef});import{existsSync as pU,mkdirSync as C3,readFileSync as w5,writeFileSync as E3}from"node:fs";import{dirname as b3}from"node:path";import{resolveMcpSettingsPath as rU}from"@cline/shared/storage";import{z as y}from"zod";function q5($){if(!$)return;if($==="http")return"streamableHttp";return $}function h0(){return rU()}function WF($){let f=w5($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let Z=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function x3($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function ZF($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function sf($={}){let f=$.filePath??h0(),J=w5(f,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=JF.safeParse(W);if(!Z.success){let Q=Z.error.issues.map((j)=>{let H=j.path.join(".");return H?`${H}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${Q}`)}return Z.data}function QF($){let f=w5($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let W=J,Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return W}function Qf($){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 jF($){if($===void 0)return;let f=S5.safeParse($);if(!f.success)return;return Qf(f.data)}function P1($={}){let f=$.filePath??h0();return pU(f)}function C$($={}){let f=sf($);return Object.entries(f.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata,oauth:W.oauth}))}function of($){let f=$.filePath??h0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let W=WF(f),Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let Q={...Z},j=x3(Q,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let H={...j};if($.disabled)H.disabled=!0;else delete H.disabled;ZF(Q,J,H),C3(b3(f),{recursive:!0}),E3(f,`${JSON.stringify({...W,mcpServers:Q},null,2)}
4
- `)}function ef($,f={}){let J=sf(f);if(!Object.hasOwn(J.mcpServers,$))return;return Qf(J.mcpServers[$]?.oauth)}function $2($,f,J={}){let W=J.filePath??h0(),Z=QF(W),Q=Z.mcpServers,j=x3(Q,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let H=jF(j.oauth)??{},X=Qf(f(H));if(X)j.oauth=X;else delete j.oauth;return C3(b3(W),{recursive:!0}),E3(W,`${JSON.stringify(Z,null,2)}
5
- `,"utf8"),X??{}}function h5($={}){return C$($).map((J)=>{let W=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:W,oauthConfigured:W&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,W)=>J.serverName.localeCompare(W.serverName))}async function f2($,f={}){let J=C$(f);for(let W of J)await $.registerServer(W);return J}var tf,k3,S5,iU,nU,aU,tU,sU,oU,I3,eU,$F,fF,JF;var AJ=f1(()=>{tf=y.record(y.string(),y.string()),k3=y.record(y.string(),y.unknown()),S5=y.object({clientInformation:y.record(y.string(),y.unknown()).optional(),tokens:y.record(y.string(),y.unknown()).optional(),codeVerifier:y.string().optional(),discoveryState:y.record(y.string(),y.unknown()).optional(),redirectUrl:y.string().url().optional(),lastError:y.string().optional(),lastAuthenticatedAt:y.number().int().positive().optional()}).strip(),iU=y.object({type:y.literal("stdio"),command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:tf.optional()}),nU=y.object({type:y.literal("sse"),url:y.string().url(),headers:tf.optional()}),aU=y.object({type:y.literal("streamableHttp"),url:y.string().url(),headers:tf.optional()}),tU=y.discriminatedUnion("type",[iU,nU,aU]),sU=y.object({transport:tU,disabled:y.boolean().optional(),metadata:k3.optional(),oauth:S5.optional()}),oU=y.enum(["stdio","sse","http","streamableHttp"]).optional(),I3=y.object({type:y.enum(["stdio","sse","streamableHttp"]).optional(),transportType:oU,disabled:y.boolean().optional(),metadata:k3.optional(),oauth:S5.optional()});eU=I3.extend({command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:tf.optional()}).superRefine(($,f)=>{let J=$.type??q5($.transportType);if(J&&J!=="stdio")f.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),$F=I3.extend({url:y.string().url(),headers:tf.optional()}).superRefine(($,f)=>{let J=$.type??q5($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??q5($.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}}),fF=y.union([sU,eU,$F]),JF=y.object({mcpServers:y.record(y.string(),fF)}).passthrough()});import{existsSync as zO,mkdirSync as _O,readFileSync as TO,writeFileSync as NO}from"node:fs";import{resolve as MO}from"node:path";import{resolveSessionDataDir as yO}from"@cline/shared/storage";import{nanoid as qO}from"nanoid";import*as wO from"node-machine-id";function y1($){let f=$?.trim();if(f)return f;let J=CO();if(J)return J;return EO()}function hO(){let $=wO;return $.machineIdSync??$.default?.machineIdSync}function CO(){try{let $=hO();if(!$)return;return $().trim()||void 0}catch{return}}function EO(){let $=yO(),f=MO($,SO);try{if(zO(f)){let W=TO(f,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${qO()}`;try{_O($,{recursive:!0}),NO(f,J,"utf8")}catch{}return J}var SO="machine-id";var EJ=()=>{};class c2{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.counters.get($);if(!Q)Q=this.meter.createCounter($,W?{description:W}:void 0),this.counters.set($,Q);Q.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.histograms.get($);if(!Q)Q=this.meter.createHistogram($,W?{description:W}:void 0),this.histograms.set($,Q);Q.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.buildAttributes(J),j=JSON.stringify(Q),H=this.gaugeValues.get($);if(f===null){if(H){if(H.delete(j),H.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let X=H;if(!X)X=new Map,this.gaugeValues.set($,X);if(!this.gauges.has($)){let A=this.meter.createObservableGauge($,W?{description:W}:void 0);A.addCallback((Y)=>{for(let V of this.snapshotGaugeSeries($))Y.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set($,A)}X.set(j,{value:f,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:W})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,W=0){if(!$)return{};let Z={},Q=100,j=10;for(let[H,X]of Object.entries($)){if(H==="__proto__"||H==="constructor"||H==="prototype")continue;let A=f?`${f}.${H}`:H;if(X===null||X===void 0){Z[A]=String(X);continue}if(Array.isArray(X)){let Y=X.length>Q?X.slice(0,Q):X;try{Z[A]=JSON.stringify(Y)}catch{Z[A]="[UnserializableArray]"}if(X.length>Q)Z[`${A}_truncated`]=!0,Z[`${A}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){Z[A]=X.toISOString();continue}if(X instanceof Error){Z[A]=X.message;continue}if(J.has(X)){Z[A]="[Circular]";continue}if(W>=j){Z[A]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(Z,this.flattenProperties(X,A,J,W+1));continue}if(MN(X)){Z[A]=X;continue}try{Z[A]=JSON.stringify(X)}catch{Z[A]=String(X)}}return Z}}function MN($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class R4{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordHistogram($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordGauge($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:W,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class d2{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new R4({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let W of this.adapters)W.emitRequired($,J)}recordCounter($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,Q,W,Z)}recordHistogram($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,Q,W,Z)}recordGauge($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,Q,W,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var bZ=()=>{};import{metrics as yN,trace as qN}from"@opentelemetry/api";import{logs as wN}from"@opentelemetry/api-logs";import{OTLPLogExporter as SN}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as hN}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as CN}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as EN}from"@opentelemetry/resources";import{BatchLogRecordProcessor as bN,ConsoleLogRecordExporter as kN,LoggerProvider as IN}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as xN,MeterProvider as mN,PeriodicExportingMetricReader as FA}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as gN,ConsoleSpanExporter as vN,SimpleSpanProcessor as uN}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as cN}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as dN,ATTR_SERVICE_VERSION as lN}from"@opentelemetry/semantic-conventions";class RA{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 l2{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=EN({[dN]:$.serviceName??"cline",...$.serviceVersion?{[lN]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)yN.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)wN.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return qN.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new c2({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new d2({...$,adapters:[f],distinctId:y1($.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=kZ(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),Z=f.map((Q)=>iN(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(Z.length===0)return null;return new mN({resource:$,readers:Z})}createTracerProvider($){let f=kZ(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let Q of f){let j=rN(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new cN({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=kZ(this.options.logsExporter);if(f.length===0)return null;let J=f.map((W)=>{let Z=pN(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new bN(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new IN({resource:$,processors:J})}}function D4($){let f=new l2($),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 k1($){if(N6())return{telemetry:new RA($)};if($.enabled!==!0)return{telemetry:new d2({...$,distinctId:y1($.distinctId)})};return D4($)}function L4($){let{telemetry:f,provider:J}=k1($);return{telemetry:f,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function kZ($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function pN($,f){if($==="console")return new kN;if(!f.endpoint)return null;let J=IZ(f.endpoint,"/v1/logs");return new SN({url:J,headers:f.headers})}function rN($,f){if($==="console")return new uN(new vN);if(!f.endpoint)return null;let J=IZ(f.endpoint,"/v1/traces");return new gN(new CN({url:J,headers:f.headers}))}function iN($,f){if($==="console")return new FA({exporter:new xN,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=IZ(f.endpoint,"/v1/metrics");return new FA({exporter:new hN({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function IZ($,f){let J=new URL($),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith(f)?W:`${W}${f}`,J.toString()}var O4=f1(()=>{n0();EJ();bZ()});var VY={};b4(VY,{createOpenTelemetryTelemetryService:()=>D4,createConfiguredTelemetryService:()=>k1,createConfiguredTelemetryHandle:()=>L4,OpenTelemetryProvider:()=>l2,OpenTelemetryAdapter:()=>c2});var eZ=f1(()=>{O4()});import*as xp from"@cline/llms";import{buildClineSystemPrompt as gp,buildSdkErrorProperties as vp,ContributionRegistry as up,captureSdkError as cp,createClineTelemetryServiceConfig as dp,createClineTelemetryServiceMetadata as lp,createContributionRegistry as pp,createTool as rp,emptyWorkspaceManifest as ip,formatDisplayUserInput as np,noopBasicLogger as ap,normalizeSdkError as tp,normalizeUserInput as sp,parseUserCommandEnvelope as op,registerDisposable as ep,SDK_ERROR_TELEMETRY_EVENT as $r}from"@cline/shared";export*from"@cline/shared/storage";function rY($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function F9($,f,J){let W=rY(J);if(W)return W;let Z=f.trim();if(Z){let Q=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${Q}`}return`Cline account request failed with status ${$}`}class k4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((H)=>H.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,Q=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let H=await j.text(),X;if(H.trim())try{X=JSON.parse(H)}catch{if(!j.ok)throw Error(F9(j.status,H,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(F9(j.status,H,X));if(typeof X==="object"&&X!==null){let A=X;if(typeof A.success==="boolean"){if(!A.success)throw Error(A.error||"Cline account request failed");if(A.data!==void 0)return A.data}}if(X===void 0||X===null)throw Error("Cline account response payload was empty");return X}finally{clearTimeout(Q)}}}function R9($){return $.action==="clineAccount"}async function D9($,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 I4{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 x4($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((W)=>{$.onOpenUrlError?.({url:f,error:W})})}catch(W){$.onOpenUrlError?.({url:f,error:W})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}B0();import{getClineEnvironmentConfig as $6}from"@cline/shared";function fV(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function W$($){let f=await import("node:http"),J=$.host??"127.0.0.1",W=$.timeoutMs??300000,Z=$.successHtml??JV,Q=fV(),j=!1,H=null,X=null,A=null,Y=(K)=>{if(j)return;j=!0,Q.resolve(K)},V=()=>{if(H)clearTimeout(H),H=null;let K=A;if(A=null,X)X.close(),X=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return H=setTimeout(()=>{V(),Y(null)},W),Q.promise};for(let K of $.ports){let G=f.createServer((P,U)=>{try{let F=new URL(P.url||"",`http://${J}:${K}`);if(F.pathname!==$.callbackPath){U.statusCode=404,U.end("Not found");return}let z={url:F,code:F.searchParams.get("code")??void 0,state:F.searchParams.get("state")??void 0,provider:F.searchParams.get("provider")??void 0,error:F.searchParams.get("error")??void 0};if(z.error){U.statusCode=400,U.end(`Authentication failed: ${z.error}`),V(),Y(z);return}if(!z.code){U.statusCode=400,U.end("Missing authorization code");return}if($.expectedState&&z.state!==$.expectedState){U.statusCode=400,U.end("State mismatch");return}U.statusCode=200,U.setHeader("Content-Type","text/html; charset=utf-8"),U.end(Z),V(),Y(z)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((P)=>{let U=(F)=>{G.off("error",U),P({bound:!1,error:F})};G.once("error",U),G.listen(K,J,()=>{G.off("error",U),X=G,P({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){A=K;let P=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:P})).catch(()=>{});return{callbackUrl:P,waitForCallback:B,cancelWait:()=>{V(),Y(null)},close:()=>{V(),Y(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var JV=`<!DOCTYPE html>
1
+ import{createRequire as RV}from"node:module";var GV=Object.defineProperty;var FV=(f)=>f;function UV(f,$){this[f]=FV.bind(null,$)}var p4=(f,$)=>{for(var J in $)GV(f,J,{get:$[J],enumerable:!0,configurable:!0,set:UV.bind($,J)})};var j$=(f,$)=>()=>(f&&($=f(f=0)),$);var bZ=RV(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as LV}from"@cline/shared";function u(f,$,J){f?.capture({event:$,properties:J})}function W8(f){if(!f)return;return f.substring(0,OV)}function _V(f){if(typeof f==="string")return"Error";return f.name?.trim()||f.constructor?.name||"Error"}function TV(f){return typeof f==="string"?f:f.message}function gZ(f,$){return f.some((J)=>$.has(J.trim().toLowerCase()))}function zV(f){u(f,x.CLIENT.EXTENSION_ACTIVATED)}function n4(f,$){let J=[...$.vcs_types],Q={root_count:$.root_count,vcs_types:J,is_multi_root:$.root_count>1,has_git:gZ(J,new Set(["git"])),has_mercurial:gZ(J,new Set(["mercurial","hg"]))};if($.init_duration_ms!==void 0)Q.init_duration_ms=$.init_duration_ms;if($.feature_flag_enabled!==void 0)Q.feature_flag_enabled=$.feature_flag_enabled;if($.is_remote_workspace!==void 0)Q.is_remote_workspace=$.is_remote_workspace;u(f,x.WORKSPACE.INITIALIZED,Q)}function a4(f,$,J){u(f,x.WORKSPACE.INIT_ERROR,{error_type:_V($),error_message:W8(TV($)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function MV(f,$){u(f,x.WORKSPACE.PATH_RESOLVED,{...$})}function Tf(f,$){u(f,x.USER.AUTH_STARTED,{provider:$})}function zf(f,$){u(f,x.USER.AUTH_SUCCEEDED,{provider:$})}function Mf(f,$,J){u(f,x.USER.AUTH_FAILED,{provider:$,errorMessage:W8(J)})}function H$(f,$,J){u(f,x.USER.AUTH_LOGGED_OUT,{provider:$,reason:J})}function NV(f,$){u(f,x.USER.PROVIDER_CONFIGURED,{provider:$})}function mZ(f,$){f?.captureRequired(x.USER.TELEMETRY_OPT_OUT,$)}function Nf(f,$){let J=$.id?.trim();if(J)f?.setDistinctId(J);f?.updateCommonProperties({account_id:$.id,account_email:$.email,provider:$.provider,organization_id:$.organizationId,organization_name:$.organizationName,member_id:$.memberId})}function t4(f,$){u(f,x.TASK.CREATED,$)}function s4(f,$){u(f,x.TASK.RESTARTED,$)}function j8(f,$){u(f,x.TASK.COMPLETED,$)}function E1(f,$){u(f,x.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function o4(f,$){u(f,x.TASK.TOKEN_USAGE,$)}function e4(f,$,J){u(f,x.TASK.MODE_SWITCH,{ulid:$,mode:J})}function f6(f,$){u(f,x.TASK.TOOL_USED,$)}function $6(f,$){u(f,x.TASK.SKILL_USED,$)}function J6(f,$){u(f,x.TASK.DIFF_EDIT_FAILED,$)}function H8(f,$){u(f,x.TASK.PROVIDER_API_ERROR,{...$,errorMessage:W8($.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function vZ(f,$){u(f,x.SDK.TOOL_TIMEOUT,qV($))}function qV(f){let $={};for(let[J,Q]of Object.entries(f))if(Q!==void 0)$[J]=Q;return $}function Q6(f,$,J){u(f,x.TASK.MENTION_USED,{mentionType:$,contentLength:J,timestamp:new Date().toISOString()})}function Z6(f,$,J,Q){u(f,x.TASK.MENTION_FAILED,{mentionType:$,errorType:J,errorMessage:W8(Q),timestamp:new Date().toISOString()})}function W6(f,$,J,Q,Z){u(f,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:J,searchType:Q,isEmpty:Z,timestamp:new Date().toISOString()})}function X$(f,$){u(f,x.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function j6(f,$){u(f,x.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function X8(f,$){u(f,$.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function H6(f,$,J,Q){u(f,x.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:J,workspaceCount:Q,totalCount:J+Q,timestamp:new Date().toISOString()})}function X6(f,$){u(f,x.TASK.COMPACTION_EXECUTED,{...$,timestamp:new Date().toISOString()})}function A6(f,$){u(f,x.TASK.COMPACTION_SKIPPED,{...$,timestamp:new Date().toISOString()})}var OV=500,x;var V0=j$(()=>{x={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:LV,TOOL_TIMEOUT:"sdk.tool_timeout"}}});import{mkdirSync as PK,readFileSync as GK,statSync as FK,writeFileSync as UK}from"node:fs";import{dirname as RK}from"node:path";import{resolveGlobalSettingsPath as IW}from"@cline/shared/storage";import{z as s$}from"zod";function M8(){return q8.parse({})}function DK(){N8=void 0}function LK(f){if(f.disabledTools)Object.freeze(f.disabledTools);if(f.disabledPlugins)Object.freeze(f.disabledPlugins);return Object.freeze(f)}function OK(f){let $;try{$=GK(f,"utf8")}catch{return M8()}try{let J=q8.safeParse(JSON.parse($));return J.success?J.data:M8()}catch{return M8()}}function _K(){let f=IW(),$=FK(f,{throwIfNoEntry:!1}),J=$?.mtimeMs??0,Q=$?.size??0,Z=N8;if(Z&&Z.path===f&&Z.mtimeMs===J&&Z.size===Q)return Z;let W=LK($?OK(f):M8());return N8={path:f,mtimeMs:J,size:Q,value:W},N8}function T0(){return _K().value}function wf(f,$={}){let J=IW(),Q=T0();PK(RK(J),{recursive:!0});let Z=q8.parse(f);if(!Q.telemetryOptOut&&Z.telemetryOptOut)mZ($.telemetry);UK(J,`${JSON.stringify(Z,null,2)}
2
+ `,"utf8"),DK()}function g6(){return T0().telemetryOptOut}function TK(f,$={}){wf({...T0(),telemetryOptOut:f},$)}function zK(){return T0().autoUpdateEnabled}function MK(f,$={}){wf({...T0(),autoUpdateEnabled:f},$)}function Yf(f){return new Set(f??T0().disabledTools??[])}function y8(f){return new Set(f??T0().disabledPlugins??[])}function NK(f){return Yf().has(f)}function m6(f){let $=T0(),J=new Set($.disabledTools??[]),Q=J.has(f);if(Q)J.delete(f);else J.add(f);return wf({...$,disabledTools:[...J]}),!Q}function xW(f,$){let J=[...new Set(f.map((W)=>W.trim()).filter(Boolean))];if(J.length===0)return;let Q=T0(),Z=Yf(Q.disabledTools);for(let W of J)if($)Z.add(W);else Z.delete(W);wf({...Q,disabledTools:[...Z]})}function gW(f,$){return xW([f],$),$}function qK(f){return y8().has(f)}function yK(f,$){let J=f.trim();if(!J)return;let Q=T0(),Z=y8(Q.disabledPlugins);if($)Z.add(J);else Z.delete(J);wf({...Q,disabledPlugins:[...Z]})}function v6(f,$){let J=y8($);if(J.size===0)return[...f];return f.filter((Q)=>!J.has(Q))}function o$(f,$){let J=Yf($);if(J.size===0)return[...f];return f.filter((Q)=>!J.has(Q.name))}function c6(f,$){if(!f||f.length===0)return f;let J=Yf($);if(J.size===0)return f;return f.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 kW,q8,N8;var t0=j$(()=>{V0();kW=s$.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,s$.array(s$.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,Q)=>J.localeCompare(Q));return $.length>0?$:void 0}),q8=s$.object({telemetryOptOut:s$.boolean().default(!1).catch(!1),autoUpdateEnabled:s$.boolean().default(!0).catch(!0),disabledTools:kW.optional(),disabledPlugins:kW.optional()}).strip().transform((f)=>{let $={autoUpdateEnabled:f.autoUpdateEnabled,telemetryOptOut:f.telemetryOptOut};if(f.disabledTools?.length)$.disabledTools=f.disabledTools;if(f.disabledPlugins?.length)$.disabledPlugins=f.disabledPlugins;return $})});var G3={};p4(G3,{normalizeUserMessage:()=>hF,buildInitialUserContent:()=>EF});async function EF(f,$,J,Q){let Z=bF($),W=await IF(J,Q);if(Z.length===0&&!W)return f;let j=[{type:"text",text:f},...Z];if(W)j.push(...W);return j}function hF(f){if(f==null)return"";if(typeof f==="string")return f;let $=f.content;if(typeof $==="string")return $;if(!Array.isArray($))return"";let J=[];for(let Q of $)if(Q&&typeof Q==="object"&&Q.type==="text"){let Z=Q.text;if(typeof Z==="string")J.push(Z)}return J.join(`
3
+ `)}function bF(f){if(!f||f.length===0)return[];let $=[];for(let J of f){let Q=kF(J);if(Q)$.push(Q)}return $}function kF(f){let $=f.trim();if(!$)return;let J=$.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:$}}async function IF(f,$){if(!f||f.length===0)return;let J=$??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all(f.map(async(Z)=>{let W=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:W,content:j}}catch(j){let H=j instanceof Error?j.message:String(j);return{type:"file",path:W,content:`Error fetching content: ${H}`}}}));if(Q.length===0)return;return Q}var Wj={};p4(Wj,{updateMcpServerOAuthState:()=>X2,setMcpServerDisabled:()=>j2,resolveMcpServerRegistrations:()=>xf,resolveDefaultMcpSettingsPath:()=>b0,registerMcpServersFromSettingsFile:()=>A2,normalizeMcpServerOAuthState:()=>K1,loadMcpSettingsFile:()=>W2,listMcpServerOAuthStatuses:()=>p5,hasMcpSettingsFile:()=>D$,getMcpServerOAuthState:()=>H2});import{existsSync as TU,mkdirSync as e3,readFileSync as d5,writeFileSync as fj}from"node:fs";import{dirname as $j}from"node:path";import{resolveMcpSettingsPath as zU}from"@cline/shared/storage";import{z as q}from"zod";function u5(f){if(!f)return;if(f==="http")return"streamableHttp";return f}function b0(){return zU()}function kU(f){let $=d5(f,"utf8"),J;try{J=JSON.parse($)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${f}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${f}": expected object.`);return J}function Zj(f,$){if(!Object.hasOwn(f,$))return;let J=f[$];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function IU(f,$,J){Object.defineProperty(f,$,{value:J,enumerable:!0,configurable:!0,writable:!0})}function W2(f={}){let $=f.filePath??b0(),J=d5($,"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 "${$}": ${j}`)}let Z=bU.safeParse(Q);if(!Z.success){let W=Z.error.issues.map((j)=>{let H=j.path.join(".");return H?`${H}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${$}": ${W}`)}return Z.data}function xU(f){let $=d5(f,"utf8"),J;try{J=JSON.parse($)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${f}": expected object`);let Q=J,Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object`);return Q}function K1(f){if(!f)return;let $={...f.clientInformation?{clientInformation:f.clientInformation}:{},...f.tokens?{tokens:f.tokens}:{},...f.codeVerifier?{codeVerifier:f.codeVerifier}:{},...f.discoveryState?{discoveryState:f.discoveryState}:{},...f.redirectUrl?{redirectUrl:f.redirectUrl}:{},...f.lastError?{lastError:f.lastError}:{},...f.lastAuthenticatedAt?{lastAuthenticatedAt:f.lastAuthenticatedAt}:{}};return Object.keys($).length>0?$:void 0}function gU(f){if(f===void 0)return;let $=l5.safeParse(f);if(!$.success)return;return K1($.data)}function D$(f={}){let $=f.filePath??b0();return TU($)}function xf(f={}){let $=W2(f);return Object.entries($.mcpServers).map(([J,Q])=>({name:J,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function j2(f){let $=f.filePath??b0(),J=f.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=kU($),Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object.`);let W={...Z},j=Zj(W,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let H={...j};if(f.disabled)H.disabled=!0;else delete H.disabled;IU(W,J,H),e3($j($),{recursive:!0}),fj($,`${JSON.stringify({...Q,mcpServers:W},null,2)}
4
+ `)}function H2(f,$={}){let J=W2($);if(!Object.hasOwn(J.mcpServers,f))return;return K1(J.mcpServers[f]?.oauth)}function X2(f,$,J={}){let Q=J.filePath??b0(),Z=xU(Q),W=Z.mcpServers,j=Zj(W,f);if(!j)throw Error(`Unknown MCP server: ${f}`);let H=gU(j.oauth)??{},X=K1($(H));if(X)j.oauth=X;else delete j.oauth;return e3($j(Q),{recursive:!0}),fj(Q,`${JSON.stringify(Z,null,2)}
5
+ `,"utf8"),X??{}}function p5(f={}){return xf(f).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 A2(f,$={}){let J=xf($);for(let Q of J)await f.registerServer(Q);return J}var Z2,Jj,l5,MU,NU,qU,yU,wU,CU,Qj,SU,EU,hU,bU;var FJ=j$(()=>{Z2=q.record(q.string(),q.string()),Jj=q.record(q.string(),q.unknown()),l5=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(),MU=q.object({type:q.literal("stdio"),command:q.string().min(1),args:q.array(q.string()).optional(),cwd:q.string().min(1).optional(),env:Z2.optional()}),NU=q.object({type:q.literal("sse"),url:q.string().url(),headers:Z2.optional()}),qU=q.object({type:q.literal("streamableHttp"),url:q.string().url(),headers:Z2.optional()}),yU=q.discriminatedUnion("type",[MU,NU,qU]),wU=q.object({transport:yU,disabled:q.boolean().optional(),metadata:Jj.optional(),oauth:l5.optional()}),CU=q.enum(["stdio","sse","http","streamableHttp"]).optional(),Qj=q.object({type:q.enum(["stdio","sse","streamableHttp"]).optional(),transportType:CU,disabled:q.boolean().optional(),metadata:Jj.optional(),oauth:l5.optional()});SU=Qj.extend({command:q.string().min(1),args:q.array(q.string()).optional(),cwd:q.string().min(1).optional(),env:Z2.optional()}).superRefine((f,$)=>{let J=f.type??u5(f.transportType);if(J&&J!=="stdio")$.addIssue({code:q.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((f)=>({transport:{type:"stdio",command:f.command,args:f.args,cwd:f.cwd,env:f.env},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth})),EU=Qj.extend({url:q.string().url(),headers:Z2.optional()}).superRefine((f,$)=>{let J=f.type??u5(f.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")$.addIssue({code:q.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((f)=>{if((f.type??u5(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth}}),hU=q.union([wU,SU,EU]),bU=q.object({mcpServers:q.record(q.string(),hU)}).passthrough()});import{existsSync as f_,mkdirSync as $_,readFileSync as J_,writeFileSync as Q_}from"node:fs";import{resolve as Z_}from"node:path";import{resolveSessionDataDir as W_}from"@cline/shared/storage";import{nanoid as j_}from"nanoid";import*as H_ from"node-machine-id";function S$(f){let $=f?.trim();if($)return $;let J=Y_();if(J)return J;return V_()}function A_(){let f=H_;return f.machineIdSync??f.default?.machineIdSync}function Y_(){try{let f=A_();if(!f)return;return f().trim()||void 0}catch{return}}function V_(){let f=W_(),$=Z_(f,X_);try{if(f_($)){let Q=J_($,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${j_()}`;try{$_(f,{recursive:!0}),Q_($,J,"utf8")}catch{}return J}var X_="machine-id";var vJ=()=>{};class t2{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(f){this.name=f.name??"OpenTelemetryAdapter",this.metadata={...f.metadata},this.meterProvider=f.meterProvider,this.loggerProvider=f.loggerProvider,this.meter=f.meterProvider?.getMeter("cline")??null,this.logger=f.loggerProvider?.getLogger("cline")??null,this.enabled=f.enabled??!0,this.distinctId=f.distinctId,this.commonProperties=f.commonProperties?{...f.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(f);if(!W)W=this.meter.createCounter(f,Q?{description:Q}:void 0),this.counters.set(f,W);W.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get(f);if(!W)W=this.meter.createHistogram(f,Q?{description:Q}:void 0),this.histograms.set(f,W);W.record($,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),H=this.gaugeValues.get(f);if($===null){if(H){if(H.delete(j),H.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let X=H;if(!X)X=new Map,this.gaugeValues.set(f,X);if(!this.gauges.has(f)){let A=this.meter.createObservableGauge(f,Q?{description:Q}:void 0);A.addCallback((Y)=>{for(let V of this.snapshotGaugeSeries(f))Y.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set(f,A)}X.set(j,{value:$,attributes:W})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(f){this.distinctId=f}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}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($,J));this.logger.emit({severityText:"INFO",body:f,attributes:Q})}buildAttributes(f,$=!1){return{...this.commonProperties,...this.metadata,...f,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(f){let $=this.gaugeValues.get(f);if(!$)return[];return Array.from($.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties(f,$="",J=new WeakSet,Q=0){if(!f)return{};let Z={},W=100,j=10;for(let[H,X]of Object.entries(f)){if(H==="__proto__"||H==="constructor"||H==="prototype")continue;let A=$?`${$}.${H}`:H;if(X===null||X===void 0){Z[A]=String(X);continue}if(Array.isArray(X)){let Y=X.length>W?X.slice(0,W):X;try{Z[A]=JSON.stringify(Y)}catch{Z[A]="[UnserializableArray]"}if(X.length>W)Z[`${A}_truncated`]=!0,Z[`${A}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){Z[A]=X.toISOString();continue}if(X instanceof Error){Z[A]=X.message;continue}if(J.has(X)){Z[A]="[Circular]";continue}if(Q>=j){Z[A]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(Z,this.flattenProperties(X,A,J,Q+1));continue}if(GN(X)){Z[A]=X;continue}try{Z[A]=JSON.stringify(X)}catch{Z[A]=String(X)}}return Z}}function GN(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class w4{name;logger;enabled;constructor(f={}){this.name=f.name??"TelemetryLoggerSink",this.logger=f.logger,this.enabled=f.enabled??!0}emit(f,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:f,properties:$})}emitRequired(f,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:f,properties:$})}recordCounter(f,$,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,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:f,value:$,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:f,value:$,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class s2{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new w4({logger:f.logger}));this.metadata={...f.metadata??{}},this.distinctId=f.distinctId,this.commonProperties={...f.commonProperties??{}}}addAdapter(f){this.adapters.push(f)}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return this.adapters.some((f)=>f.isEnabled())}capture(f){let $=this.buildAttributes(f.properties);for(let J of this.adapters)J.emit(f.event,$)}captureRequired(f,$){let J=this.buildAttributes($);for(let Q of this.adapters)Q.emitRequired(f,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((f)=>f.flush()))}async dispose(){await Promise.all(this.adapters.map((f)=>f.dispose()))}buildAttributes(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var oQ=()=>{};import{metrics as FN,trace as UN}from"@opentelemetry/api";import{logs as RN}from"@opentelemetry/api-logs";import{OTLPLogExporter as DN}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as LN}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as ON}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as _N}from"@opentelemetry/resources";import{BatchLogRecordProcessor as TN,ConsoleLogRecordExporter as zN,LoggerProvider as MN}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as NN,MeterProvider as qN,PeriodicExportingMetricReader as uA}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as yN,ConsoleSpanExporter as wN,SimpleSpanProcessor as CN}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as SN}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as EN,ATTR_SERVICE_VERSION as hN}from"@opentelemetry/semantic-conventions";class dA{distinctId;metadata;commonProperties;constructor(f={}){this.distinctId=f.distinctId,this.metadata={...f.metadata??{}},this.commonProperties={...f.commonProperties??{}}}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return!1}capture(f){this.resolveProperties(f.properties)}captureRequired(f,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class o2{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=_N({[EN]:f.serviceName??"cline",...f.serviceVersion?{[hN]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)FN.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)RN.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return UN.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new t2({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new s2({...f,adapters:[$],distinctId:S$(f.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(f){let $=eQ(this.options.metricsExporter);if($.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=$.map((W)=>IN(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 qN({resource:f,readers:Z})}createTracerProvider(f){let $=eQ(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of $){let j=kN(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 SN({resource:f,spanProcessors:Z})}createLoggerProvider(f){let $=eQ(this.options.logsExporter);if($.length===0)return null;let J=$.map((Q)=>{let Z=bN(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new TN(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 MN({resource:f,processors:J})}}function C4(f){let $=new o2(f),J=$.createTelemetryService(f);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:f.enabled??!0,logsExporter:Array.isArray(f.logsExporter)?f.logsExporter.join(","):f.logsExporter,metricsExporter:Array.isArray(f.metricsExporter)?f.metricsExporter.join(","):f.metricsExporter,tracesExporter:Array.isArray(f.tracesExporter)?f.tracesExporter.join(","):f.tracesExporter,otlpProtocol:f.otlpProtocol,hasOtlpEndpoint:Boolean(f.otlpEndpoint),serviceName:f.serviceName,serviceVersion:f.serviceVersion}),{provider:$,telemetry:J}}function m$(f){if(g6())return{telemetry:new dA(f)};if(f.enabled!==!0)return{telemetry:new s2({...f,distinctId:S$(f.distinctId)})};return C4(f)}function S4(f){let{telemetry:$,provider:J}=m$(f);return{telemetry:$,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function eQ(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function bN(f,$){if(f==="console")return new zN;if(!$.endpoint)return null;let J=fZ($.endpoint,"/v1/logs");return new DN({url:J,headers:$.headers})}function kN(f,$){if(f==="console")return new CN(new wN);if(!$.endpoint)return null;let J=fZ($.endpoint,"/v1/traces");return new yN(new ON({url:J,headers:$.headers}))}function IN(f,$){if(f==="console")return new uA({exporter:new NN,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=fZ($.endpoint,"/v1/metrics");return new uA({exporter:new LN({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function fZ(f,$){let J=new URL(f),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith($)?Q:`${Q}${$}`,J.toString()}var E4=j$(()=>{t0();vJ();oQ()});var xY={};p4(xY,{createOpenTelemetryTelemetryService:()=>C4,createConfiguredTelemetryService:()=>m$,createConfiguredTelemetryHandle:()=>S4,OpenTelemetryProvider:()=>o2,OpenTelemetryAdapter:()=>t2});var UZ=j$(()=>{E4()});import*as xr from"@cline/llms";import{buildClineSystemPrompt as mr,buildSdkErrorProperties as vr,ContributionRegistry as cr,captureSdkError as ur,createClineTelemetryServiceConfig as dr,createClineTelemetryServiceMetadata as lr,createContributionRegistry as pr,createTool as rr,emptyWorkspaceManifest as ir,formatDisplayUserInput as nr,noopBasicLogger as ar,normalizeSdkError as tr,normalizeUserInput as sr,parseUserCommandEnvelope as or,registerDisposable as er,SDK_ERROR_TELEMETRY_EVENT as fi}from"@cline/shared";export*from"@cline/shared/storage";function DV(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function kZ(f,$,J){let Q=DV(J);if(Q)return Q;let Z=$.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${f}: ${W}`}return`Cline account request failed with status ${f}`}class r4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(f){let $=f.apiBaseUrl.trim();if(!$)throw Error("apiBaseUrl is required");this.apiBaseUrl=$,this.getAuthTokenFn=f.getAuthToken,this.getCurrentUserIdFn=f.getCurrentUserId,this.getOrganizationMemberIdFn=f.getOrganizationMemberId,this.getHeadersFn=f.getHeaders,this.requestTimeoutMs=f.requestTimeoutMs??30000,this.fetchImpl=f.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(f){let $=await this.resolveUserId(f);return this.request(`/api/v1/users/${encodeURIComponent($)}/balance`)}async fetchUsageTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/usages`)).items??[]}async fetchPaymentTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}`)}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}/balance`)}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId($,f.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent($)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount(f){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:f?.trim()||null},expectNoContent:!0})}async resolveUserId(f){let $=f?.trim();if($)return $;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=$?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((H)=>H.organizationId===f)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);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(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:Z.signal});if(j.status===204||$?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let H=await j.text(),X;if(H.trim())try{X=JSON.parse(H)}catch{if(!j.ok)throw Error(kZ(j.status,H,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(kZ(j.status,H,X));if(typeof X==="object"&&X!==null){let A=X;if(typeof A.success==="boolean"){if(!A.success)throw Error(A.error||"Cline account request failed");if(A.data!==void 0)return A.data}}if(X===void 0||X===null)throw Error("Cline account response payload was empty");return X}finally{clearTimeout(W)}}}function IZ(f){return f.action==="clineAccount"}async function xZ(f,$){switch(f.operation){case"fetchMe":return $.fetchMe();case"fetchBalance":return $.fetchBalance(f.userId);case"fetchUsageTransactions":return $.fetchUsageTransactions(f.userId);case"fetchPaymentTransactions":return $.fetchPaymentTransactions(f.userId);case"fetchUserOrganizations":return $.fetchUserOrganizations();case"fetchOrganizationBalance":return $.fetchOrganizationBalance(f.organizationId);case"fetchOrganizationUsageTransactions":return $.fetchOrganizationUsageTransactions({organizationId:f.organizationId,memberId:f.memberId});case"switchAccount":return await $.switchAccount(f.organizationId),{updated:!0};case"fetchFeaturebaseToken":return $.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String(f)}`)}}class i4{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}function Z8(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((Q)=>{f.onOpenUrlError?.({url:$,error:Q})})}catch(Q){f.onOpenUrlError?.({url:$,error:Q})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}V0();import{getClineEnvironmentConfig as Y6}from"@cline/shared";function yV(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function Xf(f){let $=await import("node:http"),J=f.host??"127.0.0.1",Q=f.timeoutMs??300000,Z=f.successHtml??wV,W=yV(),j=!1,H=null,X=null,A=null,Y=(K)=>{if(j)return;j=!0,W.resolve(K)},V=()=>{if(H)clearTimeout(H),H=null;let K=A;if(A=null,X)X.close(),X=null;if(K!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return H=setTimeout(()=>{V(),Y(null)},Q),W.promise};for(let K of f.ports){let P=$.createServer((G,F)=>{try{let U=new URL(G.url||"",`http://${J}:${K}`);if(U.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let _={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(_.error){F.statusCode=400,F.end(`Authentication failed: ${_.error}`),V(),Y(_);return}if(!_.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&_.state!==f.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(Z),V(),Y(_)}catch{F.statusCode=500,F.end("Internal error")}}),R=await new Promise((G)=>{let F=(U)=>{P.off("error",F),G({bound:!1,error:U})};P.once("error",F),P.listen(K,J,()=>{P.off("error",F),X=P,G({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){A=K;let G=`http://${J}:${K}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:K,callbackUrl:G})).catch(()=>{});return{callbackUrl:G,waitForCallback:B,cancelWait:()=>{V(),Y(null)},close:()=>{V(),Y(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var wV=`<!DOCTYPE html>
6
6
  <html lang="en">
7
7
  <head>
8
8
  <meta charset="utf-8">
@@ -43,18 +43,18 @@ import{createRequire as pY}from"node:module";var cY=Object.defineProperty;var dY
43
43
  </div>
44
44
  <script>setTimeout(() => window.close(), 3000);</script>
45
45
  </body>
46
- </html>`;function _9($){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 WV($){let J=new TextEncoder().encode($),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function ZV($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),_9(f)}async function o2(){let $=ZV(),f=_9(await WV($));return{verifier:$,challenge:f}}function e2($){return $.endsWith("/")?$.slice(0,-1):$}function Z1($,f){return new URL(f,`${e2($)}/`).toString()}function v1($,f={}){let J=$.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:f.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[W,Z]=J.split("#",2);return{code:W||void 0,state:Z||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:f.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function QV($){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 P0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),Z=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=QV(Z);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function u1($){try{let f=JSON.parse($),J=f.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:Z}}catch{return{}}}function Q1($,f){return Date.now()>=$.expires-f}async function c1($){if(!$.onManualCodeInput){let Q=await $.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let f,J,W=$.onManualCodeInput().then((Q)=>{f=Q,$.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return v1(f,$.parseOptions);if(await W,J)throw J;if(f)return v1(f,$.parseOptions);return{}}var $8={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},y9={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},f6="https://api.workos.com",jV="/auth",T9=Array.from({length:11},($,f)=>48801+f),HV=300000,XV=30000,d1=30000,AV=300,YV=5;class z$ 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 VV($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function J6($,f,J={}){let W=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:VV($.expiresAt),accountId:W??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function W6($){if(!$)return{};return typeof $==="function"?await $():$}function N9($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function M9($){await new Promise((f)=>setTimeout(f,$))}function Z6($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function q9($,f){let J=await fetch(Z1(f6,y9.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??d1)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new z$(`Device authorization failed: ${J.status}${W.error_description?` - ${W.error_description}`:""}`,{status:J.status,errorCode:W.error});if(!W.device_code||!W.user_code||!W.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:W.device_code,userCode:W.user_code,verificationUri:W.verification_uri,verificationUriComplete:W.verification_uri_complete,expiresInSeconds:N9(W.expires_in,AV),pollIntervalSeconds:N9(W.interval,YV)}}async function w9($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let W=await fetch(Z1($.workosApiBaseUrl,y9.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await W.json().catch(()=>({}));if(W.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await M9(J*1000);break}case"slow_down":{J+=1,await M9(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new z$(Z.error_description||"WorkOS authorization failed",{status:W.status,errorCode:Z.error});default:throw new z$(`WorkOS token polling failed: ${W.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:W.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function S9($,f,J){let W={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(Z1(f.apiBaseUrl,$8.register),{method:"POST",headers:{"Content-Type":"application/json",...await W6(f.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(f.requestTimeoutMs??d1)});if(!Z.ok){let j=await Z.text().catch(()=>""),H=u1(j);throw new z$(`Token registration failed: ${Z.status}${H.message?` - ${H.message}`:""}`,{status:Z.status,errorCode:H.code})}let Q=await Z.json();return J6(Z6(Q,"Invalid token exchange response"),J??f.provider)}async function BV($,f,J,W){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:W??J.provider},Q=await fetch(Z1(J.apiBaseUrl,$8.token),{method:"POST",headers:{"Content-Type":"application/json",...await W6(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??d1)});if(!Q.ok){let H=await Q.text().catch(()=>""),X=u1(H);throw new z$(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let j=await Q.json();return J6(Z6(j,"Invalid token exchange response"),W??J.provider)}async function f8($){R$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:T9,W=$.callbackPath??jV,Z=f?null:await W$({ports:J,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Q=Z?.callbackUrl||`http://127.0.0.1:${J[0]??T9[0]}${W}`;try{let j;if(f){let H=$6().workOsClientId,X=await q9(H,$);$.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await w9({clientId:H,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??d1,workosApiBaseUrl:f6,onProgress:$.callbacks.onProgress});j=await S9(A,$,$.provider)}else{let H=new URL(Z1($.apiBaseUrl,$8.authorize));H.searchParams.set("client_type","extension"),H.searchParams.set("callback_url",Q),H.searchParams.set("redirect_uri",Q),$.callbacks.onAuth({url:H.toString(),instructions:"Continue the authentication process in your browser."});let X,A=$.provider,Y=await c1({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(Y.error)throw Error(`OAuth error: ${Y.error}`);if(X=Y.code,A=Y.provider??A,!X){let V=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=v1(V,{includeProvider:!0});X=B.code,A=B.provider??A}if(!X)throw Error("Missing authorization code");j=await BV(X,Q,$,A)}return D$($.telemetry,$.provider??"cline"),O$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw L$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function KV($){return await q9($6().workOsClientId,$)}async function GV($){let f=$.provider??"cline";R$($.telemetry,f);try{let J=await w9({clientId:$6().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??d1,workosApiBaseUrl:f6}),W=await S9(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return D$($.telemetry,f),O$($.telemetry,{id:W.accountId,email:W.email,provider:f}),W}catch(J){throw L$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function Q6($,f){let J=await fetch(Z1(f.apiBaseUrl,$8.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await W6(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??d1)});if(!J.ok){let Q=await J.text().catch(()=>""),j=u1(Q);throw new z$(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let W=await J.json(),Z=$.metadata?.provider??f.provider;return J6(Z6(W,"Invalid token refresh response"),Z,$)}async function j6($,f,J){if(!$)return null;let W=J?.refreshBufferMs??HV,Z=J?.retryableTokenGraceMs??XV;if(J?.forceRefresh!==!0&&!Q1($,W))return $;try{return await Q6($,f)}catch(j){if(j instanceof z$&&j.isLikelyInvalidGrant())return J1(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function PV($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return f8({...$,callbacks:f})},async refreshToken(f){return Q6(f,$)},getApiKey(f){return`workos:${f.access}`}}}B0();import{nanoid as UV}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 J8 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 FV($,f,J=t.redirectUri){let W=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(!W.ok)return{type:"failed"};let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function RV($){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 W=await f.text().catch(()=>""),Z=u1(W);throw new J8(`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 J8)throw f;return{type:"failed"}}}async function DV($="pi"){let{verifier:f,challenge:J}=await o2(),W=UV(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",W),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:W,url:Z.toString()}}function LV(){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 h9($,f){let J=f?P0(f):P0($),W=J?J:P0($),Q=W?.[t.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let j=W?.organizations;if(Array.isArray(j)&&j.length>0){let X=j[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let H=W?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;return null}function C9($,f){let J=h9($.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 W8($){R$($.telemetry,"openai-codex");let f=LV(),{verifier:J,state:W,url:Z}=await DV($.originator),Q=await W$({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:W});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let H=await c1({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(H.state&&H.state!==W)throw Error("State mismatch");if(j=H.code,!j){let Y=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=v1(Y,{allowHashCodeState:!0});if(V.state&&V.state!==W)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let X=await FV(j,J,f.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=C9(X);return D$($.telemetry,"openai-codex"),O$($.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(H){throw L$($.telemetry,"openai-codex",H instanceof Error?H.message:String(H)),H}finally{Q.close()}}async function H6($,f){let J=await RV($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=C9(J,f);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function X6($,f){if(!$)return null;let J=f?.refreshBufferMs??t.refreshBufferMs,W=f?.retryableTokenGraceMs??t.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!Q1($,J))return $;try{return await H6($.refresh,$)}catch(Q){if(Q instanceof J8&&Q.isLikelyInvalidGrant())return J1(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}function OV($,f=t.refreshBufferMs){return Q1($,f)}function zV($){let f=$.accountId??h9($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var _V={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return W8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return H6($.refresh,$)},getApiKey($){return $.access}};B0();import{nanoid as E9}from"nanoid";class A6{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+W})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var TV="a8331954c0cf48ba99b5dd223a14c6ea",NV="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",MV="openid offline_access",V6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",yV="c1aba3deed5740659981a752714eba33",qV="https://login-ext.identity.oraclecloud.com",wV="openid offline_access",B6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",SV="opc-request-id",hV="/auth/oca",CV=Array.from({length:11},($,f)=>48801+f),EV=300000,bV=30000,b9=30000,kV=600000;class Z8 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 _$={internal:{clientId:TV,idcsUrl:NV,scopes:MV,baseUrl:V6},external:{clientId:yV,idcsUrl:qV,scopes:wV,baseUrl:B6}},Mf=new Map,IV=86400000,xV=300000,mV=32,Y6=new A6(IV,mV);function k9($){if(typeof $==="function")return $();return $??"internal"}function I9($){return{internal:{clientId:$?.internal?.clientId??_$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??_$.internal.idcsUrl,scopes:$?.internal?.scopes??_$.internal.scopes,baseUrl:$?.internal?.baseUrl??_$.internal.baseUrl},external:{clientId:$?.external?.clientId??_$.external.clientId,idcsUrl:$?.external?.idcsUrl??_$.external.idcsUrl,scopes:$?.external?.scopes??_$.external.scopes,baseUrl:$?.external?.baseUrl??_$.external.baseUrl}}}function gV($=Date.now()){let f=$-kV;for(let[J,W]of Mf.entries())if(W.createdAt<f)Mf.delete(J)}function vV($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=P0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=P0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function x9($,f,J){let W=$.access_token;if(!W)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let Q=P0($.id_token),j=P0(W),H=Q?.sub??j?.sub,X=Q?.email??j?.email;return{access:W,refresh:Z,expires:vV($,W,$.id_token),accountId:H??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:H,idToken:$.id_token}}}async function m9($,f){let J=e2($),W=Y6.get(J);if(W)return W;let Z=`${J}/.well-known/openid-configuration`,Q=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!Q.ok){let X=`${J}/oauth2/v1/token`;return Y6.set(J,X,Date.now(),xV),X}let H=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return Y6.set(J,H),H}function g9($){return{code:$.error,message:$.error_description}}async function uV($){let f=Mf.get($.state);if(!f)throw Error("No PKCE verifier found for this state");Mf.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,W=await m9(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await Q.json();if(!Q.ok){let X=g9(j);throw new Z8(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let H=P0(j.id_token);if(!j.id_token||!H)throw Error("No ID token received from OCA");if(H.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return x9(j,$.mode)}function cV($){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 Q8($){R$($.telemetry,"oca");let f=I9($.config),J=k9($.mode),W=$.callbackPorts?.length?$.callbackPorts:CV,Z=$.callbackPath??hV,Q=$.requestTimeoutMs??b9,j=await W$({ports:W,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),H=j.callbackUrl;if(!H)throw Error("Unable to bind local OAuth callback server");let X=E9(16),A=E9(16),{verifier:Y,challenge:V}=await o2();gV(),Mf.set(X,{verifier:Y,nonce:A,mode:J,redirectUri:H,createdAt:Date.now()});let B=cV({callbackUrl:H,mode:J,state:X,nonce:A,challenge:V,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await c1({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!==X)throw Error("State mismatch");let P=await uV({code:G,state:R,mode:J,config:f,requestTimeoutMs:Q});return D$($.telemetry,"oca"),O$($.telemetry,{id:P.accountId,email:P.email,provider:"oca"}),P}catch(K){throw L$($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function K6($,f={}){let J=I9(f.config),W=f.requestTimeoutMs??b9,Z=$.metadata?.mode,Q=Z==="internal"||Z==="external"?Z:k9(f.mode),j=Q==="external"?J.external:J.internal,H=await m9(j.idcsUrl,W),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),A=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(W)}),Y=await A.json();if(!A.ok){let V=g9(Y);throw new Z8(`Token refresh failed: ${A.status}${V.message?` - ${V.message}`:""}`,{status:A.status,errorCode:V.code})}return x9(Y,Q,$)}async function G6($,f,J){if(!$)return null;let W=f?.refreshBufferMs??J?.refreshBufferMs??EV,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??bV;if(f?.forceRefresh!==!0&&!Q1($,W))return $;try{return await K6($,J)}catch(j){if(j instanceof Z8&&j.isLikelyInvalidGrant())return J1(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function dV($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return Q8({...$,callbacks:f})},async refreshToken(f){return K6(f,$)},getApiKey(f){return f.access}}}async function v9($,f){let J=new TextEncoder,W=async(A)=>{let Y=await crypto.subtle.digest("SHA-256",J.encode(A));return Array.from(new Uint8Array(Y).slice(0,4),(V)=>V.toString(16).padStart(2,"0")).join("")},[Z,Q]=await Promise.all([W(f),W($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),H=new Uint32Array(1);crypto.getRandomValues(H);let X=(H[0]??0).toString(16).padStart(8,"0");return Z+Q+j+X}async function lV($){let f=await v9($.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",[SV]:f}}import*as y0 from"@cline/llms";import{z as N}from"zod";import*as e from"@cline/llms";function P6($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter((f)=>f.length>0)}function pV($,f){let J=P6($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let W=$,Z=P6(W.data??W.models);if(Z.length>0)return Z;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let j=Object.keys(W.models).filter((H)=>H.trim().length>0);if(j.length>0)return j}let Q=W.providers?.[f];if(Q&&typeof Q==="object"){let H=P6(Q.models??Q);if(H.length>0)return H}return[]}async function j8($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return pV(await J.json(),f)}function u9($){return $.replace(/\/+$/,"")}function H8($,f,J){let W=J?.trim();if(!W)return;let Z=$?.trim();if(!Z||!f?.trim())return W;try{let Q=new URL(W),j=new URL(f),H=new URL(Z);if(Q.origin!==j.origin)return W;let X=u9(j.pathname),A=u9(H.pathname);if(X&&Q.pathname.startsWith(`${X}/`)){let Y=Q.pathname.slice(X.length);H.pathname=`${A}${Y}`}else H.pathname=Q.pathname;return H.search=Q.search,H.hash=Q.hash,H.toString()}catch{return W}}function rV($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function iV($){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 nV=Object.values(e.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:rV($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),l9=Object.fromEntries(nV.map(($)=>[$.id,$]));function aV($){return l9[$]}function tV(){return Object.fromEntries(Object.entries(l9).filter(([,$])=>iV($)))}function p9($=[]){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 r9="https://models.dev/api.json",sV=600000,i9=300000,oV=5000,A8=new Map,yf=new Map,F6=new Map,X8=new Map;async function eV(){return e.getGeneratedProviderModels()}async function $B($,f={},J={},W={},Z={},Q={}){let j=await eV(),H=e.resolveProviderModelCatalogKeys($),X=Object.assign({},...H.map((V)=>j[V]??{})),A=Boolean(e.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),Y=Object.keys(Z).length>0;if(A&&Y)return e.sortModelsByReleaseDate({...Z,...Q});if($==="openai-codex")return e.sortModelsByReleaseDate({...f,...e.filterOpenAICodexModels(J),...Z,...Q});return e.sortModelsByReleaseDate({...X,...f,...J,...W,...Z,...Q})}function fB($,f){let J=e.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((W)=>f[W]??{}))}function Y8($){let f=$?.trim();return f&&f.length>0?f:""}function R6($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function JB($){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 WB($,f){return`${$}:${Y8(f.baseUrl)}:${JB(R6(f)??"")}`}async function V8($,f,J=oV){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await fetch($,{...f,signal:W.signal})}finally{clearTimeout(Z)}}function j1($,f,J){if(J&&!$.includes(f))$.push(f)}function B8($,f){let J=["streaming","tools"];return j1(J,"images",Boolean(f.supportsImages)),j1(J,"prompt-cache",Boolean(f.supportsPromptCache)),j1(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 ZB($,f){let J=await V8("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let H=j.id?.trim();if(!H)continue;if(H.includes("whisper")||H.includes("tts")||H.includes("embedding"))continue;let X=j.supported_features??[];Q[H]=B8(H,{name:H,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return Q}function c9($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function QB($,f){let J=await V8("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let H=j.id?.trim();if(!H)continue;Q[H]=B8(H,{name:H,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}async function jB($,f){let W=`${(Y8($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await V8(W,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],H={};for(let X of j){let A=X.id?.trim();if(!A)continue;let Y=X.supported_features??[],V=X.supported_sampling_parameters??[],B=X.input_modalities??[],K=["streaming"];j1(K,"tools",Y.includes("tools")),j1(K,"reasoning",Y.includes("reasoning")),j1(K,"temperature",V.includes("temperature")),j1(K,"images",B.includes("image"));let G={input:c9(X.pricing?.prompt),output:c9(X.pricing?.completion)};H[A]={id:A,name:X.name??A,description:X.description,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return H}function HB($){let f=Y8($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function XB($,f){let W=`${HB($.baseUrl)}/v1/model/info`,Z=async(A)=>V8(W,{method:"GET",headers:{accept:"application/json",...A}}),Q=await Z({"x-litellm-api-key":f});if(!Q.ok)Q=await Z({Authorization:`Bearer ${f}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let H=(await Q.json())?.data??[],X={};for(let A of H){let Y=A.model_name?.trim(),B=A.litellm_params?.model?.trim()||Y;if(!B)continue;let K=A.model_info,G=B8(B,{name:Y??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(X[B]=G,Y)X[Y]={...G,id:Y,name:Y}}return X}var n9={baseten:ZB,hicap:QB,litellm:XB,poolside:jB},d9=new Map,U6=new Map;function AB($,f){return`${$}:${Y8(f.baseUrl)}`}async function YB($,f,J){let W=e.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=H8(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!Z)return{};let Q=f?.cacheTtlMs??i9,j=AB($,J),H=Date.now(),X=d9.get(j);if(X&&X.expiresAt>H)return X.data;let A=U6.get(j);if(A)return A;let Y=j8(Z,$).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,B8(K,{name:K})]));return d9.set(j,{data:B,expiresAt:H+Q}),B}).finally(()=>{U6.delete(j)});return U6.set(j,Y),Y}async function VB($,f){let J=R6(f);if(!J)return{};let W=n9[$];if(!W)return{};return W(f,J)}function BB($,f,J){if(!J)return!1;if(!n9[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(R6(J))}async function KB($,f,J){let W=f?.cacheTtlMs??i9,Z=WB($,J),Q=Date.now(),j=F6.get(Z);if(j&&j.expiresAt>Q)return j.data;let H=X8.get(Z);if(H)return H;let X=VB($,J).then((A)=>{return F6.set(Z,{data:A,expiresAt:Q+W}),A}).finally(()=>{X8.delete(Z)});return X8.set(Z,X),X}async function GB($){return e.fetchModelsDevProviderModels($,globalThis.fetch)}async function K8($={}){let f=$.url??r9,J=$.cacheTtlMs??sV,W=Date.now(),Z=A8.get(f);if(Z&&Z.expiresAt>W)return Z.data;let Q=yf.get(f);if(Q)return Q;let j=GB(f).then((H)=>{return A8.set(f,{data:H,expiresAt:W+J}),H}).finally(()=>{yf.delete(f)});return yf.set(f,j),j}function PB($){if($){A8.delete($),yf.delete($);return}A8.clear(),yf.clear()}function UB(){F6.clear(),X8.clear()}function FB($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:p9(J.capabilities)}]))}var D6=FB(tV());function a9($){let f=aV($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:p9(f.capabilities)}}async function L6($,f,J){let W=a9($);if(!W)return;try{let Z=f?.loadLatestOnInit?await K8(f):void 0,Q=Z?fB($,Z):{},j=J&&BB($,f,J)?await KB($,f,J):{},X=Boolean(e.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:W.modelId,baseUrl:W.baseUrl}:J,A=X?await YB($,f,X).catch(()=>({})):{},Y=await $B($,W.knownModels,Q,j,A,J?.knownModels);return{...W,knownModels:Y}}catch(Z){if(f?.failOnError)throw Z;return W}}var O6=y0.BUILT_IN_PROVIDER,RB=y0.BUILT_IN_PROVIDER_IDS,DB=y0.isBuiltInProviderId,G8=y0.normalizeProviderId,z6=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),t9=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),s9=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),o9=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),LB=N.enum(["none","low","medium","high","xhigh"]),e9=N.object({enabled:N.boolean().optional(),effort:LB.optional(),budgetTokens:N.number().int().positive().optional()}),$Q=N.object({accessKey:N.string().optional(),secretKey:N.string().optional(),sessionToken:N.string().optional(),region:N.string().optional(),profile:N.string().optional(),authentication:N.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:N.boolean().optional(),useCrossRegionInference:N.boolean().optional(),useGlobalInference:N.boolean().optional(),endpoint:N.string().url().optional(),customModelBaseId:N.string().optional()}),fQ=N.object({projectId:N.string().optional(),region:N.string().optional()}),JQ=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),WQ=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()}),ZQ=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),QQ=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()}),l1=N.object({provider:z6,apiKey:N.string().optional(),auth:o9.optional(),model:N.string().optional(),protocol:t9.optional(),client:s9.optional(),routingProviderId:z6.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:e9.optional(),aws:$Q.optional(),gcp:fQ.optional(),azure:JQ.optional(),sap:WQ.optional(),oca:ZQ.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:QQ.optional()});function jQ($){return l1.parse($)}function HQ($){return l1.safeParse($)}function OB($){return $.protocol==="openai-responses"||$.client==="openai"}function Z$($,f={}){let J=$.provider,W=G8(J),Z=f.includeKnownModels!==!1,Q=$.reasoning?.effort||"none",j=Q==="none"?void 0:Q,H=D6[W],X=Object.assign({},...y0.resolveProviderModelCatalogKeys(W).map((R)=>y0.getGeneratedModelsForProvider(R))),A=Object.keys(X)[0],Y=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,V=$.baseUrl??(W==="oca"?$.oca?.mode==="internal"?V6:B6:H?.baseUrl),B=$.routingProviderId??(OB($)&&W!==O6.OPENAI_NATIVE?O6.OPENAI_NATIVE:void 0),K=Z?H?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??H?.modelId??A??"default",...Z?{knownModels:K}:{},apiKey:Y,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:V,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??H?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,P])=>P!==void 0))}function zB($){let f=jQ($);return Z$(f)}function _B($){let f=HQ($);if(f.success)return{success:!0,config:Z$(f.data)};return{success:!1,error:f.error}}import{SESSION_STATUS_VALUES as TB}from"@cline/shared";var _6=TB,NB=["idle","running","pending"];function MB($){return!NB.includes($)}function $0($){return!MB($)}var U0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function XQ($){if($===!0)return{};if(!$)return;return $}function AQ($){if($==="user")return"global";return $}class T6{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 W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||U0.CLI,interactive:!1,config:{providerId:G8(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:wB(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:qB(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 P8($){let f=yB($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),W=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,Q=$.context?.telemetry??$.telemetry;if(!f&&!J&&!W&&!Z&&!Q)return $.context;return{...$.context??{},...J?{client:J}:{},...W?{user:W}:{},...Z?{logger:Z}:{},...Q?{telemetry:Q}:{},...f?{automation:f}:{}}}function yB($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function qB($){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 wB($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}import{existsSync as UJ}from"node:fs";import{basename as e3,isAbsolute as xF,relative as mF}from"node:path";import{createHash as SB}from"node:crypto";import{watch as hB}from"node:fs";import{readdir as CB,readFile as EB}from"node:fs/promises";import{join as bB}from"node:path";function kB($){return SB("sha1").update($).digest("hex")}function KQ($){return Boolean($&&typeof $==="object"&&"code"in $)}function VQ($){return KQ($)&&$.code==="ENOENT"}function BQ($){return KQ($)&&($.code==="EACCES"||$.code==="EPERM")}class qf{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let Z=this.baseTypesByDirectory.get(W);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([W,Z])=>[W,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=hB(f,()=>{let W=this.watchedTypesByDirectory.get(f);if(!W)return;for(let Z of W)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(W)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let Q of Z)this.emit({kind:"error",type:Q,error:W,filePath:f})})}catch(J){if(!VQ(J)&&!BQ(J)){let W=$.get(f);if(!W)continue;for(let Z of W)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),W=this.recordsByType.get($.type)??new Map;for(let[Z,Q]of W.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:Q.filePath})}for(let[Z,Q]of f.entries()){let j=W.get(Z);if(j&&j.filePath===Q.filePath&&j.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:Z,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let W of $.directories){J.add(W);let Z=$.discoverFiles?await $.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of Z){let{fileName:j,filePath:H}=Q;if(J.add(Q.directoryPath),$.includeFile&&!$.includeFile(j,H))continue;try{let X=await EB(H,"utf8"),A={type:$.type,directoryPath:Q.directoryPath,fileName:j,filePath:H,content:X},Y=$.parseFile(A),V=$.resolveId(Y,A).trim();if(!V)continue;f.set(V,{type:$.type,id:V,item:Y,filePath:H,fingerprint:kB(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:X,filePath:H})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let Z=$.get(W);if(Z)Z.add(f);else $.set(W,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await CB($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:bB($,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch(f){if(VQ(f)||BQ(f))return[];throw f}}}import{readdir as r6,readFile as oK,stat as p6}from"node:fs/promises";import{basename as j$,dirname as eK,extname as S8,join as O0,resolve as kf}from"node:path";import{AGENTS_RULES_FILE_NAME as cQ,RULES_CONFIG_DIRECTORY_NAME as dQ,resolveGlobalAgentsRulesPath as $G,resolveRulesConfigSearchPaths as fG,resolveSkillsConfigSearchPaths as JG,resolveWorkflowsConfigSearchPaths as WG,SKILLS_CONFIG_DIRECTORY_NAME as i6,WORKFLOWS_CONFIG_DIRECTORY_NAME as n6}from"@cline/shared/storage";import ZG from"yaml";n0();import{existsSync as M8,readFileSync as gK,statSync as vK}from"node:fs";import{basename as uK,dirname as T8,join as y8,resolve as N8}from"node:path";import{discoverPluginModulePaths as cK,resolveConfiguredPluginModulePaths as xQ,resolvePluginConfigSearchPaths as dK,SKILLS_CONFIG_DIRECTORY_NAME as lK}from"@cline/shared/storage";import{resolve as UK}from"node:path";import{normalizePluginManifest as FK}from"@cline/shared";import{existsSync as H0,readFileSync as n1}from"node:fs";import{builtinModules as sB,createRequire as C6}from"node:module";import{dirname as N$,extname as Sf,isAbsolute as oB,resolve as g}from"node:path";import{fileURLToPath as DQ}from"node:url";import{PLUGIN_FILE_EXTENSIONS as eB}from"@cline/shared";var LQ=N$(DQ(import.meta.url)),$K=C6(import.meta.url),fK=g(LQ,"..","..","..","..",".."),w6=ZK(fK),JK=["@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"],E6=new Set(sB.flatMap(($)=>[$,$.replace(/^node:/,"")])),wf=new Set(eB),WK=["development","node","import","require","default"];function ZK($){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[W,Z]of Object.entries(J))if(H0(Z))f[W]=Z;for(let W of["agents","core","llms","shared"]){let Z=g($,"packages",W),Q=g(Z,"package.json");if(!H0(Q))continue;try{let j=JSON.parse(n1(Q,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let H=g(Z,j.exports);if(H0(H))f[j.name]=H;continue}if(typeof j.exports!=="object")continue;for(let[H,X]of Object.entries(j.exports)){let A=QK(Z,X);if(!A)continue;let Y=H==="."?j.name:`${j.name}/${H.replace(/^\.\//,"")}`;f[Y]=A}}catch{}}return f}function QK($,f){let J=b6(f);if(!J)return null;let W=OQ($,J);for(let Z of W)if(H0(Z))return Z;return null}function b6($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let W of WK){let Z=b6(J[W],f);if(Z)return Z}return null}function OQ($,f){let J=f.replace(/^\.\//,""),W=[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`),...W]}return W}function jK($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function L8($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function i1($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function HK($){let f=i1($);if($===f)return".";return`.${$.slice(f.length)}`}function zQ($){return i1($).startsWith("@cline/")}function S6($,f){let J=i1(f),W=N$($);while(!0){let Z=g(W,"node_modules",J);if(H0(Z)||H0(g(Z,"package.json")))return!0;let Q=g(W,"..");if(Q===W)return!1;W=Q}}function RQ($){return h6($)!==null}function h6($){try{return $K.resolve($)}catch{}return XK($)}function XK($){let f=i1($),J=_Q(f);if(!J)return null;let W=g(J,"package.json");try{let Z=JSON.parse(n1(W,"utf8")),Q=HK($),j=Q==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,Q)?Z.exports[Q]:void 0,H=b6(j)??(Q==="."&&typeof Z.main==="string"?Z.main:null);if(!H)return null;let X=g(J,H),A=[X,...OQ(J,H).filter((Y)=>Y!==X)];for(let Y of A)if(H0(Y))return Y;return null}catch{return null}}function AK(){let $=[LQ],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(N$(N$(f)));let J=process.execPath?.trim();if(J)$.push(N$(J));return[...new Set($.map((W)=>g(W)))]}function YK($,f){let J=$;while(!0){let W=g(J,"package.json");if(H0(W))try{if(JSON.parse(n1(W,"utf8")).name===f)return J}catch{}let Z=g(J,"node_modules",f,"package.json");if(H0(Z))return N$(Z);let Q=g(J,"..");if(Q===J)return null;J=Q}}function _Q($){for(let f of AK()){let J=YK(f,$);if(J)return J}return null}function VK($){let J=N$($);for(let W=0;W<4;W++){let Z=g(J,"package.json");if(H0(Z))try{let j=JSON.parse(n1(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let Q=g(J,"..");if(Q===J)return!1;J=Q}return!1}function TQ($,f){let J=f.startsWith("file:")?DQ(f):oB(f)?f:g(N$($),f);if(H0(J)&&wf.has(Sf(J)))return J;for(let W of wf){let Z=`${J}${W}`;if(H0(Z))return Z}for(let W of wf){let Z=g(J,`index${W}`);if(H0(Z))return Z}return null}function NQ($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of J)for(let Z of $.matchAll(W)){let Q=Z[1];if(Q)f.add(Q)}return[...f]}function BK($){return Sf($)!==".ts"}function MQ($,f,J=new Set){if(J.has($)||!H0($))return;if(J.add($),!wf.has(Sf($)))return;let W=n1($,"utf8"),Z=BK($);for(let Q of NQ(W)){if(Q.startsWith("node:")||E6.has(Q))continue;if(L8(Q)){if(!Z)continue;if(Object.hasOwn(w6,Q)||Object.hasOwn(w6,i1(Q))||S6($,Q)||zQ(Q)&&RQ(Q)||f&&RQ(Q))continue;throw Error(`Cannot find module '${i1(Q)}'`)}let j=TQ($,Q);if(j)MQ(j,f,J)}}function yQ($,f=new Set,J=new Set){if(f.has($)||!H0($))return J;if(f.add($),!wf.has(Sf($)))return J;let W=n1($,"utf8");for(let Z of NQ(W)){if(J.add(Z),L8(Z))continue;let Q=TQ($,Z);if(Q)yQ(Q,f,J)}return J}function KK($,f){let J=C6($),W={},Z=yQ($),Q=new Set(JK);for(let[j,H]of Object.entries(w6)){try{J.resolve(j);continue}catch{}W[j]=H}for(let j of Z)if(L8(j)&&(zQ(j)||f))Q.add(j);for(let j of Q){if(Object.hasOwn(W,j)||S6($,j))continue;let H=h6(j);if(H)W[j]=H}if(!f)return W;for(let j of Z){if(!L8(j)||Object.hasOwn(W,j)||S6($,j)||j.startsWith("node:")||E6.has(j))continue;let H=h6(j);if(H)W[j]=H}return W}function GK($){let f=Sf($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var H1;function PK(){if(H1!==void 0)return H1;let $=_Q("jiti");if(!$)return H1=null,null;let f=g($,"dist","babel.cjs");if(!H0(f))return H1=null,null;try{let W=C6(f)(f);H1=typeof W==="function"?W:null}catch{H1=null}return H1}async function qQ($,f={}){let J=!VK($);MQ($,J);let W=KK($,J),Z=jK(W),Q=await import("jiti"),j=typeof Q==="function"?Q:typeof Q.default==="function"?Q.default:void 0;if(!j)throw Error("Unable to load jiti");let H=Object.entries(Z).filter(([,V])=>GK(V)).map(([V])=>V),X=PK(),A=X?(V)=>X({...V,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...E6],transformModules:H,tryNative:!1,...A?{transform:A}:{}}).import($,{})}function wQ($,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 SQ($){return typeof $==="object"&&$!==null}function k6($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function RK($,f){if(!SQ($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!k6($.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")&&!k6($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!k6($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function DK($,f){if(!SQ($))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"`);RK($,f)}async function I6($,f={}){let J=UK(f.cwd??process.cwd(),$),W=await qQ(J,{useCache:f.useCache}),Z=f.exportName??"plugin",Q=W.default??W[Z];DK(Q,J);let j=Q,H=j.setup,X=H?(A,Y)=>{let V={...f.session,...Y.session},B={...Y,session:Object.keys(V).length>0?V:void 0,client:f.client??Y.client,user:f.user??Y.user,workspaceInfo:f.workspaceInfo??Y.workspaceInfo,automation:f.automation??Y.automation,logger:f.logger??Y.logger,telemetry:f.telemetry??Y.telemetry};return H(A,B)}:void 0;return{...j,manifest:FK(j.manifest),setup:X}}async function hQ($,f={}){return(await hf($,f)).plugins}async function hf($,f={}){let J=[],W=[],Z=new Map,Q=0;for(let H of $)try{let X=await I6(H,f);if(!wQ(X.manifest,f))continue;let A=Z.get(X.name);if(A)W.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:H,overriddenPluginPath:A.pluginPath,message:`Plugin "${X.name}" from ${H} overrides ${A.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:H,order:Q++})}catch(X){let A=X instanceof Error?X.message:String(X);J.push({pluginPath:H,phase:"load",message:A,stack:X instanceof Error?X.stack:void 0})}let j=[...Z.values()].sort((H,X)=>H.order-X.order);return{plugins:j.map((H)=>H.plugin),pluginPaths:j.map((H)=>H.pluginPath),failures:J,warnings:W}}import{existsSync as g6}from"node:fs";import{createRequire as IQ}from"node:module";import{dirname as z8,join as a1}from"node:path";import{fileURLToPath as MK}from"node:url";import{spawn as LK}from"node:child_process";import{basename as OK}from"node:path";import{augmentNodeCommandForDebug as zK,withResolvedClineBuildEnv as _K}from"@cline/shared";function CQ($){if($ instanceof Error)return $;return Error(String($))}var TK="CLINE_JS_RUNTIME_PATH";function EQ($){let f=$?.trim();if(!f)return!1;let J=OK(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function bQ($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[TK]?.trim();if(J)return J;let W=$.execPath?.trim()||process.execPath;if(EQ(W))return W;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let Q=Z?.trim();if(Q&&EQ(Q))return Q}return"node"}function NK($,f={}){let J=bQ({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return zK([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class O8{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=NK($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=LK(f[0]??bQ(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:_K(process.env)});this.process=J;let W="",Z=(Q)=>{let j=W+Q;W=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{Z(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${CQ(Q).message}`))}),J.on("exit",(Q,j)=>{this.process=null;let H=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(j)})${H?`: ${H}`:""}`))})}async call($,f,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,Q={type:"call",id:Z,method:$,args:f};return await new Promise((j,H)=>{let X={resolve:(A)=>j(A),reject:H};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),H(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,X),W.send(Q,(A)=>{if(!A)return;let Y=this.clearPendingRequest(Z);if(!Y)return;Y.reject(Error(`${this.processLabel} failed to send call "${$}": ${CQ(A).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 yK($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function Cf($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function qK(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function wK(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=IQ($).resolve(`${qK()}/package.json`),W=a1(z8(J),"extensions","plugin-sandbox-bootstrap.js");return g6(W)?W:void 0}catch{return}}function SK(){let $=process.execPath?.trim();if(!$)return;let f=a1(z8(z8($)),"extensions","plugin-sandbox-bootstrap.js");return g6(f)?f:void 0}function hK(){let $=z8(MK(import.meta.url)),f=IQ(import.meta.url),J=[a1($,"plugin-sandbox-bootstrap.js"),a1($,"extensions","plugin-sandbox-bootstrap.js"),a1($,"agents","plugin-sandbox-bootstrap.js"),wK(),SK()];for(let Q of J.filter((j)=>typeof j==="string"))if(g6(Q))return{file:Q};let W=a1($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
47
- `)}}var x6=hK();function m6($,f,J){if(typeof $==="number"&&$>0)return $;if(J){let W=process.env[J];if(W){let Z=Number(W);if(Number.isInteger(Z)&&Z>0)return Z}}return f}async function _8($){let f=new O8({name:"plugin-sandbox",..."file"in x6?{bootstrapFile:x6.file}:{bootstrapScript:x6.script},onEvent:$.onEvent}),J=m6($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),W=m6($.hookTimeoutMs,3000),Z=m6($.contributionTimeoutMs,60000),Q={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,H=()=>{return j??=f.call("initialize",Q,{timeoutMs:J}).finally(()=>{j=void 0}),j},X;try{X=await f.call("initialize",Q,{timeoutMs:J})}catch(V){throw await f.shutdown().catch(()=>{}),V}let A=X.plugins.map(yK);return{extensions:A.map((V)=>{let B={name:V.name,__clinePluginPath:V.pluginPath,manifest:V.manifest,setup:(K)=>{CK(K,f,V,Z,H),EK(K,f,V,Z,H),bK(K,f,V,Z,H),IK(K,f,V,Z,H),kK(K,V)}};return B.hooks=mK(f,V,W,H),B}),failures:X.failures,pluginPaths:A.map((V)=>V.pluginPath),shutdown:async()=>{await f.shutdown()},warnings:X.warnings}}function CK($,f,J,W,Z){for(let Q of J.contributions?.tools??[]){let j={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(H,X)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:H,context:X},{timeoutMs:W})}catch(A){if(!Cf(A))throw A;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:H,context:X},{timeoutMs:W})}}};$.registerTool(j)}}function EK($,f,J,W,Z){for(let Q of J.contributions?.commands??[])$.registerCommand({name:Q.name,description:Q.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}catch(H){if(!Cf(H))throw H;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}}})}function bK($,f,J,W,Z){for(let Q of J.contributions?.rules??[])$.registerRule({id:Q.ruleId,source:Q.source,content:Q.hasContentHandler===!0?async()=>{try{return await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}catch(j){if(!Cf(j))throw j;return await Z(),await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}}:Q.content??""})}function kK($,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 IK($,f,J,W,Z){for(let Q of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:Q.name,async build(j){try{let H=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return kQ(H)?H:j}catch(H){if(!Cf(H))throw H;await Z();let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return kQ(X)?X:j}}})}function kQ($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function xK($,f,J,W,Z){return async(Q)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}catch(j){if(!Cf(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}}}function mK($,f,J,W){let Z={};for(let Q of f.hooks??[])Z[Q]=xK($,f.pluginId,Q,J,W);return Object.keys(Z).length>0?Z:void 0}var u6="package.json",pK="package";function c6($){return dK($)}function d6($){return cK($)}function rK($){try{return M8($)&&vK($).isDirectory()}catch{return!1}}function l6($){let f=[],J=new Set;for(let W of $){let Z=N8(W);if(J.has(Z))continue;J.add(Z),f.push(Z)}return f}function mQ($){let f=l6($);return y6(f)}function gQ($){return c6($).flatMap((f)=>d6(f)).filter((f)=>M8(f))}function iK($,f){let J=[];for(let W of $)try{J.push(...xQ([W],f))}catch{}return J}function v6($){return typeof $==="object"&&$!==null}function nK($){try{let f=JSON.parse(gK(y8($,u6),"utf8"));if(!v6(f)||!v6(f.cline))return[];let J=f.cline.plugins;if(!Array.isArray(J))return[];let W=[];for(let Z of J){if(typeof Z==="string"){W.push(Z);continue}if(!v6(Z)||!Array.isArray(Z.paths))continue;for(let Q of Z.paths)if(typeof Q==="string")W.push(Q)}return W}catch{return[]}}function vQ($,f){let J=N8(f);return nK($).some((W)=>N8($,W)===J)}function aK($,f){return uK($)===pK&&M8(y8(T8($),u6))&&vQ(T8($),f)}function tK($){let f=N8($),J=[],W=T8(f);while(!0){if(aK(W,f)){J.push(W);break}if(M8(y8(W,u6))){if(vQ(W,f))J.push(W);break}let Z=T8(W);if(Z===W)break;W=Z}return l6(J)}function Ef($={}){let f=$.cwd??process.cwd(),J=gQ($.workspacePath),W=xQ($.pluginPaths??[],f);return mQ([...W,...J])}function sK($={}){let f=$.cwd??process.cwd(),J=gQ($.workspacePath),W=iK($.pluginPaths??[],f);return mQ([...W,...J])}function bf($){let f=[];for(let J of $)for(let W of tK(J)){let Z=y8(W,lK);if(rK(Z))f.push(Z)}return l6(f)}function uQ($={}){return bf(sK($))}async function q8($={}){let f=Ef($);if(f.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let W=await hf(f,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:W.plugins,failures:W.failures,pluginPaths:W.pluginPaths,warnings:W.warnings}}let J=await _8({pluginPaths:f,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}var w8="SKILL.md",QG="managed.json",jG=new Set([".md",".markdown",".txt"]);function a6($){return $.trim().toLowerCase()}function t1($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"||f?.code==="ELOOP"}function h8($){return jG.has(S8($).toLowerCase())}function lQ($){let f=[],J=new Set;for(let W of $){let Z=kf(W);if(J.has(Z))continue;J.add(Z),f.push(W)}return f}function HG($){let f=[...$?.directories??f5($?.workspacePath)];if($?.pluginSkillDirectories)f.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)f.push(...uQ({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return lQ(f)}async function t6($){try{let f=await r6($,{withFileTypes:!0}),J=[];for(let W of f){if(!W.isDirectory())continue;let Z=O0($,W.name),Q=O0(Z,QG);try{let j=await oK(Q,"utf8"),H=JSON.parse(j);if(H&&typeof H==="object")J.push(Z)}catch(j){if(t1(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((W,Z)=>W.localeCompare(Z))}catch(f){if(t1(f))return[];throw f}}function s6($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J;try{let Q=ZG.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}catch(Q){let j=Q instanceof Error?Q.message:String(Q);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function C8($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let W=$.trim();if(!W&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return W||void 0}function s1($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function XG($,f){if(j$($.filePath).toLowerCase()!==cQ.toLowerCase())return j$($.filePath,S8($.filePath));if(f&&kf($.filePath)===kf(f,cQ))return"Workspace AGENTS.md";if(kf($.filePath)===kf($G()))return"Global AGENTS.md";return j$($.filePath,S8($.filePath))}function o6($,f){let{data:J,body:W,parseError:Z}=s6($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let H=C8(J.name,"name",!1)??f.trim();if(!H)throw Error("Missing skill name.");return{name:H,description:C8(J.description,"description",!1),disabled:s1(J.disabled,"disabled")??(s1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function e6($,f){let{data:J,body:W,parseError:Z}=s6($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let j=C8(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:s1(J.disabled,"disabled")??(s1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function $5($,f){let{data:J,body:W,parseError:Z}=s6($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let j=C8(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:s1(J.disabled,"disabled")??(s1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function f5($){return JG($)}function J5($){return fG($)}function W5($){return WG($)}async function pQ($){if(j$($)===".cline"){let f=await t6($);return(await Promise.all(f.map((W)=>pQ(O0(W,i6))))).flat()}try{let f=await r6($,{withFileTypes:!0}),J=[];for(let W of f){if(W.isFile()&&W.name===w8){J.push({directoryPath:$,fileName:W.name,filePath:O0($,W.name)});continue}let Z=O0($,W.name);if(W.isDirectory()||W.isSymbolicLink()&&await p6(Z).then((j)=>j.isDirectory()).catch((j)=>{if(t1(j))return!1;throw j}))J.push({directoryPath:Z,fileName:w8,filePath:O0(Z,w8)})}return J}catch(f){if(t1(f))return[];throw f}}async function E8($){if(j$($)===".cline"){let f=await t6($);return(await Promise.all(f.map((W)=>E8(O0(W,"rules.md"))))).flat()}try{if((await p6($)).isFile())return[{directoryPath:eK($),fileName:j$($),filePath:$}]}catch(f){if(!t1(f))throw f}try{let J=(await r6($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&h8(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:O0($,Z.name)})),W=O0($,"AGENTS.md");try{if((await p6(W)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch(f){if(t1(f))return[];throw f}}async function AG($){if(j$($)===".cline"){let f=await t6($);return(await Promise.all(f.map((W)=>E8(O0(W,n6))))).flat()}return E8($)}function Z5($){let f=HG($),J=$?.workspacePath?O0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?lQ([...f,J]):f,discoverFiles:pQ,includeFile:(W)=>W===w8,parseFile:(W)=>o6(W.content,j$(W.directoryPath)),resolveId:(W)=>a6(W.name)}}function Q5($){let f=$?.directories??J5($?.workspacePath),J=$?.workspacePath?O0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:E8,includeFile:(W,Z)=>W===".clinerules"||h8(W)||h8(Z),parseFile:(W)=>e6(W.content,XG(W,$?.workspacePath)),resolveId:(W)=>a6(W.name)}}function j5($){let f=$?.directories??W5($?.workspacePath),J=$?.workspacePath?O0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:AG,includeFile:(W)=>h8(W),parseFile:(W)=>$5(W.content,j$(W.filePath,S8(W.filePath))),resolveId:(W)=>a6(W.name)}}function rQ($){let f=[Z5($?.skills),Q5($?.rules),j5($?.workflows)];return new qf(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as iQ}from"@cline/shared";function YG($,f){if($.description?.trim())return iQ($.description,".");if(f==="workflow")return;return iQ($.instructions,".")}function VG($){return $.disabled!==!0}function nQ($,f){return[...$.getSnapshot(f).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>VG(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:YG(W.item,f),kind:f})).sort((J,W)=>J.name.localeCompare(W.name))}function If($){let f=new Map;for(let J of[...nQ($,"workflow"),...nQ($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,W)=>J.name.localeCompare(W.name))}function aQ($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let W=J[1];if(!W)return $;let Z=W.length+1,Q=$.slice(Z),j=If(f).find((H)=>H.name===W);return j?`${j.instructions}${Q}`:$}function tQ($){return $.disabled!==!0}function b8($){if($.length===0)return"";return`
46
+ </html>`;function cZ(f){let $="";for(let J=0;J<f.length;J+=1)$+=String.fromCharCode(f[J]??0);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function CV(f){let J=new TextEncoder().encode(f),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function SV(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),cZ($)}async function A8(){let f=SV(),$=cZ(await CV(f));return{verifier:f,challenge:$}}function Y8(f){return f.endsWith("/")?f.slice(0,-1):f}function A$(f,$){return new URL($,`${Y8(f)}/`).toString()}function p$(f,$={}){let J=f.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:$.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if($.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:$.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function EV(f){if(typeof atob==="function")try{return atob(f)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from(f,"base64").toString("utf8")}catch{return null}return null}function F0(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=EV(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function r$(f){try{let $=JSON.parse(f),J=$.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function i$(f,$){return Date.now()>=f.expires-$}async function n$(f){if(!f.onManualCodeInput){let W=await f.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let $,J,Q=f.onManualCodeInput().then((W)=>{$=W,f.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),f.cancelWait()}),Z=await f.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if($)return p$($,f.parseOptions);if(await Q,J)throw J;if($)return p$($,f.parseOptions);return{}}var V8={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},pZ={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},V6="https://api.workos.com",hV="/auth",uZ=Array.from({length:11},(f,$)=>48801+$),bV=300000,kV=30000,a$=30000,IV=300,xV=5;class qf extends Error{status;errorCode;constructor(f,$){super(f);this.name="ClineOAuthTokenError",this.status=$?.status,this.errorCode=$?.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 gV(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function B6(f,$,J={}){let Q=f.userInfo.clineUserId??J.accountId,Z=f.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:Z,expires:gV(f.expiresAt),accountId:Q??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function K6(f){if(!f)return{};return typeof f==="function"?await f():f}function dZ(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function lZ(f){await new Promise(($)=>setTimeout($,f))}function P6(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function rZ(f,$){let J=await fetch(A$(V6,pZ.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??a$)}),Q=await J.json().catch(()=>({}));if(!J.ok)throw new qf(`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:dZ(Q.expires_in,IV),pollIntervalSeconds:dZ(Q.interval,xV)}}async function iZ(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let Q=await fetch(A$(f.workosApiBaseUrl,pZ.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:f.deviceCode,client_id:f.clientId}),signal:AbortSignal.timeout(f.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 lZ(J*1000);break}case"slow_down":{J+=1,await lZ(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new qf(Z.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:Z.error});default:throw new qf(`WorkOS token polling failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function nZ(f,$,J){let Q={accessToken:f.accessToken,refreshToken:f.refreshToken},Z=await fetch(A$($.apiBaseUrl,V8.register),{method:"POST",headers:{"Content-Type":"application/json",...await K6($.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout($.requestTimeoutMs??a$)});if(!Z.ok){let j=await Z.text().catch(()=>""),H=r$(j);throw new qf(`Token registration failed: ${Z.status}${H.message?` - ${H.message}`:""}`,{status:Z.status,errorCode:H.code})}let W=await Z.json();return B6(P6(W,"Invalid token exchange response"),J??$.provider)}async function mV(f,$,J,Q){let Z={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:Q??J.provider},W=await fetch(A$(J.apiBaseUrl,V8.token),{method:"POST",headers:{"Content-Type":"application/json",...await K6(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??a$)});if(!W.ok){let H=await W.text().catch(()=>""),X=r$(H);throw new qf(`Token exchange failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return B6(P6(j,"Invalid token exchange response"),Q??J.provider)}async function G6(f){Tf(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:uZ,Q=f.callbackPath??hV,Z=$?null:await Xf({ports:J,callbackPath:Q,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??uZ[0]}${Q}`;try{let j;if($){let H=Y6().workOsClientId,X=await rZ(H,f);f.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await iZ({clientId:H,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??a$,workosApiBaseUrl:V6,onProgress:f.callbacks.onProgress});j=await nZ(A,f,f.provider)}else{let H=new URL(A$(f.apiBaseUrl,V8.authorize));H.searchParams.set("client_type","extension"),H.searchParams.set("callback_url",W),H.searchParams.set("redirect_uri",W),f.callbacks.onAuth({url:H.toString(),instructions:"Continue the authentication process in your browser."});let X,A=f.provider,Y=await n$({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(Y.error)throw Error(`OAuth error: ${Y.error}`);if(X=Y.code,A=Y.provider??A,!X){let V=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=p$(V,{includeProvider:!0});X=B.code,A=B.provider??A}if(!X)throw Error("Missing authorization code");j=await mV(X,W,f,A)}return zf(f.telemetry,f.provider??"cline"),Nf(f.telemetry,{id:j.accountId,email:j.email,provider:f.provider??"cline"}),j}catch(j){throw Mf(f.telemetry,f.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function vV(f){return await rZ(Y6().workOsClientId,f)}async function cV(f){let $=f.provider??"cline";Tf(f.telemetry,$);try{let J=await iZ({clientId:Y6().workOsClientId,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??a$,workosApiBaseUrl:V6}),Q=await nZ(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return zf(f.telemetry,$),Nf(f.telemetry,{id:Q.accountId,email:Q.email,provider:$}),Q}catch(J){throw Mf(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function aZ(f,$){let J=await fetch(A$($.apiBaseUrl,V8.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await K6($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??a$)});if(!J.ok){let W=await J.text().catch(()=>""),j=r$(W);throw new qf(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let Q=await J.json(),Z=f.metadata?.provider??$.provider;return B6(P6(Q,"Invalid token refresh response"),Z,f)}async function F6(f,$,J){if(!f)return null;let Q=J?.refreshBufferMs??bV,Z=J?.retryableTokenGraceMs??kV;if(J?.forceRefresh!==!0&&!i$(f,Q))return f;try{return await aZ(f,$)}catch(j){if(j instanceof qf&&j.isLikelyInvalidGrant())return H$($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>Z)return f;return null}}V0();import{nanoid as uV}from"nanoid";var o={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 B8 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OpenAICodexOAuthTokenError",this.status=$?.status,this.errorCode=$?.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 dV(f,$,J=o.redirectUri){let Q=await fetch(o.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:o.clientId,code:f,code_verifier:$,redirect_uri:J}),signal:AbortSignal.timeout(o.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 lV(f){try{let $=await fetch(o.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:o.clientId}),signal:AbortSignal.timeout(o.httpTimeoutMs)});if(!$.ok){let Q=await $.text().catch(()=>""),Z=r$(Q);throw new B8(`Token refresh failed: ${$.status}${Z.message?` - ${Z.message}`:""}`,{status:$.status,errorCode:Z.code})}let J=await $.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($){if($ instanceof B8)throw $;return{type:"failed"}}}async function pV(f="pi"){let{verifier:$,challenge:J}=await A8(),Q=uV(32),Z=new URL(o.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",o.clientId),Z.searchParams.set("redirect_uri",o.redirectUri),Z.searchParams.set("scope",o.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",f),{verifier:$,state:Q,url:Z.toString()}}function rV(){try{let f=new URL(o.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):o.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:o.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:o.callbackPort,callbackPath:"/auth/callback",redirectUri:o.redirectUri}}}function iV(f,$){let J=$?F0($):F0(f),Q=J?J:F0(f),W=Q?.[o.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 X=j[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let H=Q?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;return null}function tZ(f,$){let J=iV(f.access,f.idToken)??$?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:f.access,refresh:f.refresh||$?.refresh||"",expires:f.expires,accountId:J,email:f.email??$?.email,metadata:{...$?.metadata??{},provider:"openai-codex"}}}async function U6(f){Tf(f.telemetry,"openai-codex");let $=rV(),{verifier:J,state:Q,url:Z}=await pV(f.originator),W=await Xf({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:Q});f.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let H=await n$({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(H.state&&H.state!==Q)throw Error("State mismatch");if(j=H.code,!j){let Y=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=p$(Y,{allowHashCodeState:!0});if(V.state&&V.state!==Q)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let X=await dV(j,J,$.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=tZ(X);return zf(f.telemetry,"openai-codex"),Nf(f.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(H){throw Mf(f.telemetry,"openai-codex",H instanceof Error?H.message:String(H)),H}finally{W.close()}}async function sZ(f,$){let J=await lV(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=tZ(J,$);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function R6(f,$){if(!f)return null;let J=$?.refreshBufferMs??o.refreshBufferMs,Q=$?.retryableTokenGraceMs??o.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!i$(f,J))return f;try{return await sZ(f.refresh,f)}catch(W){if(W instanceof B8&&W.isLikelyInvalidGrant())return H$($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>Q)return f;return null}}V0();import{nanoid as oZ}from"nanoid";class D6{ttlMs;maxEntries;entries=new Map;constructor(f,$){this.ttlMs=f;this.maxEntries=$}get(f,$=Date.now()){this.pruneExpired($);let J=this.entries.get(f);if(!J)return;return this.entries.delete(f),this.entries.set(f,J),J.value}set(f,$,J=Date.now(),Q=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);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(f,{value:$,expiresAt:J+Q})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var nV="a8331954c0cf48ba99b5dd223a14c6ea",aV="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",tV="openid offline_access",O6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",sV="c1aba3deed5740659981a752714eba33",oV="https://login-ext.identity.oraclecloud.com",eV="openid offline_access",_6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm";var fB="/auth/oca",$B=Array.from({length:11},(f,$)=>48801+$),JB=300000,QB=30000,eZ=30000,ZB=600000;class K8 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OcaOAuthTokenError",this.status=$?.status,this.errorCode=$?.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 yf={internal:{clientId:nV,idcsUrl:aV,scopes:tV,baseUrl:O6},external:{clientId:sV,idcsUrl:oV,scopes:eV,baseUrl:_6}},h1=new Map,WB=86400000,jB=300000,HB=32,L6=new D6(WB,HB);function fW(f){if(typeof f==="function")return f();return f??"internal"}function $W(f){return{internal:{clientId:f?.internal?.clientId??yf.internal.clientId,idcsUrl:f?.internal?.idcsUrl??yf.internal.idcsUrl,scopes:f?.internal?.scopes??yf.internal.scopes,baseUrl:f?.internal?.baseUrl??yf.internal.baseUrl},external:{clientId:f?.external?.clientId??yf.external.clientId,idcsUrl:f?.external?.idcsUrl??yf.external.idcsUrl,scopes:f?.external?.scopes??yf.external.scopes,baseUrl:f?.external?.baseUrl??yf.external.baseUrl}}}function XB(f=Date.now()){let $=f-ZB;for(let[J,Q]of h1.entries())if(Q.createdAt<$)h1.delete(J)}function AB(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let Z=F0($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=F0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function JW(f,$,J){let Q=f.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=f.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=F0(f.id_token),j=F0(Q),H=W?.sub??j?.sub,X=W?.email??j?.email;return{access:Q,refresh:Z,expires:AB(f,Q,f.id_token),accountId:H??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:H,idToken:f.id_token}}}async function QW(f,$){let J=Y8(f),Q=L6.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout($)});if(!W.ok){let X=`${J}/oauth2/v1/token`;return L6.set(J,X,Date.now(),jB),X}let H=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return L6.set(J,H),H}function ZW(f){return{code:f.error,message:f.error_description}}async function YB(f){let $=h1.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");h1.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,Q=await QW(J.idcsUrl,f.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout(f.requestTimeoutMs)}),j=await W.json();if(!W.ok){let X=ZW(j);throw new K8(`Token exchange failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let H=F0(j.id_token);if(!j.id_token||!H)throw Error("No ID token received from OCA");if(H.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return JW(j,f.mode)}function VB(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${Y8($.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",$.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",$.scopes),J.searchParams.set("code_challenge",f.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",f.callbackUrl),J.searchParams.set("state",f.state),J.searchParams.set("nonce",f.nonce),J.toString()}async function T6(f){Tf(f.telemetry,"oca");let $=$W(f.config),J=fW(f.mode),Q=f.callbackPorts?.length?f.callbackPorts:$B,Z=f.callbackPath??fB,W=f.requestTimeoutMs??eZ,j=await Xf({ports:Q,callbackPath:Z,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),H=j.callbackUrl;if(!H)throw Error("Unable to bind local OAuth callback server");let X=oZ(16),A=oZ(16),{verifier:Y,challenge:V}=await A8();XB(),h1.set(X,{verifier:Y,nonce:A,mode:J,redirectUri:H,createdAt:Date.now()});let B=VB({callbackUrl:H,mode:J,state:X,nonce:A,challenge:V,config:$});f.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await n$({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),P=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!P){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==X)throw Error("State mismatch");let G=await YB({code:P,state:R,mode:J,config:$,requestTimeoutMs:W});return zf(f.telemetry,"oca"),Nf(f.telemetry,{id:G.accountId,email:G.email,provider:"oca"}),G}catch(K){throw Mf(f.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function WW(f,$={}){let J=$W($.config),Q=$.requestTimeoutMs??eZ,Z=f.metadata?.mode,W=Z==="internal"||Z==="external"?Z:fW($.mode),j=W==="external"?J.external:J.internal,H=await QW(j.idcsUrl,Q),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:j.clientId}),A=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(Q)}),Y=await A.json();if(!A.ok){let V=ZW(Y);throw new K8(`Token refresh failed: ${A.status}${V.message?` - ${V.message}`:""}`,{status:A.status,errorCode:V.code})}return JW(Y,W,f)}async function z6(f,$,J){if(!f)return null;let Q=$?.refreshBufferMs??J?.refreshBufferMs??JB,Z=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??QB;if($?.forceRefresh!==!0&&!i$(f,Q))return f;try{return await WW(f,J)}catch(j){if(j instanceof K8&&j.isLikelyInvalidGrant())return H$(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>Z)return f;return null}}import{getClineEnvironmentConfig as jW}from"@cline/shared";var P8="workos:";function BB(f){let $=f.trim();return $.toLowerCase().startsWith(P8)?$:`${P8}${$}`}function KB(f){let $=f.trim();return $.toLowerCase().startsWith(P8)?$.slice(P8.length):$}function PB(f){let J=F0(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function GB(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=PB($);if(Q)return Q;return Date.now()-1}function FB(f,$){let J=f.auth?.accessToken?.trim(),Q=f.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=$?.normalizeAccessToken?.(J)??J;if(!Z)return null;return{access:Z,refresh:Q,expires:GB(f,Z),accountId:f.auth?.accountId}}function UB(f){let $=f.formatAccessToken?.(f.credentials.access)??f.credentials.access,J={...f.settings?.auth??{},accessToken:$,refreshToken:f.credentials.refresh,accountId:f.credentials.accountId,expiresAt:f.credentials.expires},Q={...f.settings??{provider:f.storageProviderId},provider:f.storageProviderId,auth:J};if(f.save!==!1)f.manager.saveProviderSettings(Q,{...f.setLastUsed===void 0?{}:{setLastUsed:f.setLastUsed},tokenSource:"oauth"});return Q}function M6(f){let $=f.storageProviderId??f.providerId;return{providerId:f.providerId,storageProviderId:$,getApiKey(J){let Q=J?.auth?.accessToken?.trim();if(Q)return f.formatAccessToken?.(Q)??Q;return J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0},login:f.login,refresh:f.refresh,saveCredentials(J){return UB({...J,storageProviderId:$,formatAccessToken:f.formatAccessToken})},isConfigured(J){return!!J?.auth?.accessToken},normalizeStoredAccessToken:f.normalizeStoredAccessToken}}var RB=[M6({providerId:"cline",formatAccessToken:BB,normalizeStoredAccessToken:KB,login:({settings:f,callbacks:$,telemetry:J})=>G6({apiBaseUrl:f?.baseUrl?.trim()||jW().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:$,telemetry:J}),refresh:({settings:f,credentials:$,forceRefresh:J,telemetry:Q})=>F6($,{apiBaseUrl:f.baseUrl?.trim()||jW().apiBaseUrl,telemetry:Q},{forceRefresh:J})}),M6({providerId:"oca",login:({settings:f,callbacks:$,telemetry:J})=>T6({mode:f?.oca?.mode,callbacks:$,telemetry:J}),refresh:({settings:f,credentials:$,forceRefresh:J,telemetry:Q})=>z6($,{forceRefresh:J,telemetry:Q},{mode:f.oca?.mode,telemetry:Q})}),M6({providerId:"openai-codex",login:({callbacks:f,telemetry:$})=>U6({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput,telemetry:$}),refresh:({credentials:f,forceRefresh:$,telemetry:J})=>R6(f,{forceRefresh:$,telemetry:J})})],DB=new Map(RB.map((f)=>[f.providerId,f]));function B0(f){return DB.get(f.trim().toLowerCase())}function b1(f){return B0(f)!==void 0}function LB(f){return B0(f)?.storageProviderId}function OB(f,$){let J=B0($),Q=J?.storageProviderId??$,Z=f.getProviderSettings(Q);return J?.getApiKey(Z)??HW($,Z)}async function N6(f,$,J){let Q=B0($);if(!Q)throw Error(`Provider "${$}" does not support OAuth login`);let Z=f.getProviderSettings(Q.storageProviderId),W=await Q.login({settings:Z,callbacks:J.callbacks,telemetry:J.telemetry});return Q.saveCredentials({manager:f,settings:Z,credentials:W})}function q6(f,$){let J=B0(f);if(!J)return null;return FB($,{normalizeAccessToken:J.normalizeStoredAccessToken})}function k1(f){let $=B0(f.providerId);if(!$)throw Error(`Provider "${f.providerId}" does not support OAuth credentials`);return $.saveCredentials({manager:f.manager,settings:f.settings,credentials:f.credentials,setLastUsed:f.setLastUsed,save:f.save})}function HW(f,$){let J=B0(f);if(J)return J.getApiKey($);return $?.auth?.accessToken?.trim()||$?.apiKey?.trim()||$?.auth?.apiKey?.trim()||void 0}function _B(f,$){let J=B0(f);if(!J)return $.access;return J.getApiKey({provider:J.storageProviderId,auth:{accessToken:$.access}})??$.access}import*as C0 from"@cline/llms";import{z}from"zod";import*as f0 from"@cline/llms";function y6(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter(($)=>$.length>0)}function TB(f,$){let J=y6(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let Q=f,Z=y6(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((H)=>H.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[$];if(W&&typeof W==="object"){let H=y6(W.models??W);if(H.length>0)return H}return[]}async function G8(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return TB(await J.json(),$)}function XW(f){return f.replace(/\/+$/,"")}function F8(f,$,J){let Q=J?.trim();if(!Q)return;let Z=f?.trim();if(!Z||!$?.trim())return Q;try{let W=new URL(Q),j=new URL($),H=new URL(Z);if(W.origin!==j.origin)return Q;let X=XW(j.pathname),A=XW(H.pathname);if(X&&W.pathname.startsWith(`${X}/`)){let Y=W.pathname.slice(X.length);H.pathname=`${A}${Y}`}else H.pathname=W.pathname;return H.search=W.search,H.hash=W.hash,H.toString()}catch{return Q}}function zB(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function MB(f){if(f.baseUrl.length===0)return!1;switch(f.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return f.protocol==="openai-chat"}}var NB=Object.values(f0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:zB(f.models),capabilities:f.provider.capabilities?[...f.provider.capabilities]:void 0,env:f.provider.env?[...f.provider.env]:void 0,client:f.provider.client,protocol:f.provider.protocol})),VW=Object.fromEntries(NB.map((f)=>[f.id,f]));function qB(f){return VW[f]}function yB(){return Object.fromEntries(Object.entries(VW).filter(([,f])=>MB(f)))}function BW(f=[]){let $=f.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return $.length>0?$:void 0}var KW="https://models.dev/api.json",wB=600000,PW=300000,CB=5000,R8=new Map,I1=new Map,C6=new Map,U8=new Map;async function SB(){return f0.getGeneratedProviderModels()}async function EB(f,$={},J={},Q={},Z={},W={}){let j=await SB(),H=f0.resolveProviderModelCatalogKeys(f),X=Object.assign({},...H.map((V)=>j[V]??{})),A=Boolean(f0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),Y=Object.keys(Z).length>0;if(A&&Y)return f0.sortModelsByReleaseDate({...Z,...W});if(f==="openai-codex")return f0.sortModelsByReleaseDate({...$,...f0.filterOpenAICodexModels(J),...Z,...W});return f0.sortModelsByReleaseDate({...X,...$,...J,...Q,...Z,...W})}function hB(f,$){let J=f0.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((Q)=>$[Q]??{}))}function D8(f){let $=f?.trim();return $&&$.length>0?$:""}function S6(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function bB(f){let $=2166136261;for(let J=0;J<f.length;J+=1)$^=f.charCodeAt(J),$+=($<<1)+($<<4)+($<<7)+($<<8)+($<<24);return($>>>0).toString(16)}function kB(f,$){return`${f}:${D8($.baseUrl)}:${bB(S6($)??"")}`}async function L8(f,$,J=CB){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch(f,{...$,signal:Q.signal})}finally{clearTimeout(Z)}}function Y$(f,$,J){if(J&&!f.includes($))f.push($)}function O8(f,$){let J=["streaming","tools"];return Y$(J,"images",Boolean($.supportsImages)),Y$(J,"prompt-cache",Boolean($.supportsPromptCache)),Y$(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxInputTokens:$.maxInputTokens,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}async function IB(f,$){let J=await L8("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${$}`,"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 H=j.id?.trim();if(!H)continue;if(H.includes("whisper")||H.includes("tts")||H.includes("embedding"))continue;let X=j.supported_features??[];W[H]=O8(H,{name:H,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return W}function AW(f){if(typeof f==="number")return Number.isFinite(f)?f:void 0;if(typeof f==="string"){let $=Number(f);return Number.isFinite($)?$:void 0}return}async function xB(f,$){let J=await L8("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":$}});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 H=j.id?.trim();if(!H)continue;W[H]=O8(H,{name:H,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}async function gB(f,$){let Q=`${(D8(f.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await L8(Q,{method:"GET",headers:{Authorization:`Bearer ${$}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],H={};for(let X of j){let A=X.id?.trim();if(!A)continue;let Y=X.supported_features??[],V=X.supported_sampling_parameters??[],B=X.input_modalities??[],K=["streaming"];Y$(K,"tools",Y.includes("tools")),Y$(K,"reasoning",Y.includes("reasoning")),Y$(K,"temperature",V.includes("temperature")),Y$(K,"images",B.includes("image"));let P={input:AW(X.pricing?.prompt),output:AW(X.pricing?.completion)};H[A]={id:A,name:X.name??A,description:X.description,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,capabilities:K,pricing:P.input!==void 0||P.output!==void 0?P:void 0,status:"active"}}return H}function mB(f){let $=D8(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function vB(f,$){let Q=`${mB(f.baseUrl)}/v1/model/info`,Z=async(A)=>L8(Q,{method:"GET",headers:{accept:"application/json",...A}}),W=await Z({"x-litellm-api-key":$});if(!W.ok)W=await Z({Authorization:`Bearer ${$}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let H=(await W.json())?.data??[],X={};for(let A of H){let Y=A.model_name?.trim(),B=A.litellm_params?.model?.trim()||Y;if(!B)continue;let K=A.model_info,P=O8(B,{name:Y??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(X[B]=P,Y)X[Y]={...P,id:Y,name:Y}}return X}var GW={baseten:IB,hicap:xB,litellm:vB,poolside:gB},YW=new Map,w6=new Map;function cB(f,$){return`${f}:${D8($.baseUrl)}`}async function uB(f,$,J){let Q=f0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=F8(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=$?.cacheTtlMs??PW,j=cB(f,J),H=Date.now(),X=YW.get(j);if(X&&X.expiresAt>H)return X.data;let A=w6.get(j);if(A)return A;let Y=G8(Z,f).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,O8(K,{name:K})]));return YW.set(j,{data:B,expiresAt:H+W}),B}).finally(()=>{w6.delete(j)});return w6.set(j,Y),Y}async function dB(f,$){let J=S6($);if(!J)return{};let Q=GW[f];if(!Q)return{};return Q($,J)}function lB(f,$,J){if(!J)return!1;if(!GW[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(S6(J))}async function pB(f,$,J){let Q=$?.cacheTtlMs??PW,Z=kB(f,J),W=Date.now(),j=C6.get(Z);if(j&&j.expiresAt>W)return j.data;let H=U8.get(Z);if(H)return H;let X=dB(f,J).then((A)=>{return C6.set(Z,{data:A,expiresAt:W+Q}),A}).finally(()=>{U8.delete(Z)});return U8.set(Z,X),X}async function rB(f){return f0.fetchModelsDevProviderModels(f,globalThis.fetch)}async function _8(f={}){let $=f.url??KW,J=f.cacheTtlMs??wB,Q=Date.now(),Z=R8.get($);if(Z&&Z.expiresAt>Q)return Z.data;let W=I1.get($);if(W)return W;let j=rB($).then((H)=>{return R8.set($,{data:H,expiresAt:Q+J}),H}).finally(()=>{I1.delete($)});return I1.set($,j),j}function iB(f){if(f){R8.delete(f),I1.delete(f);return}R8.clear(),I1.clear()}function nB(){C6.clear(),U8.clear()}function aB(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:BW(J.capabilities)}]))}var E6=aB(yB());function FW(f){let $=qB(f);if(!$)return;return{baseUrl:$.baseUrl||void 0,modelId:$.modelId,knownModels:$.knownModels,capabilities:BW($.capabilities)}}async function h6(f,$,J){let Q=FW(f);if(!Q)return;try{let Z=$?.loadLatestOnInit?await _8($):void 0,W=Z?hB(f,Z):{},j=J&&lB(f,$,J)?await pB(f,$,J):{},X=Boolean(f0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,A=X?await uB(f,$,X).catch(()=>({})):{},Y=await EB(f,Q.knownModels,W,j,A,J?.knownModels);return{...Q,knownModels:Y}}catch(Z){if($?.failOnError)throw Z;return Q}}var b6=C0.BUILT_IN_PROVIDER,tB=C0.BUILT_IN_PROVIDER_IDS,sB=C0.isBuiltInProviderId,T8=C0.normalizeProviderId,k6=z.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),UW=z.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),RW=z.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),DW=z.object({apiKey:z.string().optional(),accessToken:z.string().optional(),refreshToken:z.string().optional(),expiresAt:z.number().int().positive().optional(),accountId:z.string().optional()}),oB=z.enum(["none","low","medium","high","xhigh"]),LW=z.object({enabled:z.boolean().optional(),effort:oB.optional(),budgetTokens:z.number().int().positive().optional()}),OW=z.object({accessKey:z.string().optional(),secretKey:z.string().optional(),sessionToken:z.string().optional(),region:z.string().optional(),profile:z.string().optional(),authentication:z.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:z.boolean().optional(),useCrossRegionInference:z.boolean().optional(),useGlobalInference:z.boolean().optional(),endpoint:z.string().url().optional(),customModelBaseId:z.string().optional()}),_W=z.object({projectId:z.string().optional(),region:z.string().optional()}),TW=z.object({apiVersion:z.string().optional(),useIdentity:z.boolean().optional()}),zW=z.object({clientId:z.string().optional(),clientSecret:z.string().optional(),tokenUrl:z.string().url().optional(),resourceGroup:z.string().optional(),deploymentId:z.string().optional(),useOrchestrationMode:z.boolean().optional(),api:z.enum(["orchestration","foundation-models"]).optional(),defaultSettings:z.record(z.string(),z.unknown()).optional()}),MW=z.object({mode:z.enum(["internal","external"]).optional(),usePromptCache:z.boolean().optional()}),NW=z.object({loadLatestOnInit:z.boolean().optional(),loadPrivateOnAuth:z.boolean().optional(),url:z.string().url().optional(),cacheTtlMs:z.number().int().positive().optional(),failOnError:z.boolean().optional()}),t$=z.object({provider:k6,apiKey:z.string().optional(),auth:DW.optional(),model:z.string().optional(),protocol:UW.optional(),client:RW.optional(),routingProviderId:k6.optional(),maxTokens:z.number().int().positive().optional(),contextWindow:z.number().int().positive().optional(),baseUrl:z.string().url().optional(),headers:z.record(z.string(),z.string()).optional(),timeout:z.number().int().positive().optional(),reasoning:LW.optional(),aws:OW.optional(),gcp:_W.optional(),azure:TW.optional(),sap:zW.optional(),oca:MW.optional(),region:z.string().optional(),apiLine:z.enum(["china","international"]).optional(),capabilities:z.array(z.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:NW.optional()});function qW(f){return t$.parse(f)}function yW(f){return t$.safeParse(f)}function eB(f){return f.protocol==="openai-responses"||f.client==="openai"}function Af(f,$={}){let J=f.provider,Q=T8(J),Z=$.includeKnownModels!==!1,W=f.reasoning?.effort||"none",j=W==="none"?void 0:W,H=E6[Q],X=Object.assign({},...C0.resolveProviderModelCatalogKeys(Q).map((R)=>C0.getGeneratedModelsForProvider(R))),A=Object.keys(X)[0],Y=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,V=f.baseUrl??(Q==="oca"?f.oca?.mode==="internal"?O6:_6:H?.baseUrl),B=f.routingProviderId??(eB(f)&&Q!==b6.OPENAI_NATIVE?b6.OPENAI_NATIVE:void 0),K=Z?H?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,P={providerId:J,clientType:f.client,routingProviderId:B,modelId:f.model??H?.modelId??A??"default",...Z?{knownModels:K}:{},apiKey:Y,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:V,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxInputTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:f.reasoning?.budgetTokens,region:f.region??f.aws?.region??f.gcp?.region,apiLine:f.apiLine,useCrossRegionInference:f.aws?.useCrossRegionInference,useGlobalInference:f.aws?.useGlobalInference,aws:f.aws?{accessKey:f.aws.accessKey,secretKey:f.aws.secretKey,sessionToken:f.aws.sessionToken,authentication:f.aws.authentication,profile:f.aws.profile,usePromptCache:f.aws.usePromptCache,endpoint:f.aws.endpoint,customModelBaseId:f.aws.customModelBaseId}:void 0,gcp:f.gcp?{projectId:f.gcp.projectId,region:f.gcp.region}:void 0,azure:f.azure,sap:f.sap,oca:f.oca,capabilities:f.capabilities??H?.capabilities,modelCatalog:f.modelCatalog?{loadLatestOnInit:f.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:f.modelCatalog.loadPrivateOnAuth,url:f.modelCatalog.url,cacheTtlMs:f.modelCatalog.cacheTtlMs,failOnError:f.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(P).filter(([R,G])=>G!==void 0))}function fK(f){let $=qW(f);return Af($)}function $K(f){let $=yW(f);if($.success)return{success:!0,config:Af($.data)};return{success:!1,error:$.error}}import{SESSION_STATUS_VALUES as JK}from"@cline/shared";var I6=JK,QK=["idle","running","pending"];function ZK(f){return!QK.includes(f)}function $0(f){return!ZK(f)}var U0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function wW(f){if(f===!0)return{};if(!f)return;return f}function CW(f){if(f==="user")return"global";return f}class x6{getService;constructor(f){this.getService=f}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent(f){let $=this.getService().ingestEvent(f);return{event:$.event,duplicate:$.duplicate,matchedSpecIds:$.matchedSpecs.map((J)=>J.specId),queuedRuns:$.queuedRuns,suppressions:$.suppressions}}listEvents(f){return this.getService().listEventLogs(f)}getEvent(f){return this.getService().getEventLog(f)}listSpecs(f){return this.getService().listSpecs(f)}listRuns(f){return this.getService().listRuns(f)}}function SW(f){let{host:$}=f;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await $.startSession({source:J.source?.trim()||U0.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:HK(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:f.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 $.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:jK(Z)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function z8(f){let $=WK(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),Q=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),Z=f.context?.logger??f.logger,W=f.context?.telemetry??f.telemetry;if(!$&&!J&&!Q&&!Z&&!W)return f.context;return{...f.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...$?{automation:$}:{}}}function WK(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function jK(f){return{text:f.text,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost},inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function HK(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}import{existsSync as TJ}from"node:fs";import{basename as Lj,isAbsolute as GR,relative as FR}from"node:path";import{createHash as XK}from"node:crypto";import{watch as AK}from"node:fs";import{readdir as YK,readFile as VK}from"node:fs/promises";import{join as BK}from"node:path";function KK(f){return XK("sha1").update(f).digest("hex")}function bW(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function EW(f){return bW(f)&&f.code==="ENOENT"}function hW(f){return bW(f)&&(f.code==="EACCES"||f.code==="EPERM")}class x1{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(f.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=f,this.debounceMs=$?.debounceMs??75,this.emitParseErrors=$?.emitParseErrors??!1;for(let J of f){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(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}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 f of this.watchersByDirectory.values())f.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let f of this.definitions)await this.refreshTypeInternal(f)})}async refreshType(f){let $=this.definitionsByType.get(f);if(!$)throw Error(`Unknown unified config type '${f}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal($)})}getSnapshot(f){let $=this.recordsByType.get(f);return new Map([...$?.entries()??[]].map(([J,Q])=>[J,{...Q}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));return f}emit(f){for(let $ of this.listeners)$(f)}enqueueRefresh(f){return this.refreshQueue=this.refreshQueue.then(f,f),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let f=this.buildDesiredTypesByDirectory();for(let[$,J]of this.watchersByDirectory.entries()){if(f.has($))continue;J.close(),this.watchersByDirectory.delete($)}this.watchedTypesByDirectory=f;for(let $ of f.keys()){if(this.watchersByDirectory.has($))continue;try{let J=AK($,()=>{let Q=this.watchedTypesByDirectory.get($);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get($);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:$})})}catch(J){if(!EW(J)&&!hW(J)){let Q=f.get($);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,error:J,filePath:$})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let f=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let $ of f){let J=this.definitionsByType.get($);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal(f){let{records:$,discoveredDirectories:J}=await this.loadDefinition(f),Q=this.recordsByType.get(f.type)??new Map;for(let[Z,W]of Q.entries()){if($.has(Z))continue;this.emit({kind:"remove",type:f.type,id:Z,filePath:W.filePath})}for(let[Z,W]of $.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(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let Q of f.directories){J.add(Q);let Z=f.discoverFiles?await f.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:H}=W;if(J.add(W.directoryPath),f.includeFile&&!f.includeFile(j,H))continue;try{let X=await VK(H,"utf8"),A={type:f.type,directoryPath:W.directoryPath,fileName:j,filePath:H,content:X},Y=f.parseFile(A),V=f.resolveId(Y,A).trim();if(!V)continue;$.set(V,{type:f.type,id:V,item:Y,filePath:H,fingerprint:KK(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:X,filePath:H})}}}return{records:$,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let f=new Map;for(let[$,J]of this.baseTypesByDirectory.entries())f.set($,new Set(J));for(let[$,J]of this.discoveredDirectoriesByType.entries())for(let Q of J){let Z=f.get(Q);if(Z)Z.add($);else f.set(Q,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await YK(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:BK(f,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch($){if(EW($)||hW($))return[];throw $}}}import{readdir as W5,readFile as CP,stat as Z5}from"node:fs/promises";import{basename as Vf,dirname as SP,extname as m8,join as z0,resolve as l1}from"node:path";import{AGENTS_RULES_FILE_NAME as A7,RULES_CONFIG_DIRECTORY_NAME as Y7,resolveGlobalAgentsRulesPath as EP,resolveRulesConfigSearchPaths as hP,resolveSkillsConfigSearchPaths as bP,resolveWorkflowsConfigSearchPaths as kP,SKILLS_CONFIG_DIRECTORY_NAME as j5,WORKFLOWS_CONFIG_DIRECTORY_NAME as H5}from"@cline/shared/storage";import IP from"yaml";t0();import{existsSync as k8,readFileSync as UP,statSync as RP}from"node:fs";import{basename as DP,dirname as h8,join as I8,resolve as b8}from"node:path";import{discoverPluginModulePaths as LP,resolveConfiguredPluginModulePaths as Z7,resolvePluginConfigSearchPaths as OP,SKILLS_CONFIG_DIRECTORY_NAME as _P}from"@cline/shared/storage";import{resolve as nK}from"node:path";import{normalizePluginManifest as aK}from"@cline/shared";import{existsSync as H0,readFileSync as f1}from"node:fs";import{builtinModules as wK,createRequire as p6}from"node:module";import{dirname as Cf,extname as m1,isAbsolute as CK,resolve as c}from"node:path";import{fileURLToPath as vW}from"node:url";import{PLUGIN_FILE_EXTENSIONS as SK}from"@cline/shared";var cW=Cf(vW(import.meta.url)),EK=p6(import.meta.url),hK=c(cW,"..","..","..","..",".."),u6=IK(hK),bK=["@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"],r6=new Set(wK.flatMap((f)=>[f,f.replace(/^node:/,"")])),g1=new Set(SK),kK=["development","node","import","require","default"];function IK(f){let $={},J={"@cline/sdk":c(f,"packages/sdk/src/index.ts"),"@cline/agents":c(f,"packages/agents/src/index.ts"),"@cline/core":c(f,"packages/core/src/index.ts"),"@cline/llms":c(f,"packages/llms/src/index.ts"),"@cline/shared":c(f,"packages/shared/src/index.ts"),"@cline/shared/storage":c(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":c(f,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(H0(Z))$[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=c(f,"packages",Q),W=c(Z,"package.json");if(!H0(W))continue;try{let j=JSON.parse(f1(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let H=c(Z,j.exports);if(H0(H))$[j.name]=H;continue}if(typeof j.exports!=="object")continue;for(let[H,X]of Object.entries(j.exports)){let A=xK(Z,X);if(!A)continue;let Y=H==="."?j.name:`${j.name}/${H.replace(/^\.\//,"")}`;$[Y]=A}}catch{}}return $}function xK(f,$){let J=i6($);if(!J)return null;let Q=uW(f,J);for(let Z of Q)if(H0(Z))return Z;return null}function i6(f,$=new Set){if(typeof f==="string")return f;if(!f||typeof f!=="object")return null;if($.has(f))return null;$.add(f);let J=f;for(let Q of kK){let Z=i6(J[Q],$);if(Z)return Z}return null}function uW(f,$){let J=$.replace(/^\.\//,""),Q=[c(f,$)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[c(f,`${Z}.ts`),c(f,`${Z}.tsx`),c(f,`${Z}.mts`),c(f,`${Z}.cts`),...Q]}return Q}function gK(f){return Object.fromEntries(Object.entries(f).sort(([$],[J])=>J.length-$.length))}function w8(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function e$(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function mK(f){let $=e$(f);if(f===$)return".";return`.${f.slice($.length)}`}function dW(f){return e$(f).startsWith("@cline/")}function d6(f,$){let J=e$($),Q=Cf(f);while(!0){let Z=c(Q,"node_modules",J);if(H0(Z)||H0(c(Z,"package.json")))return!0;let W=c(Q,"..");if(W===Q)return!1;Q=W}}function mW(f){return l6(f)!==null}function l6(f){try{return EK.resolve(f)}catch{}return vK(f)}function vK(f){let $=e$(f),J=lW($);if(!J)return null;let Q=c(J,"package.json");try{let Z=JSON.parse(f1(Q,"utf8")),W=mK(f),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,H=i6(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!H)return null;let X=c(J,H),A=[X,...uW(J,H).filter((Y)=>Y!==X)];for(let Y of A)if(H0(Y))return Y;return null}catch{return null}}function cK(){let f=[cW],$=process.env.CLINE_WRAPPER_PATH?.trim();if($)f.push(Cf(Cf($)));let J=process.execPath?.trim();if(J)f.push(Cf(J));return[...new Set(f.map((Q)=>c(Q)))]}function uK(f,$){let J=f;while(!0){let Q=c(J,"package.json");if(H0(Q))try{if(JSON.parse(f1(Q,"utf8")).name===$)return J}catch{}let Z=c(J,"node_modules",$,"package.json");if(H0(Z))return Cf(Z);let W=c(J,"..");if(W===J)return null;J=W}}function lW(f){for(let $ of cK()){let J=uK($,f);if(J)return J}return null}function dK(f){let J=Cf(f);for(let Q=0;Q<4;Q++){let Z=c(J,"package.json");if(H0(Z))try{let j=JSON.parse(f1(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 pW(f,$){let J=$.startsWith("file:")?vW($):CK($)?$:c(Cf(f),$);if(H0(J)&&g1.has(m1(J)))return J;for(let Q of g1){let Z=`${J}${Q}`;if(H0(Z))return Z}for(let Q of g1){let Z=c(J,`index${Q}`);if(H0(Z))return Z}return null}function rW(f){let $=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 f.matchAll(Q)){let W=Z[1];if(W)$.add(W)}return[...$]}function lK(f){return m1(f)!==".ts"}function iW(f,$,J=new Set){if(J.has(f)||!H0(f))return;if(J.add(f),!g1.has(m1(f)))return;let Q=f1(f,"utf8"),Z=lK(f);for(let W of rW(Q)){if(W.startsWith("node:")||r6.has(W))continue;if(w8(W)){if(!Z)continue;if(Object.hasOwn(u6,W)||Object.hasOwn(u6,e$(W))||d6(f,W)||dW(W)&&mW(W)||$&&mW(W))continue;throw Error(`Cannot find module '${e$(W)}'`)}let j=pW(f,W);if(j)iW(j,$,J)}}function nW(f,$=new Set,J=new Set){if($.has(f)||!H0(f))return J;if($.add(f),!g1.has(m1(f)))return J;let Q=f1(f,"utf8");for(let Z of rW(Q)){if(J.add(Z),w8(Z))continue;let W=pW(f,Z);if(W)nW(W,$,J)}return J}function pK(f,$){let J=p6(f),Q={},Z=nW(f),W=new Set(bK);for(let[j,H]of Object.entries(u6)){try{J.resolve(j);continue}catch{}Q[j]=H}for(let j of Z)if(w8(j)&&(dW(j)||$))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||d6(f,j))continue;let H=l6(j);if(H)Q[j]=H}if(!$)return Q;for(let j of Z){if(!w8(j)||Object.hasOwn(Q,j)||d6(f,j)||j.startsWith("node:")||r6.has(j))continue;let H=l6(j);if(H)Q[j]=H}return Q}function rK(f){let $=m1(f);return $===".ts"||$===".tsx"||$===".mts"||$===".cts"}var V$;function iK(){if(V$!==void 0)return V$;let f=lW("jiti");if(!f)return V$=null,null;let $=c(f,"dist","babel.cjs");if(!H0($))return V$=null,null;try{let Q=p6($)($);V$=typeof Q==="function"?Q:null}catch{V$=null}return V$}async function aW(f,$={}){let J=!dK(f);iW(f,J);let Q=pK(f,J),Z=gK(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 H=Object.entries(Z).filter(([,V])=>rK(V)).map(([V])=>V),X=iK(),A=X?(V)=>X({...V,interopDefault:!0}):void 0;return await j(f,{alias:Z,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...r6],transformModules:H,tryNative:!1,...A?{transform:A}:{}}).import(f,{})}function tW(f,$){if(!f)return!0;if(f.providerIds?.length){if(!$?.providerId||!f.providerIds.includes($.providerId))return!1}if(f.modelIds?.length){if(!$?.modelId||!f.modelIds.includes($.modelId))return!1}return!0}function sW(f){return typeof f==="object"&&f!==null}function n6(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function tK(f,$){if(!sW(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!n6(f.manifest.capabilities))throw Error(`Invalid plugin module at ${$}: manifest.capabilities must be a string array`);if(f.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${$}: manifest.capabilities cannot be empty`);if(Object.hasOwn(f.manifest,"providerIds")&&!n6(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!n6(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function sK(f,$){if(!sW(f))throw Error(`Invalid plugin module at ${$}: expected object export`);if(typeof f.name!=="string"||f.name.length===0)throw Error(`Invalid plugin module at ${$}: expected non-empty "name"`);if(!Object.hasOwn(f,"manifest"))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);tK(f,$)}async function a6(f,$={}){let J=nK($.cwd??process.cwd(),f),Q=await aW(J,{useCache:$.useCache}),Z=$.exportName??"plugin",W=Q.default??Q[Z];sK(W,J);let j=W,H=j.setup,X=H?(A,Y)=>{let V={...$.session,...Y.session},B={...Y,session:Object.keys(V).length>0?V:void 0,client:$.client??Y.client,user:$.user??Y.user,workspaceInfo:$.workspaceInfo??Y.workspaceInfo,automation:$.automation??Y.automation,logger:$.logger??Y.logger,telemetry:$.telemetry??Y.telemetry};return H(A,B)}:void 0;return{...j,manifest:aK(j.manifest),setup:X}}async function oW(f,$={}){return(await v1(f,$)).plugins}async function v1(f,$={}){let J=[],Q=[],Z=new Map,W=0;for(let H of f)try{let X=await a6(H,$);if(!tW(X.manifest,$))continue;let A=Z.get(X.name);if(A)Q.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:H,overriddenPluginPath:A.pluginPath,message:`Plugin "${X.name}" from ${H} overrides ${A.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:H,order:W++})}catch(X){let A=X instanceof Error?X.message:String(X);J.push({pluginPath:H,phase:"load",message:A,stack:X instanceof Error?X.stack:void 0})}let j=[...Z.values()].sort((H,X)=>H.order-X.order);return{plugins:j.map((H)=>H.plugin),pluginPaths:j.map((H)=>H.pluginPath),failures:J,warnings:Q}}import{existsSync as o6}from"node:fs";import{createRequire as Q7}from"node:module";import{dirname as S8,join as $1}from"node:path";import{fileURLToPath as ZP}from"node:url";import{spawn as oK}from"node:child_process";import{basename as eK}from"node:path";import{augmentNodeCommandForDebug as fP,withResolvedClineBuildEnv as $P}from"@cline/shared";function eW(f){if(f instanceof Error)return f;return Error(String(f))}var JP="CLINE_JS_RUNTIME_PATH";function f7(f){let $=f?.trim();if(!$)return!1;let J=eK($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function $7(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[JP]?.trim();if(J)return J;let Q=f.execPath?.trim()||process.execPath;if(f7(Q))return Q;for(let Z of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let W=Z?.trim();if(W&&f7(W))return W}return"node"}function QP(f,$={}){let J=$7({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return fP([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class C8{options;process=null;requestCounter=0;pending=new Map;constructor(f){this.options=f}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest(f){let $=this.pending.get(f);if(!$)return;if(this.pending.delete(f),$.timeout)clearTimeout($.timeout);return $}start(){if(this.process&&this.process.exitCode===null)return;let f=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],$=QP(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=oK($[0]??$7(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:$P(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: ${eW(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let H=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${H?`: ${H}`:""}`))})}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:f,args:$};return await new Promise((j,H)=>{let X={resolve:(A)=>j(A),reject:H};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),H(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(Z,X),Q.send(W,(A)=>{if(!A)return;let Y=this.clearPendingRequest(Z);if(!Y)return;Y.reject(Error(`${this.processLabel} failed to send call "${f}": ${eW(A).message}`))})})}async shutdown(){let f=this.process;if(this.process=null,!f||f.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise(($)=>{let J=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}$()},300);f.once("exit",()=>{clearTimeout(J),$()});try{f.kill("SIGTERM")}catch{clearTimeout(J),$()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage(f){if(!f)return;if(f.type==="event"){if(typeof f.name==="string"&&f.name.length>0)this.options.onEvent?.({name:f.name,payload:f.payload});return}if(f.type!=="response"||!f.id)return;let $=this.clearPendingRequest(f.id);if(!$)return;if(f.ok){$.resolve(f.result);return}$.reject(Error(f.error?.message||`${this.processLabel} call failed`))}failPending(f){for(let[$,J]of this.pending.entries()){if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);J.reject(f)}}}function WP(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],rules:f.contributions?.rules??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function c1(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function jP(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function HP(){let f=process.env.CLINE_WRAPPER_PATH?.trim();if(!f)return;try{let J=Q7(f).resolve(`${jP()}/package.json`),Q=$1(S8(J),"extensions","plugin-sandbox-bootstrap.js");return o6(Q)?Q:void 0}catch{return}}function XP(){let f=process.execPath?.trim();if(!f)return;let $=$1(S8(S8(f)),"extensions","plugin-sandbox-bootstrap.js");return o6($)?$:void 0}function AP(){let f=S8(ZP(import.meta.url)),$=Q7(import.meta.url),J=[$1(f,"plugin-sandbox-bootstrap.js"),$1(f,"extensions","plugin-sandbox-bootstrap.js"),$1(f,"agents","plugin-sandbox-bootstrap.js"),HP(),XP()];for(let W of J.filter((j)=>typeof j==="string"))if(o6(W))return{file:W};let Q=$1(f,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=$.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(`
47
+ `)}}var t6=AP();function s6(f,$,J){if(typeof f==="number"&&f>0)return f;if(J){let Q=process.env[J];if(Q){let Z=Number(Q);if(Number.isInteger(Z)&&Z>0)return Z}}return $}async function E8(f){let $=new C8({name:"plugin-sandbox",..."file"in t6?{bootstrapFile:t6.file}:{bootstrapScript:t6.script},onEvent:f.onEvent}),J=s6(f.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=s6(f.hookTimeoutMs,3000),Z=s6(f.contributionTimeoutMs,60000),W={pluginPaths:f.pluginPaths,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,loggerEnabled:Boolean(f.logger)},j,H=()=>{return j??=$.call("initialize",W,{timeoutMs:J}).finally(()=>{j=void 0}),j},X;try{X=await $.call("initialize",W,{timeoutMs:J})}catch(V){throw await $.shutdown().catch(()=>{}),V}let A=X.plugins.map(WP);return{extensions:A.map((V)=>{let B={name:V.name,__clinePluginPath:V.pluginPath,manifest:V.manifest,setup:(K)=>{YP(K,$,V,Z,H),VP(K,$,V,Z,H),BP(K,$,V,Z,H),PP(K,$,V,Z,H),KP(K,V)}};return B.hooks=FP($,V,Q,H),B}),failures:X.failures,pluginPaths:A.map((V)=>V.pluginPath),shutdown:async()=>{await $.shutdown()},warnings:X.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(H,X)=>{try{return await $.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:H,context:X},{timeoutMs:Q})}catch(A){if(!c1(A))throw A;return await Z(),await $.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:H,context:X},{timeoutMs:Q})}}};f.registerTool(j)}}function VP(f,$,J,Q,Z){for(let W of J.contributions?.commands??[])f.registerCommand({name:W.name,description:W.description,handler:async(j)=>{try{return await $.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}catch(H){if(!c1(H))throw H;return await Z(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}}})}function BP(f,$,J,Q,Z){for(let W of J.contributions?.rules??[])f.registerRule({id:W.ruleId,source:W.source,content:W.hasContentHandler===!0?async()=>{try{return await $.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}catch(j){if(!c1(j))throw j;return await Z(),await $.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}}:W.content??""})}function KP(f,$){for(let J of $.contributions?.providers??[])f.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of $.contributions?.automationEventTypes??[])f.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function PP(f,$,J,Q,Z){for(let W of J.contributions?.messageBuilders??[])f.registerMessageBuilder({name:W.name,async build(j){try{let H=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return J7(H)?H:j}catch(H){if(!c1(H))throw H;await Z();let X=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return J7(X)?X:j}}})}function J7(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function GP(f,$,J,Q,Z){return async(W)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:W},{timeoutMs:Q})}catch(j){if(!c1(j))throw j;return await Z(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:W},{timeoutMs:Q})}}}function FP(f,$,J,Q){let Z={};for(let W of $.hooks??[])Z[W]=GP(f,$.pluginId,W,J,Q);return Object.keys(Z).length>0?Z:void 0}var f5="package.json",TP="package";function $5(f){return OP(f)}function J5(f){return LP(f)}function zP(f){try{return k8(f)&&RP(f).isDirectory()}catch{return!1}}function Q5(f){let $=[],J=new Set;for(let Q of f){let Z=b8(Q);if(J.has(Z))continue;J.add(Z),$.push(Z)}return $}function W7(f){let $=Q5(f);return v6($)}function j7(f){return $5(f).flatMap(($)=>J5($)).filter(($)=>k8($))}function MP(f,$){let J=[];for(let Q of f)try{J.push(...Z7([Q],$))}catch{}return J}function e6(f){return typeof f==="object"&&f!==null}function NP(f){try{let $=JSON.parse(UP(I8(f,f5),"utf8"));if(!e6($)||!e6($.cline))return[];let J=$.cline.plugins;if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(typeof Z==="string"){Q.push(Z);continue}if(!e6(Z)||!Array.isArray(Z.paths))continue;for(let W of Z.paths)if(typeof W==="string")Q.push(W)}return Q}catch{return[]}}function H7(f,$){let J=b8($);return NP(f).some((Q)=>b8(f,Q)===J)}function qP(f,$){return DP(f)===TP&&k8(I8(h8(f),f5))&&H7(h8(f),$)}function yP(f){let $=b8(f),J=[],Q=h8($);while(!0){if(qP(Q,$)){J.push(Q);break}if(k8(I8(Q,f5))){if(H7(Q,$))J.push(Q);break}let Z=h8(Q);if(Z===Q)break;Q=Z}return Q5(J)}function u1(f={}){let $=f.cwd??process.cwd(),J=j7(f.workspacePath),Q=Z7(f.pluginPaths??[],$);return W7([...Q,...J])}function wP(f={}){let $=f.cwd??process.cwd(),J=j7(f.workspacePath),Q=MP(f.pluginPaths??[],$);return W7([...Q,...J])}function d1(f){let $=[];for(let J of f)for(let Q of yP(J)){let Z=I8(Q,_P);if(zP(Z))$.push(Z)}return Q5($)}function X7(f={}){return d1(wP(f))}async function x8(f={}){let $=u1(f);if($.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if(f.mode==="in_process"){let Q=await v1($,{cwd:f.cwd,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,automation:f.automation,logger:f.logger,telemetry:f.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let J=await E8({pluginPaths:$,exportName:f.exportName,importTimeoutMs:f.importTimeoutMs,hookTimeoutMs:f.hookTimeoutMs,contributionTimeoutMs:f.contributionTimeoutMs,onEvent:f.onEvent,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,logger:f.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}var g8="SKILL.md",xP="managed.json",gP=new Set([".md",".markdown",".txt"]);function X5(f){return f.trim().toLowerCase()}function J1(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"||$?.code==="ELOOP"}function v8(f){return gP.has(m8(f).toLowerCase())}function V7(f){let $=[],J=new Set;for(let Q of f){let Z=l1(Q);if(J.has(Z))continue;J.add(Z),$.push(Q)}return $}function mP(f){let $=[...f?.directories??P5(f?.workspacePath)];if(f?.pluginSkillDirectories)$.push(...f.pluginSkillDirectories);else if(f?.includePluginSkills)$.push(...X7({pluginPaths:f.pluginPaths,workspacePath:f.workspacePath,cwd:f.cwd??f.workspacePath}));return V7($)}async function A5(f){try{let $=await W5(f,{withFileTypes:!0}),J=[];for(let Q of $){if(!Q.isDirectory())continue;let Z=z0(f,Q.name),W=z0(Z,xP);try{let j=await CP(W,"utf8"),H=JSON.parse(j);if(H&&typeof H==="object")J.push(Z)}catch(j){if(J1(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch($){if(J1($))return[];throw $}}function Y5(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=IP.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:f,hadFrontmatter:!0,parseError:j}}}function c8(f,$,J){if(f===void 0||f===null){if(J)throw Error(`Missing required frontmatter field '${$}'.`);return}if(typeof f!=="string")throw Error(`Frontmatter field '${$}' must be a string.`);let Q=f.trim();if(!Q&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return Q||void 0}function Q1(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function vP(f,$){if(Vf(f.filePath).toLowerCase()!==A7.toLowerCase())return Vf(f.filePath,m8(f.filePath));if($&&l1(f.filePath)===l1($,A7))return"Workspace AGENTS.md";if(l1(f.filePath)===l1(EP()))return"Global AGENTS.md";return Vf(f.filePath,m8(f.filePath))}function V5(f,$){let{data:J,body:Q,parseError:Z}=Y5(f);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 H=c8(J.name,"name",!1)??$.trim();if(!H)throw Error("Missing skill name.");return{name:H,description:c8(J.description,"description",!1),disabled:Q1(J.disabled,"disabled")??(Q1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function B5(f,$){let{data:J,body:Q,parseError:Z}=Y5(f);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=c8(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:Q1(J.disabled,"disabled")??(Q1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function K5(f,$){let{data:J,body:Q,parseError:Z}=Y5(f);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=c8(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:Q1(J.disabled,"disabled")??(Q1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function P5(f){return bP(f)}function G5(f){return hP(f)}function F5(f){return kP(f)}async function B7(f){if(Vf(f)===".cline"){let $=await A5(f);return(await Promise.all($.map((Q)=>B7(z0(Q,j5))))).flat()}try{let $=await W5(f,{withFileTypes:!0}),J=[];for(let Q of $){if(Q.isFile()&&Q.name===g8){J.push({directoryPath:f,fileName:Q.name,filePath:z0(f,Q.name)});continue}let Z=z0(f,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await Z5(Z).then((j)=>j.isDirectory()).catch((j)=>{if(J1(j))return!1;throw j}))J.push({directoryPath:Z,fileName:g8,filePath:z0(Z,g8)})}return J}catch($){if(J1($))return[];throw $}}async function u8(f){if(Vf(f)===".cline"){let $=await A5(f);return(await Promise.all($.map((Q)=>u8(z0(Q,"rules.md"))))).flat()}try{if((await Z5(f)).isFile())return[{directoryPath:SP(f),fileName:Vf(f),filePath:f}]}catch($){if(!J1($))throw $}try{let J=(await W5(f,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&v8(Z.name)).map((Z)=>({directoryPath:f,fileName:Z.name,filePath:z0(f,Z.name)})),Q=z0(f,"AGENTS.md");try{if((await Z5(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch($){if(J1($))return[];throw $}}async function cP(f){if(Vf(f)===".cline"){let $=await A5(f);return(await Promise.all($.map((Q)=>u8(z0(Q,H5))))).flat()}return u8(f)}function U5(f){let $=mP(f),J=f?.workspacePath?z0(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?V7([...$,J]):$,discoverFiles:B7,includeFile:(Q)=>Q===g8,parseFile:(Q)=>V5(Q.content,Vf(Q.directoryPath)),resolveId:(Q)=>X5(Q.name)}}function R5(f){let $=f?.directories??G5(f?.workspacePath),J=f?.workspacePath?z0(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:u8,includeFile:(Q,Z)=>Q===".clinerules"||v8(Q)||v8(Z),parseFile:(Q)=>B5(Q.content,vP(Q,f?.workspacePath)),resolveId:(Q)=>X5(Q.name)}}function D5(f){let $=f?.directories??F5(f?.workspacePath),J=f?.workspacePath?z0(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:cP,includeFile:(Q)=>v8(Q),parseFile:(Q)=>K5(Q.content,Vf(Q.filePath,m8(Q.filePath))),resolveId:(Q)=>X5(Q.name)}}function K7(f){let $=[U5(f?.skills),R5(f?.rules),D5(f?.workflows)];return new x1($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as P7}from"@cline/shared";function uP(f,$){if(f.description?.trim())return P7(f.description,".");if($==="workflow")return;return P7(f.instructions,".")}function dP(f){return f.disabled!==!0}function G7(f,$){return[...f.getSnapshot($).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>dP(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:uP(Q.item,$),kind:$})).sort((J,Q)=>J.name.localeCompare(Q.name))}function p1(f){let $=new Map;for(let J of[...G7(f,"workflow"),...G7(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function F7(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let Q=J[1];if(!Q)return f;let Z=Q.length+1,W=f.slice(Z),j=p1($).find((H)=>H.name===Q);return j?`${j.instructions}${W}`:f}function U7(f){return f.disabled!==!0}function d8(f){if(f.length===0)return"";return`
48
48
 
49
49
  # Rules
50
- ${$.map((J)=>`## ${J.name}
50
+ ${f.map((J)=>`## ${J.name}
51
51
  ${J.instructions}`).join(`
52
52
 
53
- `)}`}function k8($,f){let J=$?.trim(),W=f?.trim();if(J&&W)return`${J}
53
+ `)}`}function l8(f,$){let J=f?.trim(),Q=$?.trim();if(J&&Q)return`${J}
54
54
 
55
- ${W}`;return J||W||void 0}function BG($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(tQ).sort((J,W)=>J.name.localeCompare(W.name))}function sQ($){return b8(BG($))}import{validateWithZod as EC,zodToJsonSchema as bC}from"@cline/shared";var j0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},o1=[j0.READ_FILES,j0.SEARCH_CODEBASE,j0.RUN_COMMANDS,j0.FETCH_WEB_CONTENT,j0.APPLY_PATCH,j0.EDITOR,j0.SKILLS,j0.ASK,j0.SUBMIT_AND_EXIT];B0();import{createTool as H$,validateWithZod as X$,zodToJsonSchema as t0}from"@cline/shared";var oQ="__clineInternalTelemetry";function eQ($){let f=$?.__clineInternalTelemetry;return f&&typeof f==="object"&&"capture"in f&&typeof f.capture==="function"?f:void 0}import{validateWithZod as KG}from"@cline/shared";import{z as L}from"zod";var y$=6000,xf=L.string().describe("The absolute file path of a text file to read content from"),$7=L.object({start_line:L.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:L.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),M$=L.object({path:xf,start_line:$7.shape.start_line,end_line:$7.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),I8=L.object({files:L.array(M$).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.")}),f7=L.union([I8,M$,L.array(M$),L.array(L.string()),L.string(),L.object({files:L.array(L.union([xf,M$]))}),L.object({files:M$}),L.object({files:xf}),L.object({file_paths:L.array(xf)}),L.object({file_paths:L.string()}),L.object({paths:L.array(L.union([xf,M$]))}),L.object({paths:M$}),L.object({paths:L.string()})]),x8=L.object({queries:L.array(L.string()).describe("Array of regex search queries to execute")}),J7=L.union([x8,L.array(L.string()),L.string(),L.object({queries:L.string()})]),X1=L.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${y$*2} characters) to avoid timeouts.`),mf=L.object({commands:L.array(X1).describe("Array of shell commands to execute")}),W7=L.union([mf,L.object({commands:X1}),L.object({command:X1}),L.object({cmd:X1}),L.array(L.string()),L.string()]),H5=L.object({command:L.string().min(1).describe("The executable to run directly without shell parsing."),args:L.array(L.string()).optional().describe("Optional argv list passed directly to the executable.")}),Z7=L.union([X1,H5]),X5=L.object({commands:L.array(Z7).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.")}),Q7=L.union([mf,X5,L.object({commands:Z7}),L.array(H5),H5,L.object({command:X1}),L.object({cmd:X1}),L.array(L.string()),L.string()]),j7=L.object({url:L.string().describe("The URL to fetch"),prompt:L.string().min(2).describe("Analysis prompt for the fetched content")}),m8=L.object({requests:L.array(j7).describe("Array of the URLs for the web fetch requests")}),g8=L.object({path:L.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:L.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${y$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:L.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${y$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:L.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),v8=L.object({input:L.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),H7=L.union([v8,L.string()]),u8=L.object({skill:L.string().min(1).describe("Name of the skill to execute."),args:L.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),c8=L.object({question:L.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:L.array(L.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),d8=L.object({summary:L.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:L.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
55
+ ${Q}`;return J||Q||void 0}function lP(f){return[...f.getSnapshot("rule").values()].map((J)=>J.item).filter(U7).sort((J,Q)=>J.name.localeCompare(Q.name))}function R7(f){return d8(lP(f))}import{validateWithZod as Mh,zodToJsonSchema as Nh}from"@cline/shared";var K0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},Z1=[K0.READ_FILES,K0.SEARCH_CODEBASE,K0.RUN_COMMANDS,K0.FETCH_WEB_CONTENT,K0.APPLY_PATCH,K0.EDITOR,K0.SKILLS,K0.ASK,K0.SUBMIT_AND_EXIT];V0();import{createTool as Bf,validateWithZod as Kf,zodToJsonSchema as o0}from"@cline/shared";var D7="__clineInternalTelemetry";function L7(f){let $=f?.__clineInternalTelemetry;return $&&typeof $==="object"&&"capture"in $&&typeof $.capture==="function"?$:void 0}import{validateWithZod as pP}from"@cline/shared";import{z as O}from"zod";var Ef=6000,r1=O.string().describe("The absolute file path of a text file to read content from"),O7=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"),Sf=O.object({path:r1,start_line:O7.shape.start_line,end_line:O7.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),p8=O.object({files:O.array(Sf).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.")}),_7=O.union([p8,Sf,O.array(Sf),O.array(O.string()),O.string(),O.object({files:O.array(O.union([r1,Sf]))}),O.object({files:Sf}),O.object({files:r1}),O.object({file_paths:O.array(r1)}),O.object({file_paths:O.string()}),O.object({paths:O.array(O.union([r1,Sf]))}),O.object({paths:Sf}),O.object({paths:O.string()})]),r8=O.object({queries:O.array(O.string()).describe("Array of regex search queries to execute")}),T7=O.union([r8,O.array(O.string()),O.string(),O.object({queries:O.string()})]),B$=O.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${Ef*2} characters) to avoid timeouts.`),i1=O.object({commands:O.array(B$).describe("Array of shell commands to execute")}),z7=O.union([i1,O.object({commands:B$}),O.object({command:B$}),O.object({cmd:B$}),O.array(O.string()),O.string()]),L5=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.")}),M7=O.union([B$,L5]),O5=O.object({commands:O.array(M7).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.")}),N7=O.union([i1,O5,O.object({commands:M7}),O.array(L5),L5,O.object({command:B$}),O.object({cmd:B$}),O.array(O.string()),O.string()]),q7=O.object({url:O.string().describe("The URL to fetch"),prompt:O.string().min(2).describe("Analysis prompt for the fetched content")}),i8=O.object({requests:O.array(q7).describe("Array of the URLs for the web fetch requests")}),n8=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 ${Ef} 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 ${Ef} 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."),a8=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."),y7=O.union([a8,O.string()]),t8=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")}),s8=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")}),o8=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.
56
56
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
57
- 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 q$($){if($ instanceof Error)return $.message;return String($)}function X7($){if(typeof $.old_text==="string"&&$.old_text.length>y$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${y$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>y$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${y$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class A1 extends Error{timeoutMs;constructor($,f){super($);this.name="TimeoutError",this.timeoutMs=f}}function a0($,f,J){return Promise.race([$,new Promise((W,Z)=>{setTimeout(()=>Z(new A1(J,f)),f)})])}function l8($){let{path:f,start_line:J,end_line:W}=$;if(J==null&&W==null)return f;return`${f}:${J??1}-${W??"EOF"}`}function A7($){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 Y7($){let f=KG(Q7,$);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 A5($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${$.command} ${J.join(" ")}`}function V7($,f){let J=$.metadata?.[f];return typeof J==="string"?J:void 0}function B7($,f){z9(eQ($.metadata),{tool_name:"run_commands",effective_timeout_ms:f.effectiveTimeoutMs,timeout_source:f.timeoutSource,command_count:f.commandCount,duration_ms:f.durationMs,ulid:$.sessionId,mode:V7($,"mode"),source:V7($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function K7($,f={}){let J=f.fileReadTimeoutMs??1e4;return H$({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:t0(I8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,Z)=>{let Q=X$(f7,W),j;if(typeof Q==="string")j=[{path:Q}];else if(Array.isArray(Q))j=Q.map((H)=>typeof H==="string"?{path:H}:H);else if("files"in Q)j=(Array.isArray(Q.files)?Q.files:[Q.files]).map((X)=>typeof X==="string"?{path:X}:X);else if("file_paths"in Q)j=(Array.isArray(Q.file_paths)?Q.file_paths:[Q.file_paths]).map((X)=>({path:X}));else if("paths"in Q)j=(Array.isArray(Q.paths)?Q.paths:[Q.paths]).map((X)=>typeof X==="string"?{path:X}:X);else j=[Q];return Promise.all(j.map(async(H)=>{let X=A7(H);if(X)return{query:l8(H),result:"",error:`Invalid file range: ${X}`,success:!1};try{let A=await a0($(H,Z),J,`File read timed out after ${J}ms`);return{query:l8(H),result:A,success:!0}}catch(A){let Y=q$(A);return{query:l8(H),result:"",error:`Error reading file: ${Y}`,success:!1}}}))}})}function G7($,f={}){let J=f.searchTimeoutMs??30000,W=f.cwd??process.cwd();return H$({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:t0(x8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,Q)=>{let j=X$(J7,Z),H=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(H.map(async(X)=>{try{let A=await a0($(X,W,Q),J,`Search timed out after ${J}ms`),Y=A.length>0&&!A.includes("No results found");return{query:X,result:A,success:Y}}catch(A){let Y=q$(A);return{query:X,result:"",error:`Search failed: ${Y}`,success:!1}}}))}})}function P7($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return H$({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:t0(mf),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=X$(W7,Q),X;if(typeof H==="string")X=[H];else if(Array.isArray(H))X=H;else if("commands"in H)X=Array.isArray(H.commands)?H.commands:[H.commands];else if("command"in H)X=[H.command];else X=[H.cmd];return Promise.all(X.map(async(A)=>{let Y=Date.now();try{let V=await a0($(A,Z,j),J,`Command timed out after ${J}ms`);return{query:A,result:V,success:!0}}catch(V){if(V instanceof A1)B7(j,{effectiveTimeoutMs:V.timeoutMs,timeoutSource:W,commandCount:X.length,durationMs:Date.now()-Y});let B=q$(V);return{query:A,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function U7($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return H$({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:t0(X5),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=Y7(Q);return Promise.all(H.map(async(X)=>{let A=Date.now();try{let Y=await a0($(X,Z,j),J,`Command timed out after ${J}ms`);return{query:A5(X),result:Y,success:!0}}catch(Y){if(Y instanceof A1)B7(j,{effectiveTimeoutMs:Y.timeoutMs,timeoutSource:W,commandCount:H.length,durationMs:Date.now()-A});let V=q$(Y);return{query:A5(X),result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function F7($,f={}){let J=f.webFetchTimeoutMs??30000;return H$({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:t0(m8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,Z)=>{let Q=X$(m8,W);return Promise.all(Q.requests.map(async(j)=>{try{let H=await a0($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:H,success:!0}}catch(H){let X=q$(H);return{query:j.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var GG=`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
+ 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 hf(f){if(f instanceof Error)return f.message;return String(f)}function w7(f){if(typeof f.old_text==="string"&&f.old_text.length>Ef)return`Editor input too large: old_text was ${f.old_text.length} characters, exceeding the recommended limit of ${Ef}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(f.new_text.length>Ef)return`Editor input too large: new_text was ${f.new_text.length} characters, exceeding the recommended limit of ${Ef}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class K$ extends Error{timeoutMs;constructor(f,$){super(f);this.name="TimeoutError",this.timeoutMs=$}}function s0(f,$,J){return Promise.race([f,new Promise((Q,Z)=>{setTimeout(()=>Z(new K$(J,$)),$)})])}function e8(f){let{path:$,start_line:J,end_line:Q}=f;if(J==null&&Q==null)return $;return`${$}:${J??1}-${Q??"EOF"}`}function C7(f){let{start_line:$,end_line:J}=f;if($==null||J==null||$<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${$}, end_line: ${J})`}function S7(f){let $=pP(N7,f);if(typeof $==="string")return[$];if(Array.isArray($))return $;if("commands"in $)return Array.isArray($.commands)?$.commands:[$.commands];if("command"in $)return"args"in $?[$]:[$.command];if("cmd"in $)return[$.cmd];return[$]}function _5(f){if(typeof f==="string")return f;let $=f.args??[];if($.length===0)return f.command;let J=$.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${f.command} ${J.join(" ")}`}function E7(f,$){let J=f.metadata?.[$];return typeof J==="string"?J:void 0}function h7(f,$){vZ(L7(f.metadata),{tool_name:"run_commands",effective_timeout_ms:$.effectiveTimeoutMs,timeout_source:$.timeoutSource,command_count:$.commandCount,duration_ms:$.durationMs,ulid:f.sessionId,mode:E7(f,"mode"),source:E7(f,"source"),session_id:f.sessionId,agent_id:f.agentId,conversation_id:f.conversationId,run_id:f.runId,iteration:f.iteration,tool_call_id:f.toolCallId})}function b7(f,$={}){let J=$.fileReadTimeoutMs??1e4;return Bf({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:o0(p8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Q,Z)=>{let W=Kf(_7,Q),j;if(typeof W==="string")j=[{path:W}];else if(Array.isArray(W))j=W.map((H)=>typeof H==="string"?{path:H}:H);else if("files"in W)j=(Array.isArray(W.files)?W.files:[W.files]).map((X)=>typeof X==="string"?{path:X}:X);else if("file_paths"in W)j=(Array.isArray(W.file_paths)?W.file_paths:[W.file_paths]).map((X)=>({path:X}));else if("paths"in W)j=(Array.isArray(W.paths)?W.paths:[W.paths]).map((X)=>typeof X==="string"?{path:X}:X);else j=[W];return Promise.all(j.map(async(H)=>{let X=C7(H);if(X)return{query:e8(H),result:"",error:`Invalid file range: ${X}`,success:!1};try{let A=await s0(f(H,Z),J,`File read timed out after ${J}ms`);return{query:e8(H),result:A,success:!0}}catch(A){let Y=hf(A);return{query:e8(H),result:"",error:`Error reading file: ${Y}`,success:!1}}}))}})}function k7(f,$={}){let J=$.searchTimeoutMs??30000,Q=$.cwd??process.cwd();return Bf({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:o0(r8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=Kf(T7,Z),H=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(H.map(async(X)=>{try{let A=await s0(f(X,Q,W),J,`Search timed out after ${J}ms`),Y=A.length>0&&!A.includes("No results found");return{query:X,result:A,success:Y}}catch(A){let Y=hf(A);return{query:X,result:"",error:`Search failed: ${Y}`,success:!1}}}))}})}function I7(f,$={}){let J=$.bashTimeoutMs??30000,Q=$.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=$.cwd??process.cwd();return Bf({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:o0(i1),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let H=Kf(z7,W),X;if(typeof H==="string")X=[H];else if(Array.isArray(H))X=H;else if("commands"in H)X=Array.isArray(H.commands)?H.commands:[H.commands];else if("command"in H)X=[H.command];else X=[H.cmd];return Promise.all(X.map(async(A)=>{let Y=Date.now();try{let V=await s0(f(A,Z,j),J,`Command timed out after ${J}ms`);return{query:A,result:V,success:!0}}catch(V){if(V instanceof K$)h7(j,{effectiveTimeoutMs:V.timeoutMs,timeoutSource:Q,commandCount:X.length,durationMs:Date.now()-Y});let B=hf(V);return{query:A,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function x7(f,$={}){let J=$.bashTimeoutMs??30000,Q=$.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=$.cwd??process.cwd();return Bf({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:o0(O5),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let H=S7(W);return Promise.all(H.map(async(X)=>{let A=Date.now();try{let Y=await s0(f(X,Z,j),J,`Command timed out after ${J}ms`);return{query:_5(X),result:Y,success:!0}}catch(Y){if(Y instanceof K$)h7(j,{effectiveTimeoutMs:Y.timeoutMs,timeoutSource:Q,commandCount:H.length,durationMs:Date.now()-A});let V=hf(Y);return{query:_5(X),result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function g7(f,$={}){let J=$.webFetchTimeoutMs??30000;return Bf({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:o0(i8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(Q,Z)=>{let W=Kf(i8,Q);return Promise.all(W.requests.map(async(j)=>{try{let H=await s0(f(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:H,success:!0}}catch(H){let X=hf(H);return{query:j.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var rP=`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:
58
58
 
59
59
  *** Begin Patch
60
60
  *** Update File: path/to/file.ts
@@ -90,111 +90,111 @@ Example:
90
90
  </div>
91
91
  );
92
92
  }
93
- *** End Patch`;function R7($,f={}){let J=f.applyPatchTimeoutMs??30000,W=f.cwd??process.cwd();return H$({name:"apply_patch",description:GG,inputSchema:t0(v8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=X$(H7,Z),H=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await a0($({input:H},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(X){return{query:"apply_patch",result:"",error:`apply_patch failed: ${q$(X)}`,success:!1}}}})}function D7($,f={}){let J=f.editorTimeoutMs??30000,W=f.cwd??process.cwd();return H$({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:t0(g8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=X$(g8,Z),H=j.insert_line==null?"edit":"insert",X=X7(j);if(X)return{query:`${H}:${j.path}`,result:"",error:X,success:!1};try{let A=await a0($(j,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${H}:${j.path}`,result:A,success:!0}}catch(A){let Y=q$(A);return{query:`${H}:${j.path}`,result:"",error:`Editor operation failed: ${Y}`,success:!1}}}})}function e1($,f={}){let J=f.skillsTimeoutMs??15000,W='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=H$({name:"skills",description:W,inputSchema:t0(u8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=X$(u8,Q);return a0($(H.skill,H.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let Q=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),Z}function L7($){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:t0(c8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let W=X$(c8,f);return $(W.question,W.options,J)}}}function O7($,f={}){let J=f.submitTimeoutMs??15000;return H$({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:t0(d8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=X$(d8,W);return a0($(Q.summary,Q.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function $f($){let{executors:f,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:Z=!0,enableWebFetch:Q=!0,enableApplyPatch:j=!1,enableEditor:H=!0,enableSkills:X=!0,enableAskQuestion:A=!0,enableSubmitAndExit:Y=!1,...V}=$,B=[];if(J&&f.readFile)B.push(K7(f.readFile,V));if(W&&f.search)B.push(G7(f.search,V));if(Z&&f.bash)if(process.platform==="win32")B.push(U7(f.bash,V));else B.push(P7(f.bash,V));if(Q&&f.webFetch)B.push(F7(f.webFetch,V));if(H&&f.editor)B.push(D7(f.editor,V));else if(j&&f.applyPatch)B.push(R7(f.applyPatch,V));if(X&&f.skills)B.push(e1(f.skills,V));let K=Y?f.submit:void 0;if(A&&f.askQuestion&&!K)B.push(L7(f.askQuestion));if(K)B.push(O7(K,V));return B}import*as w0 from"node:fs/promises";import*as S0 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"},_7=["%%bash","apply_patch","EOF","```"];class f0 extends Error{constructor($){super($);this.name="DiffError"}}function q0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class Y5{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 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(x.MOVE)?(this.lines[this.index++]??"").substring(x.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new f0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",W=this.parseUpdateFile(J,$);W.movePath=f,this.patch.actions[$]=W,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},W=$.split(`
94
- `),Z=0,Q=[x.END,x.UPDATE,x.DELETE,x.ADD,x.END_FILE];while(!Q.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],H=j?.startsWith("@@ ")?j.substring(3):void 0;if(H!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new f0(`Invalid Line:
95
- ${this.lines[this.index]}`);if(H?.trim()){let P=q0(H.trim());for(let U=Z;U<W.length;U++){let F=W[U];if(F&&(q0(F)===P||q0(F.trim())===P)){if(Z=U+1,q0(F.trim())===P&&q0(F)!==P)this.fuzz++;break}}}let[A,Y,V,B]=FG(this.lines,this.index),[K,G,R]=UG(W,A,Z,B);if(K===-1){let P=A.join(`
96
- `);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:P.length>200?`${P.substring(0,200)}...`:P}),this.index=V}else{this.fuzz+=G;for(let P of Y)P.origIndex+=K,J.chunks.push(P);Z=K+A.length,this.index=V}}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=[x.END,x.UPDATE,x.DELETE,x.ADD];while(this.hasMoreLines()&&!J.some((W)=>this.lines[this.index]?.startsWith(W.trim()))){let W=this.lines[this.index++];if(W===void 0)break;if(!W.startsWith("+"))throw new f0(`Invalid Add File line (missing '+'): ${W}`);f.push(W.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
97
- `),chunks:[]}}}function z7($,f){let J=$.length>f.length?$:f,W=$.length>f.length?f:$;if(J.length===0)return 1;let Z=PG(W,J);return(J.length-Z)/J.length}function PG($,f){let J=f.length+1,W=$.length+1,Z=Array(J*W).fill(0),Q=(H,X)=>Z[H*W+X]??0,j=(H,X,A)=>{Z[H*W+X]=A};for(let H=0;H<=f.length;H++)j(H,0,H);for(let H=0;H<=$.length;H++)j(0,H,H);for(let H=1;H<=f.length;H++)for(let X=1;X<=$.length;X++)if(f[H-1]===$[X-1])j(H,X,Q(H-1,X-1));else j(H,X,1+Math.min(Q(H-1,X-1),Q(H,X-1),Q(H-1,X)));return Q(f.length,$.length)}function UG($,f,J,W){if(f.length===0)return[J,0,1];let Z=0,Q=(j)=>{let H=q0(f.join(`
98
- `));for(let A=j;A<$.length;A++){let Y=q0($.slice(A,A+f.length).join(`
99
- `));if(Y===H)return[A,0,1];let V=z7(Y,H);if(V>Z)Z=V}for(let A=j;A<$.length;A++){let Y=q0($.slice(A,A+f.length).map((B)=>B.trimEnd()).join(`
100
- `)),V=q0(f.map((B)=>B.trimEnd()).join(`
101
- `));if(Y===V)return[A,1,1]}for(let A=j;A<$.length;A++){let Y=q0($.slice(A,A+f.length).map((B)=>B.trim()).join(`
102
- `)),V=q0(f.map((B)=>B.trim()).join(`
103
- `));if(Y===V)return[A,100,1]}let X=0.66;for(let A=j;A<$.length;A++){let Y=q0($.slice(A,A+f.length).join(`
104
- `)),V=z7(Y,H);if(V>=X)return[A,1000,V];if(V>Z)Z=V}return[-1,0,Z]};if(W){let[j,H,X]=Q($.length-f.length);if(j!==-1)return[j,H,X];return[j,H,X]=Q(J),[j,H+1e4,X]}return Q(J)}function FG($,f){let J=f,W=[],Z=[],Q=[],j=[],H="keep",X=["@@",x.END,x.UPDATE,x.DELETE,x.ADD,x.END_FILE];while(J<$.length){let A=$[J];if(!A||X.some((B)=>A.startsWith(B.trim())))break;if(A==="***")break;if(A.startsWith("***"))throw new f0(`Invalid line: ${A}`);J++;let Y=H,V=A;if(V[0]==="+")H="add";else if(V[0]==="-")H="delete";else if(V[0]===" ")H="keep";else H="keep",V=` ${V}`;if(V=V.slice(1),H==="keep"&&Y!==H){if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});Z=[],Q=[]}if(H==="delete")Z.push(V),W.push(V);else if(H==="add")Q.push(V);else W.push(V)}if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});if(J<$.length&&$[J]===x.END_FILE)return J++,[W,j,J,!0];return[W,j,J,!1]}function V5($,f,J){let W=S0.isAbsolute(f),Z=W?S0.normalize(f):S0.resolve($,f);if(!J||W)return Z;let Q=S0.relative($,Z);if(Q.startsWith("..")||S0.isAbsolute(Q))throw new f0(`Path must stay within cwd: ${f}`);return Z}function RG($){return $.split(`
105
- `).map((f)=>f.replace(/\r$/,""))}function T7($){if($.trim()==="")return!1;return _7.some((f)=>$.startsWith(f))}function DG($){let f=0,J=$.length;while(f<J&&T7($[f]??""))f++;while(J>f&&T7($[J-1]??""))J--;return $.slice(f,J)}function LG($){let f=RG($),J=f.findIndex((j)=>j.startsWith(x.BEGIN)),W=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(x.END)){W=j;break}if(J!==-1||W!==-1){if(J===-1||W===-1||W<J)throw new f0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,W+1)}}let Z=DG(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 OG($,f){let J=new Set;for(let W of $)for(let Z of f)if(W.startsWith(Z)){J.add(W.substring(Z.length).trim());break}return[...J]}function zG($,f,J){if(f.length===0)return $;let W=$.split(`
106
- `),Z=[],Q=0;for(let j of f){if(j.origIndex>W.length)throw new f0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${W.length}`);if(Q>j.origIndex)throw new f0(`${J}: currentIndex ${Q} > chunk.origIndex ${j.origIndex}`);Z.push(...W.slice(Q,j.origIndex)),Z.push(...j.insLines),Q=j.origIndex+j.delLines.length}return Z.push(...W.slice(Q)),Z.join(`
107
- `)}async function _G($,f,J,W){let Z=OG($,[x.UPDATE,x.DELETE]),Q={};for(let j of Z){let H=V5(f,j,W),X;try{X=await w0.readFile(H,J)}catch{throw new f0(`File not found: ${j}`)}Q[j]=X.replace(/\r\n/g,`
108
- `)}return Q}function TG($,f){let J={};for(let[W,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[W]={type:"delete",oldContent:f[W]};break;case"add":if(Z.newFile===void 0)throw new f0("ADD action without file content");J[W]={type:"add",newContent:Z.newFile};break;case"update":J[W]={type:"update",oldContent:f[W],newContent:zG(f[W]??"",Z.chunks,W),movePath:Z.movePath};break}return J}async function NG($,f,J,W){let Z=[];for(let[Q,j]of Object.entries($)){let H=V5(f,Q,W);switch(j.type){case"delete":await w0.rm(H,{force:!0}),Z.push(`${Q}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new f0(`Cannot create ${Q} with no content`);await w0.mkdir(S0.dirname(H),{recursive:!0}),await w0.writeFile(H,j.newContent,{encoding:J}),Z.push(Q);break;case"update":{if(j.newContent===void 0)throw new f0(`UPDATE change for ${Q} has no new content`);if(j.movePath){let X=V5(f,j.movePath,W);await w0.mkdir(S0.dirname(X),{recursive:!0}),await w0.writeFile(X,j.newContent,{encoding:J}),await w0.rm(H,{force:!0}),Z.push(`${Q} -> ${j.movePath}`)}else await w0.writeFile(H,j.newContent,{encoding:J}),Z.push(Q);break}}}return Z}function p8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(W,Z,Q)=>{let j=LG(W.input),H=await _G(j.lines,Z,f,J),X=new Y5(j.lines,H),{patch:A,fuzz:Y}=X.parse(),V=TG(A,H),B=await NG(V,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of B)K.push(G);if(Y>0)K.push(`Note: Patch applied with fuzz factor ${Y}`);if(A.warnings&&A.warnings.length>0)for(let G of A.warnings)K.push(`Warning (${G.path}): ${G.message}`);return K.join(`
109
- `)}}import{spawn as N7}from"node:child_process";import{getDefaultShell as MG,getShellArgs as yG}from"@cline/shared";function qG($,f,J,W,Z){return new Promise((Q,j)=>{let H=process.platform==="win32",X=N7($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!H}),A=X.pid,Y="",V="",B=0,K=!1,G=!1,R=(D)=>{if(G)return;G=!0,D()},P=()=>{if(!A)return;if(H){N7("taskkill",["/pid",String(A),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-A,"SIGKILL")}catch{X.kill("SIGKILL")}},U=(D)=>{K=!0,P(),R(()=>j(D))},F=setTimeout(()=>U(new A1(`Command timed out after ${J}ms`,J)),J),z=()=>U(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",z);let _=()=>{clearTimeout(F),f.signal?.removeEventListener("abort",z)};X.stdout?.on("data",(D)=>{if(B+=D.length,B<=W)Y+=D.toString()}),X.stderr?.on("data",(D)=>{if(B+=D.length,B<=W)V+=D.toString()}),X.on("close",(D)=>{if(_(),K)return;let O=Z?Y+(V?`
93
+ *** End Patch`;function m7(f,$={}){let J=$.applyPatchTimeoutMs??30000,Q=$.cwd??process.cwd();return Bf({name:"apply_patch",description:rP,inputSchema:o0(a8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=Kf(y7,Z),H=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await s0(f({input:H},Q,W),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(X){return{query:"apply_patch",result:"",error:`apply_patch failed: ${hf(X)}`,success:!1}}}})}function v7(f,$={}){let J=$.editorTimeoutMs??30000,Q=$.cwd??process.cwd();return Bf({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:o0(n8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=Kf(n8,Z),H=j.insert_line==null?"edit":"insert",X=w7(j);if(X)return{query:`${H}:${j.path}`,result:"",error:X,success:!1};try{let A=await s0(f(j,Q,W),J,`Editor operation timed out after ${J}ms`);return{query:`${H}:${j.path}`,result:A,success:!0}}catch(A){let Y=hf(A);return{query:`${H}:${j.path}`,result:"",error:`Editor operation failed: ${Y}`,success:!1}}}})}function W1(f,$={}){let J=$.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=Bf({name:"skills",description:Q,inputSchema:o0(t8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,j)=>{let H=Kf(t8,W);return s0(f(H.skill,H.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let W=f.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 c7(f){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:o0(s8),retryable:!1,maxRetries:0,execute:async($,J)=>{let Q=Kf(s8,$);return f(Q.question,Q.options,J)}}}function u7(f,$={}){let J=$.submitTimeoutMs??15000;return Bf({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:o0(o8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let W=Kf(o8,Q);return s0(f(W.summary,W.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function j1(f){let{executors:$,enableReadFiles:J=!0,enableSearch:Q=!0,enableBash:Z=!0,enableWebFetch:W=!0,enableApplyPatch:j=!1,enableEditor:H=!0,enableSkills:X=!0,enableAskQuestion:A=!0,enableSubmitAndExit:Y=!1,...V}=f,B=[];if(J&&$.readFile)B.push(b7($.readFile,V));if(Q&&$.search)B.push(k7($.search,V));if(Z&&$.bash)if(process.platform==="win32")B.push(x7($.bash,V));else B.push(I7($.bash,V));if(W&&$.webFetch)B.push(g7($.webFetch,V));if(H&&$.editor)B.push(v7($.editor,V));else if(j&&$.applyPatch)B.push(m7($.applyPatch,V));if(X&&$.skills)B.push(W1($.skills,V));let K=Y?$.submit:void 0;if(A&&$.askQuestion&&!K)B.push(c7($.askQuestion));if(K)B.push(u7(K,V));return B}import*as E0 from"node:fs/promises";import*as h0 from"node:path";var m={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},l7=["%%bash","apply_patch","EOF","```"];class J0 extends Error{constructor(f){super(f);this.name="DiffError"}}function S0(f){let $={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return f.normalize("NFC").replace(/./gu,(J)=>$[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class T5{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(f,$){this.lines=f;this.currentFiles=$}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(f){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(f)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(m.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(m.END)??!1}parseNextAction(){let f=this.lines[this.index];if(f?.startsWith(m.UPDATE)){this.parseUpdate(f.substring(m.UPDATE.length).trim());return}if(f?.startsWith(m.DELETE)){this.parseDelete(f.substring(m.DELETE.length).trim());return}if(f?.startsWith(m.ADD)){this.parseAdd(f.substring(m.ADD.length).trim());return}throw new J0(`Unknown line while parsing: ${f}`)}checkDuplicate(f,$){if(f in this.patch.actions)throw new J0(`Duplicate ${$} for file: ${f}`)}parseUpdate(f){this.checkDuplicate(f,"update"),this.currentPath=f,this.index++;let $=this.lines[this.index]?.startsWith(m.MOVE)?(this.lines[this.index++]??"").substring(m.MOVE.length).trim():void 0;if(!(f in this.currentFiles))throw new J0(`Update File Error: Missing File: ${f}`);let J=this.currentFiles[f]??"",Q=this.parseUpdateFile(J,f);Q.movePath=$,this.patch.actions[f]=Q,this.currentPath=void 0}parseUpdateFile(f,$){let J={type:"update",chunks:[]},Q=f.split(`
94
+ `),Z=0,W=[m.END,m.UPDATE,m.DELETE,m.ADD,m.END_FILE];while(!W.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],H=j?.startsWith("@@ ")?j.substring(3):void 0;if(H!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new J0(`Invalid Line:
95
+ ${this.lines[this.index]}`);if(H?.trim()){let G=S0(H.trim());for(let F=Z;F<Q.length;F++){let U=Q[F];if(U&&(S0(U)===G||S0(U.trim())===G)){if(Z=F+1,S0(U.trim())===G&&S0(U)!==G)this.fuzz++;break}}}let[A,Y,V,B]=aP(this.lines,this.index),[K,P,R]=nP(Q,A,Z,B);if(K===-1){let G=A.join(`
96
+ `);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:G.length>200?`${G.substring(0,200)}...`:G}),this.index=V}else{this.fuzz+=P;for(let G of Y)G.origIndex+=K,J.chunks.push(G);Z=K+A.length,this.index=V}}return J}parseDelete(f){if(this.checkDuplicate(f,"delete"),!(f in this.currentFiles))throw new J0(`Delete File Error: Missing File: ${f}`);this.patch.actions[f]={type:"delete",chunks:[]},this.index++}parseAdd(f){if(this.checkDuplicate(f,"add"),f in this.currentFiles)throw new J0(`Add File Error: File already exists: ${f}`);this.index++;let $=[],J=[m.END,m.UPDATE,m.DELETE,m.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}`);$.push(Q.substring(1))}this.patch.actions[f]={type:"add",newFile:$.join(`
97
+ `),chunks:[]}}}function d7(f,$){let J=f.length>$.length?f:$,Q=f.length>$.length?$:f;if(J.length===0)return 1;let Z=iP(Q,J);return(J.length-Z)/J.length}function iP(f,$){let J=$.length+1,Q=f.length+1,Z=Array(J*Q).fill(0),W=(H,X)=>Z[H*Q+X]??0,j=(H,X,A)=>{Z[H*Q+X]=A};for(let H=0;H<=$.length;H++)j(H,0,H);for(let H=0;H<=f.length;H++)j(0,H,H);for(let H=1;H<=$.length;H++)for(let X=1;X<=f.length;X++)if($[H-1]===f[X-1])j(H,X,W(H-1,X-1));else j(H,X,1+Math.min(W(H-1,X-1),W(H,X-1),W(H-1,X)));return W($.length,f.length)}function nP(f,$,J,Q){if($.length===0)return[J,0,1];let Z=0,W=(j)=>{let H=S0($.join(`
98
+ `));for(let A=j;A<f.length;A++){let Y=S0(f.slice(A,A+$.length).join(`
99
+ `));if(Y===H)return[A,0,1];let V=d7(Y,H);if(V>Z)Z=V}for(let A=j;A<f.length;A++){let Y=S0(f.slice(A,A+$.length).map((B)=>B.trimEnd()).join(`
100
+ `)),V=S0($.map((B)=>B.trimEnd()).join(`
101
+ `));if(Y===V)return[A,1,1]}for(let A=j;A<f.length;A++){let Y=S0(f.slice(A,A+$.length).map((B)=>B.trim()).join(`
102
+ `)),V=S0($.map((B)=>B.trim()).join(`
103
+ `));if(Y===V)return[A,100,1]}let X=0.66;for(let A=j;A<f.length;A++){let Y=S0(f.slice(A,A+$.length).join(`
104
+ `)),V=d7(Y,H);if(V>=X)return[A,1000,V];if(V>Z)Z=V}return[-1,0,Z]};if(Q){let[j,H,X]=W(f.length-$.length);if(j!==-1)return[j,H,X];return[j,H,X]=W(J),[j,H+1e4,X]}return W(J)}function aP(f,$){let J=$,Q=[],Z=[],W=[],j=[],H="keep",X=["@@",m.END,m.UPDATE,m.DELETE,m.ADD,m.END_FILE];while(J<f.length){let A=f[J];if(!A||X.some((B)=>A.startsWith(B.trim())))break;if(A==="***")break;if(A.startsWith("***"))throw new J0(`Invalid line: ${A}`);J++;let Y=H,V=A;if(V[0]==="+")H="add";else if(V[0]==="-")H="delete";else if(V[0]===" ")H="keep";else H="keep",V=` ${V}`;if(V=V.slice(1),H==="keep"&&Y!==H){if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});Z=[],W=[]}if(H==="delete")Z.push(V),Q.push(V);else if(H==="add")W.push(V);else Q.push(V)}if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});if(J<f.length&&f[J]===m.END_FILE)return J++,[Q,j,J,!0];return[Q,j,J,!1]}function z5(f,$,J){let Q=h0.isAbsolute($),Z=Q?h0.normalize($):h0.resolve(f,$);if(!J||Q)return Z;let W=h0.relative(f,Z);if(W.startsWith("..")||h0.isAbsolute(W))throw new J0(`Path must stay within cwd: ${$}`);return Z}function tP(f){return f.split(`
105
+ `).map(($)=>$.replace(/\r$/,""))}function p7(f){if(f.trim()==="")return!1;return l7.some(($)=>f.startsWith($))}function sP(f){let $=0,J=f.length;while($<J&&p7(f[$]??""))$++;while(J>$&&p7(f[J-1]??""))J--;return f.slice($,J)}function oP(f){let $=tP(f),J=$.findIndex((j)=>j.startsWith(m.BEGIN)),Q=-1;for(let j=$.length-1;j>=0;j--)if($[j]?.startsWith(m.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:$.slice(J,Q+1)}}let Z=sP($);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[m.BEGIN,...Z,m.END]}}function eP(f,$){let J=new Set;for(let Q of f)for(let Z of $)if(Q.startsWith(Z)){J.add(Q.substring(Z.length).trim());break}return[...J]}function fG(f,$,J){if($.length===0)return f;let Q=f.split(`
106
+ `),Z=[],W=0;for(let j of $){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(`
107
+ `)}async function $G(f,$,J,Q){let Z=eP(f,[m.UPDATE,m.DELETE]),W={};for(let j of Z){let H=z5($,j,Q),X;try{X=await E0.readFile(H,J)}catch{throw new J0(`File not found: ${j}`)}W[j]=X.replace(/\r\n/g,`
108
+ `)}return W}function JG(f,$){let J={};for(let[Q,Z]of Object.entries(f.actions))switch(Z.type){case"delete":J[Q]={type:"delete",oldContent:$[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:$[Q],newContent:fG($[Q]??"",Z.chunks,Q),movePath:Z.movePath};break}return J}async function QG(f,$,J,Q){let Z=[];for(let[W,j]of Object.entries(f)){let H=z5($,W,Q);switch(j.type){case"delete":await E0.rm(H,{force:!0}),Z.push(`${W}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new J0(`Cannot create ${W} with no content`);await E0.mkdir(h0.dirname(H),{recursive:!0}),await E0.writeFile(H,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 X=z5($,j.movePath,Q);await E0.mkdir(h0.dirname(X),{recursive:!0}),await E0.writeFile(X,j.newContent,{encoding:J}),await E0.rm(H,{force:!0}),Z.push(`${W} -> ${j.movePath}`)}else await E0.writeFile(H,j.newContent,{encoding:J}),Z.push(W);break}}}return Z}function fJ(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0}=f;return async(Q,Z,W)=>{let j=oP(Q.input),H=await $G(j.lines,Z,$,J),X=new T5(j.lines,H),{patch:A,fuzz:Y}=X.parse(),V=JG(A,H),B=await QG(V,Z,$,J),K=["Successfully applied patch to the following files:"];for(let P of B)K.push(P);if(Y>0)K.push(`Note: Patch applied with fuzz factor ${Y}`);if(A.warnings&&A.warnings.length>0)for(let P of A.warnings)K.push(`Warning (${P.path}): ${P.message}`);return K.join(`
109
+ `)}}import{spawn as r7}from"node:child_process";import{getDefaultShell as ZG,getShellArgs as WG}from"@cline/shared";function jG(f,$,J,Q,Z){return new Promise((W,j)=>{let H=process.platform==="win32",X=r7(f.executable,f.args,{cwd:f.cwd,env:{...process.env,...f.env},stdio:["pipe","pipe","pipe"],detached:!H}),A=X.pid,Y="",V="",B=0,K=!1,P=!1,R=(L)=>{if(P)return;P=!0,L()},G=()=>{if(!A)return;if(H){r7("taskkill",["/pid",String(A),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-A,"SIGKILL")}catch{X.kill("SIGKILL")}},F=(L)=>{K=!0,G(),R(()=>j(L))},U=setTimeout(()=>F(new K$(`Command timed out after ${J}ms`,J)),J),_=()=>F(Error("Command was aborted"));if($.signal)$.signal.addEventListener("abort",_);let T=()=>{clearTimeout(U),$.signal?.removeEventListener("abort",_)};X.stdout?.on("data",(L)=>{if(B+=L.length,B<=Q)Y+=L.toString()}),X.stderr?.on("data",(L)=>{if(B+=L.length,B<=Q)V+=L.toString()}),X.on("close",(L)=>{if(T(),K)return;let D=Z?Y+(V?`
110
110
  [stderr]
111
- ${V}`:""):Y;if(B>W)O+=`
112
-
113
- [Output truncated: ${B} bytes total, showing first ${W} bytes]`;if(D!==0)R(()=>j(Error(V||`Command exited with code ${D}`)));else R(()=>Q(O))}),X.on("error",(D)=>{_(),R(()=>j(Error(`Failed to execute command: ${D.message}`)))})})}function r8($={}){let{shell:f=MG(process.platform),timeoutMs:J=30000,maxOutputBytes:W=1e6,env:Z={},combineOutput:Q=!0}=$;return(j,H,X)=>{let A=typeof j!=="string";return qG({executable:A?j.command:f,args:A?j.args??[]:yG(f,j),cwd:H,env:Z},X,J,W,Q)}}import*as l0 from"node:fs/promises";import*as d0 from"node:path";function wG($,f,J){let W=d0.isAbsolute(f),Z=W?d0.normalize(f):d0.resolve($,f);if(!J)return Z;if(W)return Z;let Q=d0.relative($,Z);if(Q.startsWith("..")||d0.isAbsolute(Q))throw Error(`Path must stay within cwd: ${f}`);return Z}function SG($,f){if(f.length===0)return 0;return $.split(f).length-1}function hG($,f,J){let W=$.split(`
114
- `),Z=f.split(`
115
- `),Q=Math.max(W.length,Z.length),j=["```diff"],H=0;for(let X=0;X<Q;X++){if(H>=J){j.push("... diff truncated ...");break}let A=W[X],Y=Z[X];if(A===Y)continue;let V=X+1;if(A!==void 0)j.push(`-${V}: ${A}`),H++;if(Y!==void 0&&H<J)j.push(`+${V}: ${Y}`),H++}return j.push("```"),j.join(`
116
- `)}async function CG($,f,J){return await l0.mkdir(d0.dirname($),{recursive:!0}),await l0.writeFile($,f,{encoding:J}),`File created successfully at: ${$}`}async function EG($){try{return await l0.access($),!0}catch{return!1}}async function bG($,f,J,W,Z){let Q=await l0.readFile($,W),j=SG(Q,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 H=Q.replace(f,J??"");await l0.writeFile($,H,{encoding:W});let X=hG(Q,H,Z);return`Edited ${$}
117
- ${X}`}async function kG($,f,J,W){let Q=(await l0.readFile($,W)).split(`
118
- `),j=Q.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 H=f-1;return Q.splice(H,0,...J.split(`
119
- `)),await l0.writeFile($,Q.join(`
120
- `),{encoding:W}),`Inserted content at line ${f} in ${$}.`}function i8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=$;return async(Z,Q,j)=>{let H=wG(Q,Z.path,J);if(Z.insert_line!=null)return kG(H,Z.insert_line,Z.new_text,f);if(!await EG(H))return CG(H,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 bG(H,Z.old_text,Z.new_text,f,W)}}import*as gf from"node:fs/promises";import*as w$ from"node:path";import{resolveExistingFilePath as IG}from"@cline/shared/storage";var xG=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),mG={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function n8($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:W}={...mG,...$};return async(Z,Q)=>{let{path:j,start_line:H,end_line:X}=Z,A=w$.isAbsolute(j)?w$.normalize(j):w$.resolve(process.cwd(),j),Y=IG(A)??A,V=w$.extname(Y).toLowerCase(),B=xG.get(V),K=await gf.stat(Y);if(!K.isFile())throw Error(`Path is not a file: ${Y}`);if(K.size>f)throw Error(`File too large: ${K.size} bytes (max: ${f} bytes). Consider reading specific sections or using a different approach.`);if(B){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let z=await gf.readFile(Y);return[{type:"text",text:"Successfully read image"},{type:"image",data:z.toString("base64"),mediaType:B}]}let R=(await gf.readFile(Y,J)).split(`
121
- `),P=Math.max((H??1)-1,0),U=Math.min(X??R.length,R.length),F=R.slice(P,U);if(W){let z=String(R.length).length;return F.map((_,D)=>`${String(P+D+1).padStart(z," ")} | ${_}`).join(`
122
- `)}return F.join(`
123
- `)}}import{spawn as C7}from"node:child_process";import*as E7 from"node:fs/promises";import*as s8 from"node:path";import{spawn as gG}from"node:child_process";import{readdir as vG}from"node:fs/promises";import K5 from"node:path";import{isMainThread as q7,parentPort as M7,Worker as uG}from"node:worker_threads";var cG=15000,dG=600000,lG=1000,pG=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function y7($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var ff=new Map;function rG(){if(!q7)return!1;return!0}function iG($){if(ff.size<=1)return;for(let[f,J]of ff.entries()){if(J.pending)continue;if($-J.lastAccessedAt>dG)ff.delete(f)}}function nG($,f){return K5.relative($,f).split(K5.sep).join("/")}async function aG($){let J=(await new Promise((W,Z)=>{let Q=gG("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),j="",H="";Q.stdout.on("data",(X)=>{j+=X.toString()}),Q.stderr.on("data",(X)=>{H+=X.toString()}),Q.on("error",Z),Q.on("close",(X)=>{if(X===0){W(j);return}Z(Error(H||`rg exited with code ${X}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function w7($,f,J){let W;try{W=await vG(f,{withFileTypes:!0})}catch(Z){if(y7(Z))return;throw Z}for(let Z of W){let Q=K5.join(f,Z.name);if(Z.isDirectory()){if(pG.has(Z.name))continue;try{await w7($,Q,J)}catch(j){if(y7(j))continue;throw j}continue}if(Z.isFile())J.add(nG($,Q))}}async function tG($){let f=new Set;return await w7($,$,f),f}async function a8($){try{return await aG($)}catch{return tG($)}}function sG(){if(q7||!M7)return;let $=M7;$.on("message",(f)=>{if(f.type!=="index")return;a8(f.cwd).then((J)=>{let W={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(W)})})}class S7{worker=new uG(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let f=++this.nextRequestId,J=new Promise((Z,Q)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},lG);j.unref(),this.pending.set(f,{resolve:(H)=>{clearTimeout(j),Z(H)},reject:(H)=>{clearTimeout(j),Q(H)}})}),W={type:"index",requestId:f,cwd:$};return this.worker.postMessage(W),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}sG();var B5;function oG(){if(!rG())return null;if(B5===void 0)B5=new S7;return B5}async function eG($){let f=oG();if(!f)return a8($);try{let J=await f.requestIndex($);if(J===null)return a8($);return new Set(J)}catch{return a8($)}}async function Y1($,f={}){let J=f.ttlMs??cG,W=Date.now();iG(W);let Z=ff.get($);if(Z&&J>0&&W-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=W,Z.files;if(Z?.pending)return Z.lastAccessedAt=W,Z.pending;let Q=eG($).then((j)=>{return ff.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return ff.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function h7($,f={}){await Y1($,{...f,ttlMs:0})}import{stat as $P}from"node:fs/promises";import V1 from"node:path";var fP=/[),.:;!?`'"]+$/,JP=/^[(`'"]+/;function WP($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of f){let Z=(W[2]??"").trim();if(Z.length===0)continue;let Q=Z.replace(JP,"").replace(fP,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function ZP($,f){let J=$.replace(/\\/g,"/"),W=V1.isAbsolute(J)?V1.resolve(J):V1.resolve(f,J),Z=V1.relative(f,W);if(Z.startsWith("..")||V1.isAbsolute(Z))return;return Z.split(V1.sep).join("/")}async function t8($,f,J={}){let W=WP($);if(W.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:Q,maxTotalBytes:j}=J,H=await Y1(f,{ttlMs:J.ttlMs}),X=[],A=[],Y=[],V=0;for(let B of W){if(Z&&Y.length>=Z){A.push(B);continue}let K=ZP(B,f);if(!K||!H.has(K)){A.push(B);continue}if(!Q||!j){X.push(K);continue}let G=V1.join(f,K);try{if(!(await $P(G)).isFile()){A.push(B);continue}let P=V+Q;if(P>j){A.push(B);continue}V=P,X.push(K)}catch{A.push(B)}}return{prompt:$,mentions:W,matchedFiles:X,ignoredMentions:A}}var QP=["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"],jP=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],B1=null;function HP(){if(B1!==null)return Promise.resolve(B1);return new Promise(($)=>{let f=C7("rg",["--version"],{stdio:["ignore","pipe","pipe"]});f.on("close",(J)=>{B1=J===0,$(B1)}),f.on("error",()=>{B1=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(B1===null)B1=!1,$(!1)},1000)})}function XP($,f,J,W,Z=5000,Q){return new Promise((j)=>{let H=C7("rg",["--json",`--context=${W}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"]}),X="",A=!1,Y=()=>{if(!H.killed)H.kill("SIGTERM")},V=setTimeout(()=>{if(!A)A=!0,Y(),j(null)},Z),B=(K)=>{if(!A)A=!0,clearTimeout(V),Y(),j(K)};if(Q?.aborted){Y(),j(null);return}Q?.addEventListener("abort",()=>{B(null)}),H.stdout.on("data",(K)=>{X+=K.toString()}),H.stderr.on("data",()=>{}),H.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=X.split(`
124
- `).filter((P)=>P.trim());for(let P of R){if(G.length>=J)break;let U=JSON.parse(P);if(U.type==="match"){let F=U.data,z=[];if(U.data.submatches&&U.data.submatches.length>0){let _=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(_?.start??0)+1,match:_?.match?.text??"",context:z})}}else if(U.type==="context"&&G.length>0){let F=G[G.length-1],z=U.data.line_number===F.line?">":" ";F.context.push(`${z} ${U.data.line_number}: ${U.data.lines?.text??U.data.line?.text??""}`)}}B(G.length>0?G:null)}catch{B(null)}return}B(null)}),H.on("error",()=>{B(null)})})}function AP($,f,J,W){let Z=$.split("/"),Q=Z[Z.length-1]??"";if(Z.length-1>W)return!1;for(let X=0;X<Z.length-1;X++)if(f.has(Z[X]??""))return!1;let H=s8.posix.extname(Q).slice(1).toLowerCase();return J.has(H)||!H&&!Q.startsWith(".")}function o8($={}){let{includeExtensions:f=QP,excludeDirs:J=jP,maxResults:W=100,contextLines:Z=2,maxDepth:Q=20}=$,j=new Set(J),H=new Set(f.map((X)=>X.toLowerCase()));return async(X,A,Y)=>{if(Y.signal?.aborted)throw Error("Search operation aborted");let V=await HP(),B=null;if(V)B=await XP(X,A,W,Z,5000,Y.signal);if(B){let F=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${X}`,""];for(let z of B)F.push(`${z.file}:${z.line}:${z.column}`),F.push(...z.context),F.push("");if(B.length>=W)F.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return F.join(`
125
- `)}let K;try{K=new RegExp(X,"gim")}catch(F){throw Error(`Invalid regex pattern: ${X}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,P=await Y1(A);for(let F of P){if(Y.signal?.aborted)throw Error("Search operation aborted");if(!AP(F,j,H,Q))continue;if(G.length>=W)break;R++;let z=s8.join(A,F);try{let D=(await E7.readFile(z,"utf-8")).split(`
126
- `);for(let O=0;O<D.length;O++){let T=D[O];K.lastIndex=0;let M=K.exec(T);while(M!==null){if(G.length>=W)break;let s=Math.max(0,O-Z),Z0=Math.min(D.length-1,O+Z),a=[];for(let Q0=s;Q0<=Z0;Q0++){let l=Q0===O?">":" ";a.push(`${l} ${Q0+1}: ${D[Q0]}`)}if(G.push({file:F,line:O+1,column:M.index+1,match:M[0],context:a}),M.index===K.lastIndex)K.lastIndex++;M=K.exec(T)}}}catch{}}if(G.length===0)return`No results found for pattern: ${X}
127
- Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${X}`,`Searched ${R} files.`,""];for(let F of G)U.push(`${F.file}:${F.line}:${F.column}`),U.push(...F.context),U.push("");if(G.length>=W)U.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return U.join(`
128
- `)}}function YP($){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,`
129
- `).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,`
111
+ ${V}`:""):Y;if(B>Q)D+=`
112
+
113
+ [Output truncated: ${B} bytes total, showing first ${Q} bytes]`;if(L!==0)R(()=>j(Error(V||`Command exited with code ${L}`)));else R(()=>W(D))}),X.on("error",(L)=>{T(),R(()=>j(Error(`Failed to execute command: ${L.message}`)))})})}function $J(f={}){let{shell:$=ZG(process.platform),timeoutMs:J=30000,maxOutputBytes:Q=1e6,env:Z={},combineOutput:W=!0}=f;return(j,H,X)=>{let A=typeof j!=="string";return jG({executable:A?j.command:$,args:A?j.args??[]:WG($,j),cwd:H,env:Z},X,J,Q,W)}}import*as r0 from"node:fs/promises";import*as p0 from"node:path";function HG(f,$,J){let Q=p0.isAbsolute($),Z=Q?p0.normalize($):p0.resolve(f,$);if(!J)return Z;if(Q)return Z;let W=p0.relative(f,Z);if(W.startsWith("..")||p0.isAbsolute(W))throw Error(`Path must stay within cwd: ${$}`);return Z}function XG(f,$){if($.length===0)return 0;return f.split($).length-1}function AG(f,$,J){let Q=f.split(`
114
+ `),Z=$.split(`
115
+ `),W=Math.max(Q.length,Z.length),j=["```diff"],H=0;for(let X=0;X<W;X++){if(H>=J){j.push("... diff truncated ...");break}let A=Q[X],Y=Z[X];if(A===Y)continue;let V=X+1;if(A!==void 0)j.push(`-${V}: ${A}`),H++;if(Y!==void 0&&H<J)j.push(`+${V}: ${Y}`),H++}return j.push("```"),j.join(`
116
+ `)}async function YG(f,$,J){return await r0.mkdir(p0.dirname(f),{recursive:!0}),await r0.writeFile(f,$,{encoding:J}),`File created successfully at: ${f}`}async function VG(f){try{return await r0.access(f),!0}catch{return!1}}async function BG(f,$,J,Q,Z){let W=await r0.readFile(f,Q),j=XG(W,$);if(j===0)throw Error(`No replacement performed: text not found in ${f}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${f}.`);let H=W.replace($,J??"");await r0.writeFile(f,H,{encoding:Q});let X=AG(W,H,Z);return`Edited ${f}
117
+ ${X}`}async function KG(f,$,J,Q){let W=(await r0.readFile(f,Q)).split(`
118
+ `),j=W.length+1;if($<1||$>j)throw Error(`Invalid insert_line: ${$}. insert_line must be a positive one-based boundary line in the range 1-${j}. Use ${j} to append at EOF.`);let H=$-1;return W.splice(H,0,...J.split(`
119
+ `)),await r0.writeFile(f,W.join(`
120
+ `),{encoding:Q}),`Inserted content at line ${$} in ${f}.`}function JJ(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0,maxDiffLines:Q=200}=f;return async(Z,W,j)=>{let H=HG(W,Z.path,J);if(Z.insert_line!=null)return KG(H,Z.insert_line,Z.new_text,$);if(!await VG(H))return YG(H,Z.new_text,$);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return BG(H,Z.old_text,Z.new_text,$,Q)}}import*as n1 from"node:fs/promises";import*as bf from"node:path";import{resolveExistingFilePath as PG}from"@cline/shared/storage";var GG=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),FG={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function QJ(f={}){let{maxFileSizeBytes:$,encoding:J,includeLineNumbers:Q}={...FG,...f};return async(Z,W)=>{let{path:j,start_line:H,end_line:X}=Z,A=bf.isAbsolute(j)?bf.normalize(j):bf.resolve(process.cwd(),j),Y=PG(A)??A,V=bf.extname(Y).toLowerCase(),B=GG.get(V),K=await n1.stat(Y);if(!K.isFile())throw Error(`Path is not a file: ${Y}`);if(K.size>$)throw Error(`File too large: ${K.size} bytes (max: ${$} 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 _=await n1.readFile(Y);return[{type:"text",text:"Successfully read image"},{type:"image",data:_.toString("base64"),mediaType:B}]}let R=(await n1.readFile(Y,J)).split(`
121
+ `),G=Math.max((H??1)-1,0),F=Math.min(X??R.length,R.length),U=R.slice(G,F);if(Q){let _=String(R.length).length;return U.map((T,L)=>`${String(G+L+1).padStart(_," ")} | ${T}`).join(`
122
+ `)}return U.join(`
123
+ `)}}import{spawn as e7}from"node:child_process";import*as f3 from"node:fs/promises";import*as jJ from"node:path";import{spawn as UG}from"node:child_process";import{readdir as RG}from"node:fs/promises";import N5 from"node:path";import{isMainThread as a7,parentPort as i7,Worker as DG}from"node:worker_threads";var LG=15000,OG=600000,_G=1000,TG=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function n7(f){let $=f&&typeof f==="object"&&"code"in f?String(f.code??""):"";return $==="EACCES"||$==="EPERM"||$==="ENOENT"}var H1=new Map;function zG(){if(!a7)return!1;return!0}function MG(f){if(H1.size<=1)return;for(let[$,J]of H1.entries()){if(J.pending)continue;if(f-J.lastAccessedAt>OG)H1.delete($)}}function NG(f,$){return N5.relative(f,$).split(N5.sep).join("/")}async function qG(f){let J=(await new Promise((Q,Z)=>{let W=UG("rg",["--files","--hidden","-g","!.git"],{cwd:f,stdio:["ignore","pipe","pipe"]}),j="",H="";W.stdout.on("data",(X)=>{j+=X.toString()}),W.stderr.on("data",(X)=>{H+=X.toString()}),W.on("error",Z),W.on("close",(X)=>{if(X===0){Q(j);return}Z(Error(H||`rg exited with code ${X}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(J)}async function t7(f,$,J){let Q;try{Q=await RG($,{withFileTypes:!0})}catch(Z){if(n7(Z))return;throw Z}for(let Z of Q){let W=N5.join($,Z.name);if(Z.isDirectory()){if(TG.has(Z.name))continue;try{await t7(f,W,J)}catch(j){if(n7(j))continue;throw j}continue}if(Z.isFile())J.add(NG(f,W))}}async function yG(f){let $=new Set;return await t7(f,f,$),$}async function ZJ(f){try{return await qG(f)}catch{return yG(f)}}function wG(){if(a7||!i7)return;let f=i7;f.on("message",($)=>{if($.type!=="index")return;ZJ($.cwd).then((J)=>{let Q={type:"indexResult",requestId:$.requestId,files:Array.from(J)};f.postMessage(Q)}).catch((J)=>{let Q={type:"indexResult",requestId:$.requestId,error:J instanceof Error?J.message:"Failed to build file index"};f.postMessage(Q)})})}class s7{worker=new DG(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(f)=>{if(f.type!=="indexResult")return;let $=this.pending.get(f.requestId);if(!$)return;if(this.pending.delete(f.requestId),f.error){$.reject(Error(f.error));return}$.resolve(f.files??[])}),this.worker.on("error",(f)=>{this.flushPending(f)}),this.worker.on("exit",(f)=>{if(f!==0)this.flushPending(Error(`File index worker exited with code ${f}`))})}requestIndex(f){let $=++this.nextRequestId,J=new Promise((Z,W)=>{let j=setTimeout(()=>{this.pending.delete($),Z(null)},_G);j.unref(),this.pending.set($,{resolve:(H)=>{clearTimeout(j),Z(H)},reject:(H)=>{clearTimeout(j),W(H)}})}),Q={type:"index",requestId:$,cwd:f};return this.worker.postMessage(Q),J}flushPending(f){for(let[$,J]of this.pending.entries())J.reject(f),this.pending.delete($)}}wG();var M5;function CG(){if(!zG())return null;if(M5===void 0)M5=new s7;return M5}async function SG(f){let $=CG();if(!$)return ZJ(f);try{let J=await $.requestIndex(f);if(J===null)return ZJ(f);return new Set(J)}catch{return ZJ(f)}}async function P$(f,$={}){let J=$.ttlMs??LG,Q=Date.now();MG(Q);let Z=H1.get(f);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=SG(f).then((j)=>{return H1.set(f,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return H1.set(f,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:Q,pending:W}),W}async function o7(f,$={}){await P$(f,{...$,ttlMs:0})}import{stat as EG}from"node:fs/promises";import G$ from"node:path";var hG=/[),.:;!?`'"]+$/,bG=/^[(`'"]+/;function kG(f){let $=f.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let Q of $){let Z=(Q[2]??"").trim();if(Z.length===0)continue;let W=Z.replace(bG,"").replace(hG,"");if(W.length===0||W.includes("@"))continue;J.push(W)}return Array.from(new Set(J))}function IG(f,$){let J=f.replace(/\\/g,"/"),Q=G$.isAbsolute(J)?G$.resolve(J):G$.resolve($,J),Z=G$.relative($,Q);if(Z.startsWith("..")||G$.isAbsolute(Z))return;return Z.split(G$.sep).join("/")}async function WJ(f,$,J={}){let Q=kG(f);if(Q.length===0)return{prompt:f,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:W,maxTotalBytes:j}=J,H=await P$($,{ttlMs:J.ttlMs}),X=[],A=[],Y=[],V=0;for(let B of Q){if(Z&&Y.length>=Z){A.push(B);continue}let K=IG(B,$);if(!K||!H.has(K)){A.push(B);continue}if(!W||!j){X.push(K);continue}let P=G$.join($,K);try{if(!(await EG(P)).isFile()){A.push(B);continue}let G=V+W;if(G>j){A.push(B);continue}V=G,X.push(K)}catch{A.push(B)}}return{prompt:f,mentions:Q,matchedFiles:X,ignoredMentions:A}}var xG=["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"],gG=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],F$=null;function mG(){if(F$!==null)return Promise.resolve(F$);return new Promise((f)=>{let $=e7("rg",["--version"],{stdio:["ignore","pipe","pipe"]});$.on("close",(J)=>{F$=J===0,f(F$)}),$.on("error",()=>{F$=!1,f(!1)}),setTimeout(()=>{if(!$.killed)$.kill("SIGTERM");if(F$===null)F$=!1,f(!1)},1000)})}function vG(f,$,J,Q,Z=5000,W){return new Promise((j)=>{let H=e7("rg",["--json",`--context=${Q}`,"--max-count=1","-i",f],{cwd:$,stdio:["ignore","pipe","pipe"]}),X="",A=!1,Y=()=>{if(!H.killed)H.kill("SIGTERM")},V=setTimeout(()=>{if(!A)A=!0,Y(),j(null)},Z),B=(K)=>{if(!A)A=!0,clearTimeout(V),Y(),j(K)};if(W?.aborted){Y(),j(null);return}W?.addEventListener("abort",()=>{B(null)}),H.stdout.on("data",(K)=>{X+=K.toString()}),H.stderr.on("data",()=>{}),H.on("close",(K)=>{if(K===0||K===1){try{let P=[],R=X.split(`
124
+ `).filter((G)=>G.trim());for(let G of R){if(P.length>=J)break;let F=JSON.parse(G);if(F.type==="match"){let U=F.data,_=[];if(F.data.submatches&&F.data.submatches.length>0){let T=F.data.submatches[0];P.push({file:U.path.text,line:U.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:_})}}else if(F.type==="context"&&P.length>0){let U=P[P.length-1],_=F.data.line_number===U.line?">":" ";U.context.push(`${_} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}B(P.length>0?P:null)}catch{B(null)}return}B(null)}),H.on("error",()=>{B(null)})})}function cG(f,$,J,Q){let Z=f.split("/"),W=Z[Z.length-1]??"";if(Z.length-1>Q)return!1;for(let X=0;X<Z.length-1;X++)if($.has(Z[X]??""))return!1;let H=jJ.posix.extname(W).slice(1).toLowerCase();return J.has(H)||!H&&!W.startsWith(".")}function HJ(f={}){let{includeExtensions:$=xG,excludeDirs:J=gG,maxResults:Q=100,contextLines:Z=2,maxDepth:W=20}=f,j=new Set(J),H=new Set($.map((X)=>X.toLowerCase()));return async(X,A,Y)=>{if(Y.signal?.aborted)throw Error("Search operation aborted");let V=await mG(),B=null;if(V)B=await vG(X,A,Q,Z,5000,Y.signal);if(B){let U=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${X}`,""];for(let _ of B)U.push(`${_.file}:${_.line}:${_.column}`),U.push(..._.context),U.push("");if(B.length>=Q)U.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return U.join(`
125
+ `)}let K;try{K=new RegExp(X,"gim")}catch(U){throw Error(`Invalid regex pattern: ${X}. ${U instanceof Error?U.message:""}`)}let P=[],R=0,G=await P$(A);for(let U of G){if(Y.signal?.aborted)throw Error("Search operation aborted");if(!cG(U,j,H,W))continue;if(P.length>=Q)break;R++;let _=jJ.join(A,U);try{let L=(await f3.readFile(_,"utf-8")).split(`
126
+ `);for(let D=0;D<L.length;D++){let M=L[D];K.lastIndex=0;let S=K.exec(M);while(S!==null){if(P.length>=Q)break;let h=Math.max(0,D-Z),a=Math.min(L.length-1,D+Z),W0=[];for(let t=h;t<=a;t++){let i=t===D?">":" ";W0.push(`${i} ${t+1}: ${L[t]}`)}if(P.push({file:U,line:D+1,column:S.index+1,match:S[0],context:W0}),S.index===K.lastIndex)K.lastIndex++;S=K.exec(M)}}}catch{}}if(P.length===0)return`No results found for pattern: ${X}
127
+ Searched ${R} files.`;let F=[`Found ${P.length} result${P.length===1?"":"s"} for pattern: ${X}`,`Searched ${R} files.`,""];for(let U of P)F.push(`${U.file}:${U.line}:${U.column}`),F.push(...U.context),F.push("");if(P.length>=Q)F.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return F.join(`
128
+ `)}}function uG(f){return f.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,`
129
+ `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,($,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
130
130
  `).replace(/\n{3,}/g,`
131
131
 
132
- `).trim()}function e8($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:Q=!0}=$;return async(j,H,X)=>{let A;try{A=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(A.protocol))throw Error(`Invalid protocol: ${A.protocol}. Only http and https are supported.`);let Y=new AbortController,V=setTimeout(()=>Y.abort(),f),B;if(X.signal)B=()=>Y.abort(),X.signal.addEventListener("abort",B);try{let K=await fetch(j,{method:"GET",headers:{"User-Agent":W,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:Q?"follow":"manual",signal:Y.signal});if(clearTimeout(V),!Q&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let P=[],U=0;while(!0){let{done:T,value:M}=await R.read();if(T)break;if(U+=M.length,U>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);P.push(M)}let F=new Uint8Array(U),z=0;for(let T of P)F.set(T,z),z+=T.length;let _=new TextDecoder("utf-8").decode(F),D;if(G.includes("text/html")||G.includes("application/xhtml"))D=YP(_);else if(G.includes("application/json"))try{let T=JSON.parse(_);D=JSON.stringify(T,null,2)}catch{D=_}else D=_;let O=[`URL: ${j}`,`Content-Type: ${G}`,`Size: ${U} bytes`,"","--- Content ---",D.slice(0,50000)];if(D.length>50000)O.push(`
133
- [Content truncated: showing first 50000 of ${D.length} characters]`);return O.push("","--- Analysis Request ---",`Prompt: ${H}`),O.join(`
134
- `)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(X.signal&&B)X.signal.removeEventListener("abort",B)}}}function $J($={}){return{readFile:n8($.fileRead),search:o8($.search),bash:r8($.bash),webFetch:e8($.webFetch),applyPatch:p8($.applyPatch),editor:i8($.editor)}}var VP={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"},vf=[{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 b7($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((W)=>J.includes(W.toLowerCase()))}function BP($,f,J,W){if($.mode&&$.mode!=="any"&&$.mode!==W)return!1;return b7(f,$.providerIdIncludes)&&b7(J,$.modelIdIncludes)}function uf($,f,J,W){if(!W||W.length===0)return{};let Z=new Map;for(let j of W){if(!BP(j,$,f,J))continue;for(let H of j.disableTools??[])Z.set(H,!1);for(let H of j.enableTools??[])Z.set(H,!0)}let Q={};for(let[j,H]of Z.entries())Q[VP[j]]=H;return Q}var s0={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 S$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function k7($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let W of o1)J[W]=f;return J}function I7($,f){let J=s0[$],{enableSpawnAgent:W,enableAgentTeams:Z,...Q}=J;return $f({...Q,...f})}import{createTool as KU,zodToJsonSchema as GU}from"@cline/shared";import{z as _5}from"zod";import{createAgentRuntime as ZU}from"@cline/agents";import{createContributionRegistry as QU}from"@cline/shared";import{createGateway as zP,createHandlerAsync as _P,hasRegisteredHandler as TP,MODEL_COLLECTIONS_BY_PROVIDER_ID as NP,normalizeProviderId as MP}from"@cline/llms";import{EMPTY_CONTENT_TEXT as KP}from"@cline/shared";function GP($){let f=UP($.content),J=[],W=$.id??DP(),Z=0,Q=[],j=()=>{if(Q.length===0)return;let H=Z===0?W:`${W}_part_${Z}`;Z+=1,J.push({id:H,role:$.role,content:Q.map(FP),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:x7($.metrics)}),Q=[]};if(f.length===0)return J.push({id:W,role:$.role,content:[{type:"text",text:KP}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:x7($.metrics)}),J;for(let H of f){if(H.type!=="tool_result"){Q.push(H);continue}j(),J.push({id:`${W}_tool_${H.tool_use_id}`,role:"tool",content:[g7(H)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function fJ($){return $.flatMap(GP)}function PP($){let f=$.content.map(v7).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:RP($.metrics)}}function Jf($){return $.map(PP)}function JJ($){let f=[];for(let J of $){let W=J.content.map(v7).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,Q=f[f.length-1];if(Z==="user"&&W.length>0&&W.every((j)=>j.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((j)=>j.type==="tool_result")){Q.content.push(...W);continue}f.push({role:Z,content:W})}return f}function UP($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function FP($){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 g7($)}}function g7($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function v7($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let f=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:f?.thoughtSignature??f?.signature}}case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function x7($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function RP($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var m7=0;function DP(){return m7+=1,`msg_${Date.now().toString(36)}_${m7.toString(36)}`}function LP($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let f=$.tool_call.function,J=f.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??f.id,toolName:f.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:OP($),error:$.error}];default:return[]}}function OP($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function u7($){return{async*stream(f){let J=!1,W=!1;try{let Z=typeof $==="function"?await $():$;Z.setAbortSignal?.(f.signal);let Q=JJ(f.messages),j=f.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema}));for await(let H of Z.createMessage(f.systemPrompt??"",Q,j))for(let X of LP(H)){if(X.type==="finish")J=!0;else if(X.type==="tool-call-delta")W=!0;yield X}if(!J)yield{type:"finish",reason:W?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:f.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function yP($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function qP($){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 yP(f)}function G5($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return NP[$.providerId]?.models??void 0}function wP($){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 SP($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:wP(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function c7($,f,J){let W=$.providerConfig,Z=W?.providerId===$.providerId?W:void 0,Q={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:G5($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};if(TP(MP(Q.providerId)))return u7(()=>_P(Q));return zP({providerConfigs:[{providerId:Q.providerId,apiKey:Q.apiKey,baseUrl:Q.baseUrl,headers:Q.headers,options:qP(Q),models:Q.knownModels?Object.entries(Q.knownModels).map(([j,H])=>SP(j,H)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:Q.providerId,modelId:Q.modelId},{maxTokens:Q.maxOutputTokens})}import{normalizeUserInput as d7}from"@cline/shared";var hP=50000,CP=6000000,l7=8000,EP=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),bP=new Set(["read","read_files"]),K1="[outdated - see the latest file content]",p7="Tool execution was interrupted before a result was produced.",kP=($)=>`
132
+ `).trim()}function XJ(f={}){let{timeoutMs:$=30000,maxResponseBytes:J=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:W=!0}=f;return async(j,H,X)=>{let A;try{A=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(A.protocol))throw Error(`Invalid protocol: ${A.protocol}. Only http and https are supported.`);let Y=new AbortController,V=setTimeout(()=>Y.abort(),$),B;if(X.signal)B=()=>Y.abort(),X.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:Y.signal});if(clearTimeout(V),!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 P=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let G=[],F=0;while(!0){let{done:M,value:S}=await R.read();if(M)break;if(F+=S.length,F>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);G.push(S)}let U=new Uint8Array(F),_=0;for(let M of G)U.set(M,_),_+=M.length;let T=new TextDecoder("utf-8").decode(U),L;if(P.includes("text/html")||P.includes("application/xhtml"))L=uG(T);else if(P.includes("application/json"))try{let M=JSON.parse(T);L=JSON.stringify(M,null,2)}catch{L=T}else L=T;let D=[`URL: ${j}`,`Content-Type: ${P}`,`Size: ${F} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)D.push(`
133
+ [Content truncated: showing first 50000 of ${L.length} characters]`);return D.push("","--- Analysis Request ---",`Prompt: ${H}`),D.join(`
134
+ `)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${$}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(X.signal&&B)X.signal.removeEventListener("abort",B)}}}function AJ(f={}){return{readFile:QJ(f.fileRead),search:HJ(f.search),bash:$J(f.bash),webFetch:XJ(f.webFetch),applyPatch:fJ(f.applyPatch),editor:JJ(f.editor)}}var dG={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"},a1=[{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 $3(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((Q)=>J.includes(Q.toLowerCase()))}function lG(f,$,J,Q){if(f.mode&&f.mode!=="any"&&f.mode!==Q)return!1;return $3($,f.providerIdIncludes)&&$3(J,f.modelIdIncludes)}function t1(f,$,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!lG(j,f,$,J))continue;for(let H of j.disableTools??[])Z.set(H,!1);for(let H of j.enableTools??[])Z.set(H,!0)}let W={};for(let[j,H]of Z.entries())W[dG[j]]=H;return W}var e0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function kf(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function J3(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let Q of Z1)J[Q]=$;return J}function Q3(f,$){let J=e0[f],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return j1({...W,...$})}import{createTool as rF,zodToJsonSchema as iF}from"@cline/shared";import{z as I5}from"zod";import{createAgentRuntime as xF}from"@cline/agents";import{createContributionRegistry as gF}from"@cline/shared";import{createGateway as fF,createHandlerAsync as $F,hasRegisteredHandler as JF,MODEL_COLLECTIONS_BY_PROVIDER_ID as QF,normalizeProviderId as ZF}from"@cline/llms";import{EMPTY_CONTENT_TEXT as pG}from"@cline/shared";function rG(f){let $=nG(f.content),J=[],Q=f.id??sG(),Z=0,W=[],j=()=>{if(W.length===0)return;let H=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:H,role:f.role,content:W.map(aG),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:Z3(f.metrics)}),W=[]};if($.length===0)return J.push({id:Q,role:f.role,content:[{type:"text",text:pG}],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:Z3(f.metrics)}),J;for(let H of $){if(H.type!=="tool_result"){W.push(H);continue}j(),J.push({id:`${Q}_tool_${H.tool_use_id}`,role:"tool",content:[j3(H)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return j(),J}function YJ(f){return f.flatMap(rG)}function iG(f){let $=f.content.map(H3).filter((J)=>J!==void 0);return{id:f.id,role:f.role==="tool"?"user":f.role,content:$,ts:f.createdAt,metadata:f.metadata,modelInfo:f.modelInfo,metrics:tG(f.metrics)}}function X1(f){return f.map(iG)}function VJ(f){let $=[];for(let J of f){let Q=J.content.map(H3).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=$[$.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}$.push({role:Z,content:Q})}return $}function nG(f){if(typeof f==="string")return f.trim().length>0?[{type:"text",text:f}]:[];return[...f]}function aG(f){switch(f.type){case"text":return{type:"text",text:f.text};case"thinking":return{type:"reasoning",text:f.thinking,metadata:f.signature?{signature:f.signature,details:f.details}:f.details?{details:f.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:f.data}};case"image":return{type:"image",image:f.data,mediaType:f.mediaType};case"file":return{type:"file",path:f.path,content:f.content};case"tool_use":return{type:"tool-call",toolCallId:f.id,toolName:f.name,input:f.input,metadata:f.signature?{signature:f.signature}:void 0};case"tool_result":return j3(f)}}function j3(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:f.name,output:f.content,isError:f.is_error}}function H3(f){switch(f.type){case"text":return{type:"text",text:f.text};case"reasoning":{if(f.redacted===!0)return{type:"redacted_thinking",data:f.metadata?.data??""};let $=f.metadata;return{type:"thinking",thinking:f.text,signature:$?.signature,details:$?.details}}case"image":return typeof f.image==="string"?{type:"image",data:f.image,mediaType:f.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:f.path,content:f.content};case"tool-call":{let $=f.metadata;return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:$?.thoughtSignature??$?.signature}}case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,name:f.toolName,content:J,is_error:f.isError}}}}function Z3(f){if(!f)return;return{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,cacheReadTokens:f.cacheReadTokens??0,cacheWriteTokens:f.cacheWriteTokens??0,cost:f.cost}}function tG(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var W3=0;function sG(){return W3+=1,`msg_${Date.now().toString(36)}_${W3.toString(36)}`}function oG(f){switch(f.type){case"text":return[{type:"text-delta",text:f.text}];case"reasoning":return[{type:"reasoning-delta",text:f.reasoning,metadata:f.signature?{thoughtSignature:f.signature,details:f.details}:{details:f.details}}];case"tool_calls":{let $=f.tool_call.function,J=$.arguments;return[{type:"tool-call-delta",toolCallId:f.tool_call.call_id??$.id,toolName:$.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...f.signature?{metadata:{thoughtSignature:f.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost}}];case"done":return[{type:"finish",reason:eG(f),error:f.error}];default:return[]}}function eG(f){if(f.success===!1)return"error";if(f.incompleteReason==="max_output_tokens"||f.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function X3(f){return{async*stream($){let J=!1,Q=!1;try{let Z=typeof f==="function"?await f():f;Z.setAbortSignal?.($.signal);let W=VJ($.messages),j=$.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema}));for await(let H of Z.createMessage($.systemPrompt??"",W,j))for(let X of oG(H)){if(X.type==="finish")J=!0;else if(X.type==="tool-call-delta")Q=!0;yield X}if(!J)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:$.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function WF(f){let $=Object.fromEntries(Object.entries(f).filter(([,J])=>J!==void 0));return Object.keys($).length>0?$:void 0}function jF(f){return f.providerId==="openai-compatible"||f.clientType==="openai-compatible"}function HF(f){let $={region:f.region,apiLine:f.apiLine,openRouterProviderSorting:f.openRouterProviderSorting,modelCatalog:f.modelCatalog};if(jF(f))Object.assign($,{apiVersion:f.azure?.apiVersion,useIdentity:f.azure?.useIdentity});if(f.providerId==="bedrock")Object.assign($,{authentication:f.aws?.authentication,profile:f.aws?.profile,accessKeyId:f.aws?.accessKey,secretAccessKey:f.aws?.secretKey,sessionToken:f.aws?.sessionToken,usePromptCache:f.aws?.usePromptCache,useCrossRegionInference:f.useCrossRegionInference,useGlobalInference:f.useGlobalInference,endpoint:f.aws?.endpoint,customModelBaseId:f.aws?.customModelBaseId});if(f.providerId==="vertex"){let J=f.gcp?.region??f.region;Object.assign($,{project:f.gcp?.projectId,projectId:f.gcp?.projectId,location:J,region:J})}return WF($)}function q5(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return QF[f.providerId]?.models??void 0}function XF(f){if(!f?.length)return;let $=new Set;for(let J of f)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":$.add(J);break;case"structured_output":$.add("structured-output");break;default:$.add("text")}return $.add("text"),[...$]}function AF(f,$){return{id:f,name:$.name??f,description:$.description,contextWindow:$.contextWindow,maxInputTokens:$.maxInputTokens,maxOutputTokens:$.maxTokens,capabilities:XF($.capabilities),metadata:{family:$.family,pricing:$.pricing,status:$.status,releaseDate:$.releaseDate}}}function A3(f,$,J){let Q=f.providerConfig,Z=Q?.providerId===f.providerId?Q:void 0,W={...Z??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??Z?.apiKey,baseUrl:f.baseUrl??Z?.baseUrl,headers:f.headers??Z?.headers,knownModels:q5(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};if(JF(ZF(W.providerId)))return X3(()=>$F(W));return fF({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,options:HF(W),models:W.knownModels?Object.entries(W.knownModels).map(([j,H])=>AF(j,H)):void 0}],logger:$,telemetry:J??f.telemetry??f.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as Y3}from"@cline/shared";var YF=50000,VF=6000000,V3=8000,BF=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),KF=new Set(["read","read_files"]),U$="[outdated - see the latest file content]",B3="Tool execution was interrupted before a result was produced.",PF=(f)=>`
135
135
 
136
- ...[truncated ${$} chars]...
136
+ ...[truncated ${f} chars]...
137
137
 
138
- `,IP=($)=>`
138
+ `,GF=(f)=>`
139
139
 
140
- ...[truncated ${$} chars to fit provider request budget]...
140
+ ...[truncated ${f} chars to fit provider request budget]...
141
141
 
142
- `;class U5{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=hP,f=EP,J=CP){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let j=d7(W.content);if(j!==W.content)return{...W,content:j}}return W}let Z=!1,Q=W.content.map((j)=>{let H=this.transformBlock(j,W.role);if(H!==j)Z=!0;return H});return Z?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=d7($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),W=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let Q=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===$.content?$:{...$,content:W}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let W=$[J];if(!Array.isArray(W.content))continue;for(let Z=0;Z<W.content.length;Z++){let Q=W.content[Z];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${Z}`);else if(Q.type==="tool_use"){let j=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,j),this.isReadTool(j)){let H=this.extractLocatorsFromReadToolInput(Q.input);if(H.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,H)}}else if(Q.type==="tool_result"){let j=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(j)||Q.is_error===!0)continue;let H=this.getReadLocators(Q);for(let X of H)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),Q.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,Q.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],W=new Map,Z=!1,Q=()=>{if(W.size===0)return;j(this.createMissingToolResultMessage(W)),W.clear(),Z=!0},j=(H)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,H)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(H.content)]},Z=!0;return}J.push(H)};for(let H of $){if(this.isToolResultOnlyMessage(H)){if(j(this.appendMissingToolResults(H,W)),W.size>0)W.clear(),Z=!0;continue}if(Array.isArray(H.content)){let X=H.content.filter((Y)=>Y.type==="tool_result"),A=H.content.filter((Y)=>Y.type!=="tool_result");if(X.length>0){let Y=this.appendMissingToolResults({...H,role:"user",content:X},W);if(j(Y),W.size>0)W.clear();Z=!0}if(A.length>0||X.length===0){if(X.length===0)Q();let Y=X.length>0?{...H,content:A}:H;if(j(Y),Y.role==="assistant")this.trackMissingToolCalls(Y,f,W)}continue}Q(),j(H)}return Q(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")f.add(W.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let W of $.content){if(W.type!=="tool_use"||f.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${p7} Tool: ${$}.`:p7}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],W=this.extractLocatorFromReadRequest(f);if(W)J.push(W);if(Array.isArray(f.files))for(let Z of f.files){let Q=this.extractLocatorFromReadRequest(Z);if(Q)J.push(Q)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let W of $){let Z=this.extractLocatorFromResultEntry(W);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((Q)=>this.toReadLocatorKey(Q))),W=new Set(f.map((Q)=>Q.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??K1;let Z=0;for(let Q of $)if(Q.type==="text")Z+=this.countOutdatedImageEntries(Q.text,J);return $.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:K1}}if(Q.type==="image"){if(Z===0)return Q;return Z-=1,{type:"text",text:K1}}if(Q.type!=="text")return Q;let j=this.replaceOutdatedInString(Q.text,J);if(j===null)return{...Q,text:K1};return j===Q.text?Q:{...Q,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let W=Array.isArray(J)?J:[J],Z=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let j=Q,H=this.extractLocatorFromResultEntry(j);if(!H)continue;if(!f.has(this.toReadLocatorKey(H)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let W=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(W)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let W={...$};if(typeof W.result==="string")W.result=K1;else if(typeof W.content==="string")W.content=K1;else W.result=K1;return W}isReadTool($){return!!$&&bP.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let W=this.truncateMiddle(f.content);return W===f.content?f:{...f,content:W}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return P5($,this.maxToolResultChars,kP)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((Q)=>mP(Q))}}),W=this.collectTruncationCandidates(J);for(let Z of W){if(f<=this.maxTotalTextBytes)break;let Q=Z.byteLength;if(Q<=l7)continue;let j=f-this.maxTotalTextBytes,H=Math.max(l7,Q-j),X=xP(Z.get(),H,IP);Z.set(X),f-=Q-z0(X)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=z0(J.content);continue}for(let W of J.content)if(W.type==="text")f+=z0(W.text);else if(W.type==="thinking")f+=z0(W.thinking);else if(W.type==="file")f+=z0(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")f+=z0(W.content);else for(let Z of W.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 W of J.content){if(W.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof W.content==="string"){f.push({byteLength:z0(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")f.push({byteLength:z0(Q.text),get:()=>Q.text,set:(j)=>{Q.text=j}});else if(Q.type==="file")f.push({byteLength:z0(Q.content),get:()=>Q.content,set:(j)=>{Q.content=j}})}}return f.sort((J,W)=>W.byteLength-J.byteLength)}}function z0($){return Buffer.byteLength($,"utf8")}function P5($,f,J){if($.length<=f)return $;let W=J($.length-f),Z=Math.max(0,Math.floor((f-W.length)/2)),Q=Math.max(0,$.length-Z*2),j=J(Q),H=Math.max(0,Math.floor((f-j.length)/2)),X=$.slice(0,H),A=H>0?$.slice(-H):"";return`${X}${j}${A}`}function xP($,f,J){if(z0($)<=f)return $;let W=0,Z=$.length,Q=P5($,0,J);while(W<=Z){let j=W+Z>>>1,H=P5($,j,J);if(z0(H)<=f)Q=H,W=j+1;else Z=j-1}return Q}function mP($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function F5(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class R5{messages=[];conversationId=F5();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=F5(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=F5(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function r7($){let{agentConfig:f}=$,J=gP(f),W=vP(f),Z=$.hooks,Q=uP(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:W,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:Q,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function gP($){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 vP($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function uP($){if($===void 0)return;return $>=2?"parallel":"sequential"}function cP(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function dP($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function D5($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(D5);let f={};for(let J of Object.keys($).sort())f[J]=D5($[J]);return f}function lP($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(D5($))}catch{return String($)}}function pP($,f,J,W){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===W.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=W.hardThreshold}}var i7={softThreshold:3,hardThreshold:5};class L5{config;state=cP();constructor($){this.config={softThreshold:$?.softThreshold??i7.softThreshold,hardThreshold:$?.hardThreshold??i7.hardThreshold}}inspect($){let f=lP($.input),J=pP(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(){dP(this.state)}}class O5{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let W=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(W),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await iP({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let Q=Z.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:rP({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function rP($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let W=$.stopReason?.trim();if(W)f.push(`Decision: ${W}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function iP($,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 nP($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function aP($){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 tP($){return $.content.find((f)=>f.type==="tool-result")}function sP($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function oP($){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 z5{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=nP($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let W=aP($);if(W!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let W=tP($.message),Z=W?.output,Q=oP(W);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:Q,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,W=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,H=($.totalCost??0)-Q;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:H===0?void 0:H,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:sP($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function jU($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function HU($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function XU($,f){let J=$.trim(),W=f.map((Z)=>Z.trim()).filter(Boolean).join(`
142
+ `;class w5{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=YF,$=BF,J=VF){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((Q)=>{if(!Array.isArray(Q.content)){if(Q.role==="user"&&typeof Q.content==="string"){let j=Y3(Q.content);if(j!==Q.content)return{...Q,content:j}}return Q}let Z=!1,W=Q.content.map((j)=>{let H=this.transformBlock(j,Q.role);if(H!==j)Z=!0;return H});return Z?{...Q,content:W}:Q});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let Z=Y3(f.text);if(Z!==f.text)return{...f,text:Z};return f}if(f.type==="file"){let Z=this.truncateMiddle(f.content);return Z===f.content?f:{...f,content:Z}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),Q=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let Z=this.getReadLocators(f);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,f.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===f.content?f:{...f,content:Q}}reindex(f){let $=this.indexedMessageCount===0||f.length>=this.indexedMessageCount&&f[this.indexedMessageCount-1]===this.indexedTailRef;if(f.length<this.indexedMessageCount||!$)this.resetIndexes();for(let J=this.indexedMessageCount;J<f.length;J++){let Q=f[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 H=this.extractLocatorsFromReadToolInput(W.input);if(H.length>0)this.readLocatorsByToolUseIdCache.set(W.id,H)}}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 H=this.getReadLocators(W);for(let X of H)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),W.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,W.tool_use_id)}}}this.indexedMessageCount=f.length,this.indexedTailRef=f.length>0?f[f.length-1]:void 0}addMissingToolResults(f){let $=this.collectToolResultIds(f),J=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(H)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,H)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(H.content)]},Z=!0;return}J.push(H)};for(let H of f){if(this.isToolResultOnlyMessage(H)){if(j(this.appendMissingToolResults(H,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(H.content)){let X=H.content.filter((Y)=>Y.type==="tool_result"),A=H.content.filter((Y)=>Y.type!=="tool_result");if(X.length>0){let Y=this.appendMissingToolResults({...H,role:"user",content:X},Q);if(j(Y),Q.size>0)Q.clear();Z=!0}if(A.length>0||X.length===0){if(X.length===0)W();let Y=X.length>0?{...H,content:A}:H;if(j(Y),Y.role==="assistant")this.trackMissingToolCalls(Y,$,Q)}continue}W(),j(H)}return W(),Z?J:f}appendMissingToolResults(f,$){if($.size===0||!Array.isArray(f.content))return f;return{...f,role:"user",content:[...f.content,...this.createMissingToolResultBlocks($)]}}shouldMergeUserAfterToolResults(f,$){return f?.role==="user"&&$.role==="user"&&this.isToolResultOnlyMessage(f)&&this.contentBlocksForUserMerge($.content).length>0}contentBlocksForUserMerge(f){return typeof f==="string"?f.length>0?[{type:"text",text:f}]:[]:f}collectToolResultIds(f){let $=new Set;for(let J of f){if(!Array.isArray(J.content))continue;for(let Q of J.content)if(Q.type==="tool_result")$.add(Q.tool_use_id)}return $}isToolResultOnlyMessage(f){return f.role==="user"&&Array.isArray(f.content)&&f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}trackMissingToolCalls(f,$,J){if(!Array.isArray(f.content))return;for(let Q of f.content){if(Q.type!=="tool_use"||$.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${B3} Tool: ${f}.`:B3}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(f){let $=f,J=this.readResultLocatorCache.get($);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent(f.content),this.readResultLocatorCache.set($,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get(f.tool_use_id)??[]}extractLocatorsFromReadToolInput(f){if(!f||typeof f!=="object")return[];let $=f,J=[],Q=this.extractLocatorFromReadRequest($);if(Q)J.push(Q);if(Array.isArray($.files))for(let Z of $.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray($.file_paths)){for(let Z of $.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent(f){if(typeof f==="string")return this.tryParseReadLocators(f);for(let $ of f){if($.type!=="text")continue;let J=this.tryParseReadLocators($.text);if(J.length>0)return J}return[]}tryParseReadLocators(f){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(f))}catch{return[]}}extractLocatorsFromParsedReadResult(f){if(Array.isArray(f)){let J=[];for(let Q of f){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let $=this.extractLocatorFromResultEntry(f);return $?[$]:[]}extractLocatorFromReadRequest(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(!J)return;return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)}}extractLocatorFromResultEntry(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(J)return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)};if(typeof $.query==="string"&&$.query.length>0)return this.parseReadQuery($.query);return}extractPath(f){let $=[f.path,f.file_path,f.filePath];for(let J of $)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber(f){return typeof f==="number"&&Number.isInteger(f)?f:null}parseReadQuery(f){let $=/^(.*):(\d+)-(EOF|\d+)$/.exec(f);if(!$)return{path:f,startLine:null,endLine:null};return{path:$[1],startLine:Number($[2]),endLine:$[3]==="EOF"?null:Number($[3])}}dedupeReadLocators(f){let $=new Map;for(let J of f)$.set(this.toReadLocatorKey(J),J);return Array.from($.values())}toReadLocatorKey(f){if(this.isFullFileRead(f))return f.path;return`${f.path}:${f.startLine??1}-${f.endLine??"EOF"}`}isFullFileRead(f){return f.startLine==null&&f.endLine==null}isOutdatedReadLocator(f,$){let J=this.latestFullContentOwnerByPathCache.get(f.path);if(J&&J!==$)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(f))!==$}replaceOutdatedReadContent(f,$){let J=new Set($.map((W)=>this.toReadLocatorKey(W))),Q=new Set($.map((W)=>W.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??U$;let Z=0;for(let W of f)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return f.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:U$}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:U$}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:U$};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}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,H=this.extractLocatorFromResultEntry(j);if(!H)continue;if(!$.has(this.toReadLocatorKey(H)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(Q)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let Q={...f};if(typeof Q.result==="string")Q.result=U$;else if(typeof Q.content==="string")Q.content=U$;else Q.result=U$;return Q}isReadTool(f){return!!f&&KF.has(f)}shouldTruncateTool(f){return!!f&&this.targetToolNames.has(f)}truncateToolResultContent(f){if(typeof f==="string")return this.truncateMiddle(f);return f.map(($)=>{if($.type==="file"){let Q=this.truncateMiddle($.content);return Q===$.content?$:{...$,content:Q}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return y5(f,this.maxToolResultChars,PF)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>UF(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if($<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=V3)continue;let j=$-this.maxTotalTextBytes,H=Math.max(V3,W-j),X=FF(Z.get(),H,GF);Z.set(X),$-=W-M0(X)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=M0(J.content);continue}for(let Q of J.content)if(Q.type==="text")$+=M0(Q.text);else if(Q.type==="thinking")$+=M0(Q.thinking);else if(Q.type==="file")$+=M0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")$+=M0(Q.content);else for(let Z of Q.content)if(Z.type==="text")$+=M0(Z.text);else if(Z.type==="file")$+=M0(Z.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){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"){$.push({byteLength:M0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")$.push({byteLength:M0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")$.push({byteLength:M0(W.content),get:()=>W.content,set:(j)=>{W.content=j}})}}return $.sort((J,Q)=>Q.byteLength-J.byteLength)}}function M0(f){return Buffer.byteLength(f,"utf8")}function y5(f,$,J){if(f.length<=$)return f;let Q=J(f.length-$),Z=Math.max(0,Math.floor(($-Q.length)/2)),W=Math.max(0,f.length-Z*2),j=J(W),H=Math.max(0,Math.floor(($-j.length)/2)),X=f.slice(0,H),A=H>0?f.slice(-H):"";return`${X}${j}${A}`}function FF(f,$,J){if(M0(f)<=$)return f;let Q=0,Z=f.length,W=y5(f,0,J);while(Q<=Z){let j=Q+Z>>>1,H=y5(f,j,J);if(M0(H)<=$)W=H,Q=j+1;else Z=j-1}return W}function UF(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function C5(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class S5{messages=[];conversationId=C5();sessionStarted=!1;constructor(f){if((f?.length??0)>0)this.restore(f??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(f){this.messages.push(f)}appendMessages(f){if(f.length===0)return;this.messages.push(...f)}replaceMessages(f){this.messages=[...f]}resetForRun(){this.messages=[],this.conversationId=C5(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=C5(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function K3(f){let{agentConfig:$}=f,J=RF($),Q=DF($),Z=f.hooks,W=LF($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:Q,model:f.model,modelOptions:J,tools:f.tools,hooks:Z,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??$.telemetry,initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:W,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function RF(f){let $={};if(f.thinking!==void 0)$.thinking=f.thinking;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;if(f.maxTokensPerTurn!==void 0)$.maxTokensPerTurn=f.maxTokensPerTurn;if(f.apiTimeoutMs!==void 0)$.apiTimeoutMs=f.apiTimeoutMs;return Object.keys($).length>0?$:void 0}function DF(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function LF(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function OF(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function _F(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function E5(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(E5);let $={};for(let J of Object.keys(f).sort())$[J]=E5(f[J]);return $}function TF(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(E5(f))}catch{return String(f)}}function zF(f,$,J,Q){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=Q.hardThreshold}}var P3={softThreshold:3,hardThreshold:5};class h5{config;state=OF();constructor(f){this.config={softThreshold:f?.softThreshold??P3.softThreshold,hardThreshold:f?.hardThreshold??P3.hardThreshold}}inspect(f){let $=TF(f.input),J=zF(this.state,f.name,$,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){_F(this.state)}}class b5{consecutiveMistakes=0;options;constructor(f){this.options=f}async record(f){let $=this.options.maxConsecutiveMistakes,J=f.forceAtLimit&&$?$:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let Q=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:f.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:f.iteration,reason:f.reason,details:f.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!$||J<$)return{action:"continue"};let Z=await NF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:MF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function MF(f){let $=[`Stopped after ${f.consecutiveMistakes}/${f.maxConsecutiveMistakes} consecutive mistakes (${f.reason}) at iteration ${f.iteration}.`],J=f.details?.trim();if(J)$.push(`Error: ${J}`);let Q=f.stopReason?.trim();if(Q)$.push(`Decision: ${Q}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function NF(f,$){if(!$)return{action:"stop",reason:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`};try{return await $(f)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`}}}function qF(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function yF(f){let $=f.content.filter((J)=>J.type==="reasoning");if($.length===0)return;return{reasoning:$.map((J)=>J.text).join(""),redacted:$.some((J)=>J.redacted===!0)}}function wF(f){return f.content.find(($)=>$.type==="tool-result")}function CF(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function SF(f){if(!f||f.isError!==!0)return;if(typeof f.output==="string")return f.output;if(f.output instanceof Error)return f.output.message;try{return JSON.stringify(f.output)}catch{return String(f.output)}}class k5{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate(f){switch(f.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:f.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:f.iteration,hadToolCalls:f.toolCallCount>0,toolCallCount:f.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:f.text,accumulated:f.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:f.text,redacted:f.redacted===!0}];case"assistant-message":return this.translateAssistantMessage(f.message);case"tool-started":return this.translateToolStarted(f);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,update:f.update}];case"tool-finished":return this.translateToolFinished(f);case"usage-updated":return this.translateUsage(f.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:f.message,reason:f.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:f.metadata}];case"run-finished":return this.translateRunFinished(f.result);case"run-failed":return[{type:"error",error:f.error,recoverable:!1,iteration:f.snapshot.iteration}];default:return f}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage(f){let $=[],J=qF(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let Q=yF(f);if(Q!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return $}translateToolStarted(f){return this.toolStartedAt.set(f.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,input:f.toolCall.input}]}translateToolFinished(f){let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=$===void 0?void 0:Date.now()-$;this.toolStartedAt.delete(f.toolCall.toolCallId);let Q=wF(f.message),Z=Q?.output,W=SF(Q);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,Q=f.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,H=(f.totalCost??0)-W;return this.lastUsage={inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost},[{type:"usage",inputTokens:Math.max(0,$),outputTokens:Math.max(0,J),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:H===0?void 0:H,totalInputTokens:f.inputTokens,totalOutputTokens:f.outputTokens,totalCacheReadTokens:f.cacheReadTokens===0?void 0:f.cacheReadTokens,totalCacheWriteTokens:f.cacheWriteTokens===0?void 0:f.cacheWriteTokens,totalCost:f.totalCost}]}translateRunFinished(f){let $={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens===0?void 0:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens===0?void 0:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost};return[{type:"done",reason:CF(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function mF(f){if(typeof f==="string")return f;if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}}async function vF(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function cF(f,$){let J=f.trim(),Q=$.map((Z)=>Z.trim()).filter(Boolean).join(`
143
143
 
144
- `);if(J&&W)return`${J}
144
+ `);if(J&&Q)return`${J}
145
145
 
146
- ${W}`;return J||W}function AU($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let W of f){let Z=await W.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let W of f)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,Z;for(let Q of f){let j=await Q.beforeModel?.({...J,request:W});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},W={...W,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...W.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let W of f){let Z=await W.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let W=J.input,Z;for(let Q of f){let j=await Q.beforeTool?.({...J,input:W});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))W=j.input}return Z},afterTool:async(J)=>{let W=J.result,Z;for(let Q of f){let j=await Q.afterTool?.({...J,result:W});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)W=j.result}return Z},onEvent:async(J)=>{for(let W of f)await W.onEvent?.(J)}}}class h${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 z5;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??ZU,this.conversation=new R5($.initialMessages),this.messageBuilder=new U5,this.contributionRegistry=QU({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 O5({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,j,H)=>YU(this.logger,Q,j,H),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=$.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let Z=W===!1||W===void 0?void 0:W;this.loopTracker=new L5(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of $)if(!f.has(W.name))J.push(W),f.add(W.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await HU(f);if(J)$.push(J)}return XU(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let U=await BU(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:U})}let W=await this.composeSystemPrompt(),Z=c7(this.config,this.logger,this.telemetry),Q=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let U of Q)j.set(U.name,U);for(let U of this.config.tools)j.set(U.name,U);let H=this.conversation.getConversationId(),X=a7(this.config),A=Array.from(j.values()),Y=fJ(this.conversation.getMessages()),V=r7({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:H,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:A,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[oQ]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,A),initialMessages:Y,systemPrompt:W}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((U)=>{this.handleRuntimeEvent(U)}),G,R;try{if($.isContinue)G=await B.continue(void 0);else G=await B.run("")}catch(U){R=U instanceof Error?U:Error(String(U))}finally{K();try{await this.activeTrackerWork}catch(U){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:U})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(G&&G.messages.length>0){let U=Jf(G.messages);this.conversation.replaceMessages(U)}let P=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:P})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=AU([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let W=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(W);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let Z=Jf(W.messages),Q=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:Z,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:W.emitStatusNotice});if(!j)return;return{...j.messages?{messages:fJ(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(JJ($));return fJ(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)f=await W.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,W=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((X)=>X.type==="tool-result"),Q=Z?.type==="tool-result"&&Z.isError===!0,j=Q?jU(Z?.type==="tool-result"?Z.output:void 0):void 0,H={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:W,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(H),Q){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(Jf($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),W=Jf(f).filter((Z)=>!Z.id||!J.has(Z.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:$,input:f});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:W.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:W,endedAt:Z}=$,Q=Z.getTime()-W.getTime(),j=J?"error":VU(f),H=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",X=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,A=f?Jf(f.messages):this.conversation.getMessages(),Y=a7(this.config);if(J)throw J;return{text:H,usage:X,messages:A,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:Y},startedAt:W,endedAt:Z,durationMs:Q}}}function YU($,f,J,W){if(!$)return;if(f==="debug"){$.debug(J,W);return}if(f==="error"&&$.error){$.error(J,W);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...W,severity:Z})}function VU($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function BU($,f,J,W){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => n7);return Z($,f,J,W)}function a7($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=G5($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as t7}from"@cline/shared";function s7($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return t7({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
147
- ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function o7($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return t7({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function WJ($){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 df($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?s7($.prompt,f):o7($.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 ZJ($){let f=df($),J=new h$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var PU=_5.object({systemPrompt:_5.string().describe("System prompt defining the sub-agent's behavior"),task:_5.string().describe("Task for the sub-agent to complete")});function Wf($){return KU({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:GU(PU),execute:async(f,J)=>{let W=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=ZJ({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:W,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),Q=Z.getAgentId(),j=Z.getConversationId(),H=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:Q,conversationId:j,parentAgentId:H,input:f})}catch{}try{let X=await Z.run(f.task),A={text:X.text,iterations:X.iterations,finishReason:X.finishReason,usage:{inputTokens:X.usage.inputTokens,outputTokens:X.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:H,input:f,result:A,agentResult:X})}catch{}return A}catch(X){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:H,input:f,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as J0,TEAM_AWAIT_TIMEOUT_MS as UU,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as FU,TEAM_RUN_TEXT_PREVIEW_LIMIT as RU,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as DU,TeamAttachOutcomeFragmentInputSchema as e7,TeamAwaitRunsInputSchema as $3,TeamBroadcastInputSchema as f3,TeamBroadcastToolResultSchema as LU,TeamCancelRunInputSchema as J3,TeamCancelRunToolResultSchema as OU,TeamCleanupInputSchema as W3,TeamCleanupToolResultSchema as zU,TeamCreateOutcomeInputSchema as Z3,TeamCreateOutcomeToolResultSchema as _U,TeamFinalizeOutcomeInputSchema as Q3,TeamFinalizeOutcomeToolResultSchema as TU,TeamListOutcomesInputSchema as j3,TeamListRunsInputSchema as H3,TeamMailboxMessageToolResultSchema as NU,TeamMissionLogInputSchema as X3,TeamMissionLogToolResultSchema as MU,TeamOutcomeFragmentToolResultSchema as A3,TeamOutcomeToolResultSchema as yU,TeamReadMailboxInputSchema as Y3,TeamReviewOutcomeFragmentInputSchema as V3,TeamRunTaskInputSchema as B3,TeamRunTaskToolResultSchema as T5,TeamRunToolSummarySchema as N5,TeamSendMessageInputSchema as K3,TeamSendMessageToolResultSchema as qU,TeamShutdownTeammateInputSchema as G3,TeamSimpleAgentStatusToolResultSchema as P3,TeamSpawnTeammateInputSchema as U3,TeamStatusInputSchema as F3,TeamStatusToolResultSchema as wU,TeamTaskInputSchema as R3,TeamTaskToolResultSchema as lf,validateWithZod as S,zodToJsonSchema as W0}from"@cline/shared";function D3($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function G1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function SU($){let f=$.result;if(!f)return;return{textPreview:D3(f.text,RU),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 QJ($){return $?.toISOString()}function M5($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:D3($.message,FU),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:QJ($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:QJ($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:QJ($.heartbeatAt),lastProgressAt:QJ($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:SU($)}}function hU($){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 jJ=["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 L3($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...pf({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:df({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function HJ($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,W=pf({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let Q of $.restoredTeammates??[]){if($.runtime.isTeammateActive(Q.agentId))continue;L3({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Q}),Z.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:Z}}function pf($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,W=$.includeManagementTools??!0,Z=[];if(J)Z.push(J0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:W0(U3),execute:async(j)=>{let H=S(U3,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 X={agentId:H.agentId,rolePrompt:H.rolePrompt};if(L3({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:X}),!W)$.onLeadToolsUnlocked?.(pf({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return S(P3,{agentId:H.agentId,status:"spawned"})}}));if(!W)return Z;Z.push(J0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:W0(G3),execute:async(j)=>{let H=S(G3,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(H.agentId,H.reason),S(P3,{agentId:H.agentId,status:"stopped"})}})),Z.push(J0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:W0(F3),execute:async(j)=>{return S(F3,j),S(wU,$.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:W0(R3),execute:async(j)=>{let H=S(R3,j);switch(H.action){case"create":{let X=new Set(DU.create??[]),A=Object.entries(j).filter(([V,B])=>X.has(V)&&B!=null).map(([V])=>V),Y=$.runtime.createTask({title:G1(H.title,"title"),description:G1(H.description,"description"),dependsOn:H.dependsOn,assignee:H.assignee,createdBy:$.requesterId});return S(lf,{action:"create",taskId:Y.id,status:Y.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return S(lf,{action:"list",tasks:$.runtime.listTaskItems({status:H.status,assignee:H.assignee})});case"claim":{let X=$.runtime.claimTask(G1(H.taskId,"taskId"),$.requesterId);return S(lf,{action:"claim",taskId:X.id,status:X.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 X=$.runtime.completeTask(G1(H.taskId,"taskId"),$.requesterId,G1(H.summary,"summary"));return S(lf,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=$.runtime.blockTask(G1(H.taskId,"taskId"),$.requesterId,G1(H.reason,"reason"));return S(lf,{action:"block",taskId:X.id,status:X.status})}}}}));let Q=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:W0(B3),execute:async(j)=>{let H=S(B3,j);if(H.runMode==="async"){let Y=$.runtime.startTeammateRun(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:$.requesterId,continueConversation:H.continueConversation||void 0});return S(T5,{agentId:H.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${H.agentId} and queued as ${Y.id}.`,runId:Y.id})}let X=Q.get(H.agentId);if(X){let Y=await X;return S(T5,{...Y,status:"joined",deduped:!0,message:`Task for ${H.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=$.runtime.routeToTeammate(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:$.requesterId,continueConversation:H.continueConversation||void 0}).then((Y)=>S(T5,{agentId:H.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${H.agentId} and completed in sync mode.`,text:Y.text,iterations:Y.iterations})).finally(()=>{Q.delete(H.agentId)});return Q.set(H.agentId,A),await A}})),Z.push(J0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:W0(J3),execute:async(j)=>{let H=S(J3,j),X=$.runtime.cancelRun(H.runId,H.reason);return S(OU,{runId:X.id,status:X.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:W0(H3),execute:async(j)=>S(N5.array(),$.runtime.listRuns(S(H3,j)).map(M5))})),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:W0($3),timeoutMs:UU,execute:async(j)=>{let H=S($3,j);if(H.runId){let Y=await $.runtime.awaitRun(H.runId);return hU(Y),S(N5,M5(Y))}let X=await $.runtime.awaitAllRuns(),A=X.filter((Y)=>["failed","cancelled","interrupted"].includes(Y.status));if(A.length>0){let Y=A.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${Y}`)}return S(N5.array(),X.map(M5))}})),Z.push(J0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:W0(K3),execute:async(j)=>{let H=S(K3,j),X=$.runtime.sendMessage($.requesterId,H.toAgentId,H.subject,H.body,H.taskId??void 0);return S(qU,{id:X.id,toAgentId:X.toAgentId})}})),Z.push(J0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:W0(f3),execute:async(j)=>{let H=S(f3,j),X=$.runtime.broadcast($.requesterId,H.subject,H.body,{taskId:H.taskId??void 0});return S(LU,{delivered:X.length})}})),Z.push(J0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:W0(Y3),execute:async(j)=>{let H=S(Y3,j);return S(NU.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:H.unreadOnly,markRead:!0}))}})),Z.push(J0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:W0(X3),execute:async(j)=>{let H=S(X3,j),X=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:H.taskId||void 0,kind:H.kind,summary:H.summary,evidence:H.evidence?.length?H.evidence:void 0,nextAction:H.nextAction||void 0});return S(MU,{id:X.id})}})),Z.push(J0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:W0(W3),execute:async(j)=>{if(S(W3,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),S(zU,{status:"cleaned"})}})),Z.push(J0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:W0(Z3),execute:async(j)=>{let H=S(Z3,j),X=$.runtime.createOutcome({title:H.title,requiredSections:H.requiredSections,createdBy:$.requesterId});return S(_U,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),Z.push(J0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:W0(e7),execute:async(j)=>{let H=S(e7,j),X=$.runtime.attachOutcomeFragment({outcomeId:H.outcomeId,section:H.section,sourceAgentId:$.requesterId,sourceRunId:H.sourceRunId||void 0,content:H.content});return S(A3,{fragmentId:X.id,status:X.status})}})),Z.push(J0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:W0(V3),execute:async(j)=>{let H=S(V3,j),X=$.runtime.reviewOutcomeFragment({fragmentId:H.fragmentId,reviewedBy:$.requesterId,approved:H.approved});return S(A3,{fragmentId:X.id,status:X.status})}})),Z.push(J0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:W0(Q3),execute:async(j)=>{let H=S(Q3,j),X=$.runtime.finalizeOutcome(H.outcomeId);return S(TU,{outcomeId:X.id,status:X.status})}})),Z.push(J0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:W0(j3),execute:async(j)=>{return S(j3,j),S(yU.array(),$.runtime.listOutcomes())}})),Z}function O3($){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 CU=[{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:Wf({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...jJ]}],EU={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function bU($){return $==="plan"||$==="yolo"?$:"act"}function _3($){let f=bU($.mode),J=s0[S$({mode:f})],W=uf($.providerId??"",$.modelId??"",f,vf);return{mode:f,flags:{...J,...W,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function z3($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=_3(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=EU[$];return W?J[W]===!0:!1}function kU($,f){if($.id==="editor"){let{flags:J}=_3(f),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:z3($.id,f),headlessToolNames:[W?"apply_patch":"editor"]}}return{...$,defaultEnabled:z3($.id,f)}}function rf($={}){return CU.map((f)=>kU(f,$))}function T3($={}){return rf($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function N3($){if(!$.enabled)return new Set;let f=rf($.availabilityContext),J=new Set(f.map((W)=>W.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of $.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function y5($,f={}){return rf(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function M3($,f={}){return y5($,f)}function nf($={}){let{executorOptions:f={},executors:J,...W}=$,Z={...$J(f),...J??{}};return $f({...W,executors:Z})}function XJ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function IU($){if(!$||$.length===0)return;let f=$.map(XJ).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function xU($,f,J){if(!J)return!0;let W=XJ($),Z=XJ(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function af($,f){let J=IU(f);return[...$.getSnapshot("skill").entries()].map(([Z,Q])=>{let j=Q.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>xU(Z.id,Z.name,J))}function mU($,f){return af($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function gU($,f,J){let W=XJ(f);if(!W)return{error:"Missing skill name."};let Z=af($,J),Q=Z.find((Y)=>Y.id===W);if(Q){let{skill:Y}=Q;if(Y.disabled===!0)return{error:`Skill "${Y.name}" is configured but disabled.`};return{id:Q.id,skill:Y}}let j=W.includes(":")?W.split(":").at(-1)??W:W,H=Z.filter(({id:Y})=>{if(Y===j)return!0;return Y.endsWith(`:${j}`)}),X=H.filter(({skill:Y})=>Y.disabled!==!0);if(X.length===1){let{id:Y,skill:V}=X[0];return{id:Y,skill:V}}if(X.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${X.map(({id:Y})=>Y).join(", ")}`};if(H.length===1){let{skill:Y}=H[0];return{error:`Skill "${Y.name}" is configured but disabled.`}}if(H.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${H.map(({id:Y})=>Y).join(", ")}`};let A=mU($,J);return{error:A.length>0?`Skill "${f}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function vU($,f=Promise.resolve(),J){let W=new Set,Z=async(Q,j)=>{await f;let H=gU($,Q,J);if("error"in H)return H.error;let{id:X,skill:A}=H;if(W.has(X))return`Skill "${A.name}" is already running.`;W.add(X);try{let Y=j?.trim(),V=Y?`
146
+ ${Q}`;return J||Q}function uF(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let Q of $){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of $)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of $){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 $){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of $){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 $){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 $)await Q.onEvent?.(J)}}}class If{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 k5;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=f,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=f.parentAgentId,this.logger=$.logger??f.logger,this.telemetry=$.telemetry??f.telemetry,this.createAgentRuntimeImpl=$.createAgentRuntimeImpl??xF,this.conversation=new S5(f.initialMessages),this.messageBuilder=new w5,this.contributionRegistry=gF({extensions:f.extensions?[...f.extensions]:[],setupContext:{session:f.extensionContext?.session,client:f.extensionContext?.client,user:f.extensionContext?.user,workspaceInfo:f.extensionContext?.workspace,automation:f.extensionContext?.automation,logger:f.extensionContext?.logger??this.logger,telemetry:f.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=f.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new b5({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,H)=>dF(this.logger,W,j,H),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=f.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new h5(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(f){if(f.length===0)return;let $=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of f)if(!$.has(Q.name))J.push(Q),$.add(Q.name);this.config={...this.config,tools:J}}updateConnection(f){let $={...this.config};if(f.providerId!==void 0)$.providerId=f.providerId;if(f.modelId!==void 0)$.modelId=f.modelId;if(f.apiKey!==void 0)$.apiKey=f.apiKey;if(f.baseUrl!==void 0)$.baseUrl=f.baseUrl;if(f.headers!==void 0)$.headers=f.headers;if(f.providerConfig!==void 0)$.providerConfig=f.providerConfig;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinking!==void 0)$.thinking=f.thinking;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;this.config=$}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore(f){this.conversation.restore(f),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}abort(f){let $=typeof f==="string"?f:f instanceof Error?f.message:f===void 0?void 0:String(f);if(this.abortRequested=!0,this.abortReason=$,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort($)}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:f,userImages:$,userFiles:J,isContinue:!1})}continue(f,$,J){return this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let f=[];for(let $ of this.contributionRegistry.getRegisteredRules()){let J=await vF($);if(J)f.push(J)}return cF(this.config.systemPrompt,f)}executeRun(f){let $;return $=this.executeRunInternal(f).finally(()=>{if(this.activeRunPromise===$)this.activeRunPromise=null}),this.activeRunPromise=$,$}async executeRunInternal(f){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 $=new Date,J=f.userMessage;if(J!==void 0){let F=await pF(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Q=await this.composeSystemPrompt(),Z=A3(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let F of W)j.set(F.name,F);for(let F of this.config.tools)j.set(F.name,F);let H=this.conversation.getConversationId(),X=F3(this.config),A=Array.from(j.values()),Y=YJ(this.conversation.getMessages()),V=K3({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:H,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:A,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[D7]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,A),initialMessages:Y,systemPrompt:Q}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),P,R;try{if(f.isContinue)P=await B.continue(void 0);else P=await B.run("")}catch(F){R=F instanceof Error?F:Error(String(F))}finally{K();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(P&&P.messages.length>0){let F=X1(P.messages);this.conversation.replaceMessages(F)}let G=new Date;try{return this.buildLegacyResult({runResult:P,thrownError:R,startedAt:$,endedAt:G})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch(f){if(this.config.hookErrorMode==="throw")throw f;this.emitLegacyEvent({type:"error",error:f instanceof Error?f:Error(String(f)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let f=uF([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let Q=J?.messages??$.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=X1(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:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:YJ(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(VJ(f));return YJ($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)$=await Q.build($);return this.messageBuilder.buildForApi($)}handleRuntimeEvent(f){switch(f.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage(f.snapshot.messages,[f.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set(f.toolCall.toolCallId,new Date),this.toolInputs.set(f.toolCall.toolCallId,f.toolCall.input),this.inspectLoopForToolCall(f.toolCall.toolName,f.toolCall.input,f.iteration);break}case"tool-finished":{let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=new Date,Q=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let Z=f.message.content.find((X)=>X.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?mF(Z?.type==="tool-result"?Z.output:void 0):void 0,H={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(H),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={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};break}default:break}for(let $ of this.eventAdapter.translate(f))this.emitLegacyEvent($)}syncConversationFromRuntimeMessage(f,$){if(f.length>0){this.conversation.replaceMessages(X1(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=X1($).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent(f){for(let $ 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:f,input:$});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 \`${f}\`; stopping to avoid a loop.`})}enqueueMistakeRecord(f){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let $=await this.mistakeTracker.record(f);if($.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:$.message}]}),this.activeRuntime?.abort($.reason??$.message)})}buildLegacyResult(f){let{runResult:$,thrownError:J,startedAt:Q,endedAt:Z}=f,W=Z.getTime()-Q.getTime(),j=J?"error":lF($),H=$?.outputText||($?.status==="failed"?$.error?.message:void 0)||"",X=$?{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}:this.currentRunUsage,A=$?X1($.messages):this.conversation.getMessages(),Y=F3(this.config);if(J)throw J;return{text:H,usage:X,messages:A,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:Y},startedAt:Q,endedAt:Z,durationMs:W}}}function dF(f,$,J,Q){if(!f)return;if($==="debug"){f.debug(J,Q);return}if($==="error"&&f.error){f.error(J,Q);return}let Z=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...Q,severity:Z})}function lF(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function pF(f,$,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => G3);return Z(f,$,J,Q)}function F3(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=q5(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as U3}from"@cline/shared";function R3(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return U3({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
147
+ ${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function D3(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return U3({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function A1(f){let $={...f};return{getRuntimeConfig:()=>$,getConnectionConfig:()=>({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking}),updateConnectionDefaults:(J)=>{$={...$,...J}}}}function o1(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?R3(f.prompt,$):D3(f.prompt,$);return{...f.configProvider.getConnectionConfig(),systemPrompt:J,tools:f.tools,maxIterations:f.maxIterations??$.maxIterations,parentAgentId:f.parentAgentId,abortSignal:f.abortSignal,onEvent:f.onEvent,hooks:$.hooks,extensions:$.extensions,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval,logger:$.logger,role:f.role}}function Y1(f){let $=o1(f),J=new If($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var nF=I5.object({systemPrompt:I5.string().describe("System prompt defining the sub-agent's behavior"),task:I5.string().describe("Task for the sub-agent to complete")});function V1(f){return rF({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:iF(nF),execute:async($,J)=>{let Q=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],Z=Y1({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:Q,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),H=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:H,input:$})}catch{}try{let X=await Z.run($.task),A={text:X.text,iterations:X.iterations,finishReason:X.finishReason,usage:{inputTokens:X.usage.inputTokens,outputTokens:X.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:H,input:$,result:A,agentResult:X})}catch{}return A}catch(X){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:H,input:$,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as Q0,TEAM_AWAIT_TIMEOUT_MS as aF,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as tF,TEAM_RUN_TEXT_PREVIEW_LIMIT as sF,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as oF,TeamAttachOutcomeFragmentInputSchema as L3,TeamAwaitRunsInputSchema as O3,TeamBroadcastInputSchema as _3,TeamBroadcastToolResultSchema as eF,TeamCancelRunInputSchema as T3,TeamCancelRunToolResultSchema as fU,TeamCleanupInputSchema as z3,TeamCleanupToolResultSchema as $U,TeamCreateOutcomeInputSchema as M3,TeamCreateOutcomeToolResultSchema as JU,TeamFinalizeOutcomeInputSchema as N3,TeamFinalizeOutcomeToolResultSchema as QU,TeamListOutcomesInputSchema as q3,TeamListRunsInputSchema as y3,TeamMailboxMessageToolResultSchema as ZU,TeamMissionLogInputSchema as w3,TeamMissionLogToolResultSchema as WU,TeamOutcomeFragmentToolResultSchema as C3,TeamOutcomeToolResultSchema as jU,TeamReadMailboxInputSchema as S3,TeamReviewOutcomeFragmentInputSchema as E3,TeamRunTaskInputSchema as h3,TeamRunTaskToolResultSchema as x5,TeamRunToolSummarySchema as g5,TeamSendMessageInputSchema as b3,TeamSendMessageToolResultSchema as HU,TeamShutdownTeammateInputSchema as k3,TeamSimpleAgentStatusToolResultSchema as I3,TeamSpawnTeammateInputSchema as x3,TeamStatusInputSchema as g3,TeamStatusToolResultSchema as XU,TeamTaskInputSchema as m3,TeamTaskToolResultSchema as e1,validateWithZod as C,zodToJsonSchema as Z0}from"@cline/shared";function v3(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function R$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function AU(f){let $=f.result;if(!$)return;return{textPreview:v3($.text,sF),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function BJ(f){return f?.toISOString()}function m5(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:v3(f.message,tF),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:BJ(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:BJ(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:BJ(f.heartbeatAt),lastProgressAt:BJ(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:AU(f)}}function YU(f){if(f.status==="failed")throw Error(`Run "${f.id}" failed${f.error?`: ${f.error}`:""}`);if(f.status==="cancelled")throw Error(`Run "${f.id}" was cancelled${f.error?`: ${f.error}`:""}`);if(f.status==="interrupted")throw Error(`Run "${f.id}" was interrupted${f.error?`: ${f.error}`:""}`)}var KJ=["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 c3(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...f2({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:o1({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function PJ(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,Q=f2({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),Z=[];for(let W of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(W.agentId))continue;c3({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function f2(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,Q=f.includeManagementTools??!0,Z=[];if(J)Z.push(Q0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Z0(x3),execute:async(j)=>{let H=C(x3,j);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!$)throw Error("Spawning teammates is disabled in this context.");let X={agentId:H.agentId,rolePrompt:H.rolePrompt};if(c3({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:X}),!Q)f.onLeadToolsUnlocked?.(f2({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return C(I3,{agentId:H.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(Q0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Z0(k3),execute:async(j)=>{let H=C(k3,j);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(H.agentId,H.reason),C(I3,{agentId:H.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(g3),execute:async(j)=>{return C(g3,j),C(XU,f.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(m3),execute:async(j)=>{let H=C(m3,j);switch(H.action){case"create":{let X=new Set(oF.create??[]),A=Object.entries(j).filter(([V,B])=>X.has(V)&&B!=null).map(([V])=>V),Y=f.runtime.createTask({title:R$(H.title,"title"),description:R$(H.description,"description"),dependsOn:H.dependsOn,assignee:H.assignee,createdBy:f.requesterId});return C(e1,{action:"create",taskId:Y.id,status:Y.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return C(e1,{action:"list",tasks:f.runtime.listTaskItems({status:H.status,assignee:H.assignee})});case"claim":{let X=f.runtime.claimTask(R$(H.taskId,"taskId"),f.requesterId);return C(e1,{action:"claim",taskId:X.id,status:X.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 X=f.runtime.completeTask(R$(H.taskId,"taskId"),f.requesterId,R$(H.summary,"summary"));return C(e1,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=f.runtime.blockTask(R$(H.taskId,"taskId"),f.requesterId,R$(H.reason,"reason"));return C(e1,{action:"block",taskId:X.id,status:X.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(h3),execute:async(j)=>{let H=C(h3,j);if(H.runMode==="async"){let Y=f.runtime.startTeammateRun(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:f.requesterId,continueConversation:H.continueConversation||void 0});return C(x5,{agentId:H.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${H.agentId} and queued as ${Y.id}.`,runId:Y.id})}let X=W.get(H.agentId);if(X){let Y=await X;return C(x5,{...Y,status:"joined",deduped:!0,message:`Task for ${H.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=f.runtime.routeToTeammate(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:f.requesterId,continueConversation:H.continueConversation||void 0}).then((Y)=>C(x5,{agentId:H.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${H.agentId} and completed in sync mode.`,text:Y.text,iterations:Y.iterations})).finally(()=>{W.delete(H.agentId)});return W.set(H.agentId,A),await A}})),Z.push(Q0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Z0(T3),execute:async(j)=>{let H=C(T3,j),X=f.runtime.cancelRun(H.runId,H.reason);return C(fU,{runId:X.id,status:X.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(y3),execute:async(j)=>C(g5.array(),f.runtime.listRuns(C(y3,j)).map(m5))})),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(O3),timeoutMs:aF,execute:async(j)=>{let H=C(O3,j);if(H.runId){let Y=await f.runtime.awaitRun(H.runId);return YU(Y),C(g5,m5(Y))}let X=await f.runtime.awaitAllRuns(),A=X.filter((Y)=>["failed","cancelled","interrupted"].includes(Y.status));if(A.length>0){let Y=A.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${Y}`)}return C(g5.array(),X.map(m5))}})),Z.push(Q0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Z0(b3),execute:async(j)=>{let H=C(b3,j),X=f.runtime.sendMessage(f.requesterId,H.toAgentId,H.subject,H.body,H.taskId??void 0);return C(HU,{id:X.id,toAgentId:X.toAgentId})}})),Z.push(Q0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Z0(_3),execute:async(j)=>{let H=C(_3,j),X=f.runtime.broadcast(f.requesterId,H.subject,H.body,{taskId:H.taskId??void 0});return C(eF,{delivered:X.length})}})),Z.push(Q0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Z0(S3),execute:async(j)=>{let H=C(S3,j);return C(ZU.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:H.unreadOnly,markRead:!0}))}})),Z.push(Q0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Z0(w3),execute:async(j)=>{let H=C(w3,j),X=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:H.taskId||void 0,kind:H.kind,summary:H.summary,evidence:H.evidence?.length?H.evidence:void 0,nextAction:H.nextAction||void 0});return C(WU,{id:X.id})}})),Z.push(Q0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Z0(z3),execute:async(j)=>{if(C(z3,j),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),C($U,{status:"cleaned"})}})),Z.push(Q0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Z0(M3),execute:async(j)=>{let H=C(M3,j),X=f.runtime.createOutcome({title:H.title,requiredSections:H.requiredSections,createdBy:f.requesterId});return C(JU,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),Z.push(Q0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Z0(L3),execute:async(j)=>{let H=C(L3,j),X=f.runtime.attachOutcomeFragment({outcomeId:H.outcomeId,section:H.section,sourceAgentId:f.requesterId,sourceRunId:H.sourceRunId||void 0,content:H.content});return C(C3,{fragmentId:X.id,status:X.status})}})),Z.push(Q0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Z0(E3),execute:async(j)=>{let H=C(E3,j),X=f.runtime.reviewOutcomeFragment({fragmentId:H.fragmentId,reviewedBy:f.requesterId,approved:H.approved});return C(C3,{fragmentId:X.id,status:X.status})}})),Z.push(Q0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Z0(N3),execute:async(j)=>{let H=C(N3,j),X=f.runtime.finalizeOutcome(H.outcomeId);return C(QU,{outcomeId:X.id,status:X.status})}})),Z.push(Q0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Z0(q3),execute:async(j)=>{return C(q3,j),C(jU.array(),f.runtime.listOutcomes())}})),Z}function u3(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}var VU=[{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:V1({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...KJ]}],BU={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function KU(f){return f==="plan"||f==="yolo"?f:"act"}function l3(f){let $=KU(f.mode),J=e0[kf({mode:$})],Q=t1(f.providerId??"",f.modelId??"",$,a1);return{mode:$,flags:{...J,...Q,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function d3(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=l3($);if(f==="spawn_agent")return J.enableSpawnAgent===!0;if(f==="teams")return J.enableAgentTeams===!0;if(f==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let Q=BU[f];return Q?J[Q]===!0:!1}function PU(f,$){if(f.id==="editor"){let{flags:J}=l3($),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:d3(f.id,$),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...f,defaultEnabled:d3(f.id,$)}}function $2(f={}){return VU.map(($)=>PU($,f))}function p3(f={}){return $2(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function r3(f){if(!f.enabled)return new Set;let $=$2(f.availabilityContext),J=new Set($.map((Q)=>Q.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of f.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${$.map((Z)=>Z.id).join(", ")}`);return new Set(f.allowlist)}function v5(f,$={}){return $2($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function i3(f,$={}){return v5(f,$)}function J2(f={}){let{executorOptions:$={},executors:J,...Q}=f,Z={...AJ($),...J??{}};return j1({...Q,executors:Z})}function GJ(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function GU(f){if(!f||f.length===0)return;let $=f.map(GJ).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function FU(f,$,J){if(!J)return!0;let Q=GJ(f),Z=GJ($),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=GU($);return[...f.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)=>FU(Z.id,Z.name,J))}function UU(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 RU(f,$,J){let Q=GJ($);if(!Q)return{error:"Missing skill name."};let Z=Q2(f,J),W=Z.find((Y)=>Y.id===Q);if(W){let{skill:Y}=W;if(Y.disabled===!0)return{error:`Skill "${Y.name}" is configured but disabled.`};return{id:W.id,skill:Y}}let j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,H=Z.filter(({id:Y})=>{if(Y===j)return!0;return Y.endsWith(`:${j}`)}),X=H.filter(({skill:Y})=>Y.disabled!==!0);if(X.length===1){let{id:Y,skill:V}=X[0];return{id:Y,skill:V}}if(X.length>1)return{error:`Skill "${$}" is ambiguous. Use one of: ${X.map(({id:Y})=>Y).join(", ")}`};if(H.length===1){let{skill:Y}=H[0];return{error:`Skill "${Y.name}" is configured but disabled.`}}if(H.length>1)return{error:`Skill "${$}" is ambiguous, and all matches are disabled: ${H.map(({id:Y})=>Y).join(", ")}`};let A=UU(f,J);return{error:A.length>0?`Skill "${$}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function c5(f,$=Promise.resolve(),J){let Q=new Set,Z=async(W,j)=>{await $;let H=RU(f,W,J);if("error"in H)return H.error;let{id:X,skill:A}=H;if(Q.has(X))return`Skill "${A.name}" is already running.`;Q.add(X);try{let Y=j?.trim(),V=Y?`
148
148
  <command-args>${Y}</command-args>`:"",B=A.description?.trim()?`Description: ${A.description.trim()}
149
149
 
150
150
  `:"";return`<command-name>${A.name}</command-name>${V}
151
151
  <command-instructions>
152
152
  ${B}${A.instructions}
153
- </command-instructions>`}finally{W.delete(X)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>af($,J).map(({skill:Q,...j})=>j),enumerable:!0,configurable:!1}),Z}function y3($){let f=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((W)=>Boolean(W))},async setup(W){if(await f,$.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>sQ($.watcher)});if($.registerSkillsTool)W.registerTool(e1(vU($.watcher,f,$.allowedSkillNames)));for(let Z of If($.watcher).filter((Q)=>Q.kind==="skill"&&$.includeSkills||Q.kind==="workflow"&&$.includeWorkflows))W.registerCommand({name:Z.name,description:Z.description,handler:(Q)=>{let j=Q.trim();return j?`${Z.instructions}
153
+ </command-instructions>`}finally{Q.delete(X)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>Q2(f,J).map(({skill:W,...j})=>j),enumerable:!0,configurable:!1}),Z}function n3(f){let $=f.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.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:()=>R7(f.watcher)});if(f.registerSkillsTool)Q.registerTool(W1(c5(f.watcher,$,f.allowedSkillNames)));for(let Z of p1(f.watcher).filter((W)=>W.kind==="skill"&&f.includeSkills||W.kind==="workflow"&&f.includeWorkflows))Q.registerCommand({name:Z.name,description:Z.description,handler:(W)=>{let j=W.trim();return j?`${Z.instructions}
154
154
 
155
- ${j}`:Z.instructions}})}}}class q3{watcher;ready;stopped=!1;constructor($){this.watcher=rQ($)}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 If(this.watcher)}resolveRuntimeSlashCommand($){return aQ($,this.watcher)}hasConfiguredSkills($){return af(this.watcher,$).some((f)=>!f.disabled)}createExtension($){return y3({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function Zf($){return new q3($)}import{readFile as uU,writeFile as cU}from"node:fs/promises";import S3 from"yaml";function dU($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J,Q=S3.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}function w3($,f){return`---
156
- ${S3.stringify($).trimEnd()}
155
+ ${j}`:Z.instructions}})}}}class a3{watcher;ready;stopped=!1;constructor(f){this.watcher=K7(f)}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(f){await this.start(),await this.watcher.refreshType(f)}listRecords(f){return[...this.watcher.getSnapshot(f).entries()].map(([$,J])=>({type:f,id:$,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return p1(this.watcher)}resolveRuntimeSlashCommand(f){return F7(f,this.watcher)}hasConfiguredSkills(f){return Q2(this.watcher,f).some(($)=>!$.disabled)}createSkillsExecutor(f){return c5(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),f)}createExtension(f){return n3({...f,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function B1(f){return new a3(f)}import{readFile as DU,writeFile as LU}from"node:fs/promises";import s3 from"yaml";function OU(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,Q,Z]=J,W=s3.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}function t3(f,$){return`---
156
+ ${s3.stringify(f).trimEnd()}
157
157
  ---
158
- ${f}`}function lU($,f){let{data:J,body:W,hadFrontmatter:Z}=dU($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return W;return w3(J,W)}return J.disabled=!0,w3(J,W)}async function h3({filePath:$,enabled:f}){let J=await uU($,"utf8"),W=lU(J,f);return await cU($,W),{filePath:$,enabled:f,disabled:!f}}import{spawn as FF}from"node:child_process";import{StringDecoder as p3}from"node:string_decoder";import{UnauthorizedError as u3}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as RF}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as HF}from"node:crypto";import{UnauthorizedError as XF}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as AF}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as YF}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as VF}from"@modelcontextprotocol/sdk/client/streamableHttp.js";AJ();var BF="/mcp/oauth/callback",KF=[1456,1457,1458],GF=300000;function PF($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function UF($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function VJ($){let f={};try{f=ef($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,W,Z=async(j)=>{let H=Qf(j(f))??{};try{f=$2($.serverName,()=>H,{filePath:$.settingsPath})}catch{f=H}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return UF(f.redirectUrl??$.redirectUrl)},state:()=>{return W=HF(),W},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((H)=>({...H,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((H)=>({...H,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((H)=>({...H,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((H)=>{if(j==="all")return{lastError:H.lastError,redirectUrl:H.redirectUrl};return{...H,...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((H)=>({...H,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>W,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((H)=>({...H,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function YJ($){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 YF(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new VF(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function g3($){return new AF({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function v3($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (AJ(),m3)),W=J({filePath:$.filePath}).find((X)=>X.name===f);if(!W)throw Error(`MCP server "${f}" is not configured.`);if(W.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(W.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await W$({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:KF,callbackPath:$.callbackPath??BF,timeoutMs:$.timeoutMs??GF,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let Q=VJ({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(X)=>{await $.openUrl?.(X)}});await Q.resetInteractiveState();let j=g3($),H;try{let X=YJ({registration:W,oauthProvider:Q.provider,fetch:$.fetch});try{return await j.connect(X),await j.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(A){if(!(A instanceof XF))throw A;if(!Q.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let V=await Z.waitForCallback();if(!V)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(V.error)throw Error(`OAuth authorization failed: ${V.error}`);if(!V.code)throw Error("OAuth callback did not include an authorization code.");let B=Q.getLastOAuthState();if(!B)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(V.state!==B)throw Error("OAuth authorization failed: state mismatch.");await X.finishAuth(V.code),H=g3($);let K=YJ({registration:W,oauthProvider:Q.provider,fetch:$.fetch});return await H.connect(K),await H.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(X){let A=PF(X);throw await Q.markError(A),Error(A)}finally{await j.close().catch(()=>{return}),await H?.close().catch(()=>{return}),Z.close()}}var DF="2024-11-05",LF=5000,OF=1500,c3="http://127.0.0.1:1456/mcp/oauth/callback";function BJ($){return $ instanceof Error?$.message:String($)}function d3($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
158
+ ${$}`}function _U(f,$){let{data:J,body:Q,hadFrontmatter:Z}=OU(f);if(!Z&&$)return f;if($){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return Q;return t3(J,Q)}return J.disabled=!0,t3(J,Q)}async function o3({filePath:f,enabled:$}){let J=await DU(f,"utf8"),Q=_U(J,$);return await LU(f,Q),{filePath:f,enabled:$,disabled:!$}}import{spawn as aU}from"node:child_process";import{StringDecoder as Bj}from"node:string_decoder";import{UnauthorizedError as Xj}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as tU}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as mU}from"node:crypto";import{UnauthorizedError as vU}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as cU}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as uU}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as dU}from"@modelcontextprotocol/sdk/client/streamableHttp.js";FJ();var lU="/mcp/oauth/callback",pU=[1456,1457,1458],rU=300000;function iU(f){if(f instanceof Error){let $=f.message.trim();if($.length>0)return $}return String(f)}function nU(f){return{client_name:"Cline",redirect_uris:[f],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function RJ(f){let $={};try{$=H2(f.serverName,{filePath:f.settingsPath})??{}}catch{$={}}let J,Q,Z=async(j)=>{let H=K1(j($))??{};try{$=X2(f.serverName,()=>H,{filePath:f.settingsPath})}catch{$=H}};return{provider:{get redirectUrl(){return $.redirectUrl??f.redirectUrl},get clientMetadata(){return nU($.redirectUrl??f.redirectUrl)},state:()=>{return Q=mU(),Q},clientInformation:()=>$.clientInformation,saveClientInformation:async(j)=>{await Z((H)=>({...H,clientInformation:j,redirectUrl:f.redirectUrl,lastError:void 0}))},tokens:()=>$.tokens,saveTokens:async(j)=>{await Z((H)=>({...H,tokens:j,redirectUrl:f.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await f.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((H)=>({...H,codeVerifier:j,redirectUrl:f.redirectUrl}))},codeVerifier:()=>{if(!$.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${f.serverName}".`);return $.codeVerifier},invalidateCredentials:async(j)=>{await Z((H)=>{if(j==="all")return{lastError:H.lastError,redirectUrl:H.redirectUrl};return{...H,...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((H)=>({...H,discoveryState:j}))},discoveryState:()=>$.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:f.redirectUrl}))},markError:async(j)=>{await Z((H)=>({...H,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function UJ(f){let $=f.registration.transport;if($.type==="stdio")throw Error(`MCP server "${f.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=$.headers?{headers:$.headers}:void 0;if($.type==="sse")return new uU(new URL($.url),{authProvider:f.oauthProvider,requestInit:J,fetch:f.fetch});return new dU(new URL($.url),{authProvider:f.oauthProvider,requestInit:J,fetch:f.fetch})}function jj(f){return new cU({name:f.clientName?.trim()||"@cline/core",version:f.clientVersion?.trim()||"0.0.0"})}async function Hj(f){let $=f.serverName.trim();if(!$)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (FJ(),Wj)),Q=J({filePath:f.filePath}).find((X)=>X.name===$);if(!Q)throw Error(`MCP server "${$}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${$}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${$}" uses stdio transport and does not support OAuth browser flow.`);let Z=await Xf({host:f.callbackHost,ports:f.callbackPorts?.length?f.callbackPorts:pU,callbackPath:f.callbackPath??lU,timeoutMs:f.timeoutMs??rU,successHtml:f.successHtml,onListening:f.onServerListening,onClose:f.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let W=RJ({settingsPath:f.filePath,serverName:$,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(X)=>{await f.openUrl?.(X)}});await W.resetInteractiveState();let j=jj(f),H;try{let X=UJ({registration:Q,oauthProvider:W.provider,fetch:f.fetch});try{return await j.connect(X),await j.listTools(),await W.clearError(),{serverName:$,authorized:!0,message:`MCP server "${$}" is already authorized.`}}catch(A){if(!(A instanceof vU))throw A;if(!W.getLastAuthorizationUrl())throw Error(`MCP server "${$}" did not provide an authorization URL.`);let V=await Z.waitForCallback();if(!V)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(V.error)throw Error(`OAuth authorization failed: ${V.error}`);if(!V.code)throw Error("OAuth callback did not include an authorization code.");let B=W.getLastOAuthState();if(!B)throw Error(`MCP server "${$}" did not start an OAuth stateful authorization flow.`);if(V.state!==B)throw Error("OAuth authorization failed: state mismatch.");await X.finishAuth(V.code),H=jj(f);let K=UJ({registration:Q,oauthProvider:W.provider,fetch:f.fetch});return await H.connect(K),await H.listTools(),await W.clearError(),{serverName:$,authorized:!0,message:`MCP server "${$}" OAuth authorization completed.`}}}catch(X){let A=iU(X);throw await W.markError(A),Error(A)}finally{await j.close().catch(()=>{return}),await H?.close().catch(()=>{return}),Z.close()}}var sU="2024-11-05",oU=5000,eU=1500,Aj="http://127.0.0.1:1456/mcp/oauth/callback";function DJ(f){return f instanceof Error?f.message:String(f)}function Yj(f){let $=Buffer.from(JSON.stringify(f),"utf8"),J=Buffer.from(`Content-Length: ${$.byteLength}\r
159
159
  \r
160
- `,"utf8");return Buffer.concat([J,f])}function l3($){return Buffer.from(`${JSON.stringify($)}
161
- `,"utf8")}class C5{buffer="";decoder=new p3("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
160
+ `,"utf8");return Buffer.concat([J,$])}function Vj(f){return Buffer.from(`${JSON.stringify(f)}
161
+ `,"utf8")}class r5{buffer="";decoder=new Bj("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`\r
162
162
  \r
163
- `);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(Z[1],10),j=J+4,H=j+Q;if(this.buffer.length<H)break;f.push(this.buffer.slice(j,H)),this.buffer=this.buffer.slice(H)}return f}}class E5{buffer="";decoder=new p3("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
164
- `);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)f.push(W)}return f}}class r3{registration;process;nextRequestId=1;pending=new Map;framedParser=new C5;newlineParser=new E5;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:DF,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},OF),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){f=W instanceof Error?W:Error(String(W))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new C5,this.newlineParser=new E5,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=FF(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(Z)=>this.handleStdout(Z)),W.stderr.on("data",(Z)=>{if(this.process!==W)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(Z)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${BJ(Z)}`))}),W.once("exit",(Z,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${Q??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let Z=this.pending.get(W.id);if(!Z)continue;if(this.pending.delete(W.id),clearTimeout(Z.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;Z.reject(Error(Q));continue}Z.resolve(W.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${BJ($)}.${J}`)),f.kill()}async request($,f,J=LF){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,Q={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((H,X)=>{let A=setTimeout(()=>{this.pending.delete(Z),X(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:H,reject:X,timeout:A})});try{W.stdin.write(this.protocolMode==="framed"?d3(Q):l3(Q))}catch(H){let X=this.pending.get(Z);if(X)clearTimeout(X.timeout),this.pending.delete(Z);throw H}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?d3(W):l3(W))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class i3{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 $=VJ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??c3});this.authContext=$;try{let f=new RF({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=YJ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof u3?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):BJ(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??VJ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??c3}),J=$ instanceof u3?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):BJ($);throw await f.markError(J),Error(J)}}function KJ($={}){return(f)=>f.transport.type==="stdio"?new r3(f):new i3(f,$)}AJ();function C0(){return Date.now()}function zF($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class J2{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:C0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=C0(),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=C0(),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&&C0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),W=await(await this.ensureConnectedClient(f)).listTools(),Z=zF(W);return f.toolCache=Z,f.toolCacheUpdatedAt=C0(),f.updatedAt=C0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=C0(),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=C0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=C0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=C0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=C0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=C0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),W,Z=new Promise((j)=>{W=j}),Q=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,Q),await J.catch(()=>{return});try{return await f()}finally{if(W?.(),this.operationLocks.get($)===Q)this.operationLocks.delete($)}}}import{createHash as _F}from"node:crypto";var n3=128,TF=/[^a-zA-Z0-9_-]+/g,a3=8,NF=1,MF="mcp_tool";function yF($){return _F("sha1").update($).digest("hex").slice(0,a3)}function qF($){return $.replace(TF,"_")}var GJ=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,W=qF(J);if(W===J&&J.length<=n3)return J;let Z=yF(J),Q=n3-NF-a3;return`${W.slice(0,Q)||MF}_${Z}`};function b5($){return{[($.nameTransform??GJ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function t3($){let f={};for(let J of $.toolNames)Object.assign(f,b5({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as wF}from"@cline/shared";function SF($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function PJ($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??GJ;return f.map((W)=>{let Z=J({serverName:$.serverName,toolName:W.name});return wF({name:Z,description:SF($.serverName,W),inputSchema:W.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(Q,j)=>$.provider.callTool({serverName:$.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:j})})})}n0();import{stat as hF}from"node:fs/promises";n0();var CF=32,jf=new Map;function EF($,f){if(!jf.has($)&&jf.size>=CF){let J=jf.keys().next().value;if(J)jf.delete(J)}jf.set($,f)}async function bF($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let W=await hF(J);return`${J}:${W.mtimeMs}:${W.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function s3($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function kF($){return $.sort((f,J)=>{let W=f.name.localeCompare(J.name);if(W!==0)return W;return f.path.localeCompare(J.path)})}function IF($,f){if(!$.setup)return[];let J=[],W={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(W,{workspaceInfo:f}),J}async function o3($){let f=Ef({workspacePath:$.workspacePath,cwd:$.cwd}),J=Q$($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let W=await bF({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=jf.get(W);if(Z)return{tools:s3(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let Q=[],j=[],H=[],X;try{X=await _8({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...X.failures],H=[...X.warnings];for(let V of X.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of IF(V,{rootPath:$.workspacePath}))Q.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=f.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await X?.shutdown().catch(()=>{})}let A=kF(Q);return EF(W,{tools:A,failures:j,warnings:H}),{tools:s3(A,J),failures:j,warnings:H}}async function k5($){return(await o3($)).tools}function FJ($,f){if(!f)return"global";let J=mF(f,$);return!J.startsWith("..")&&!xF(J)?"workspace":"global"}function W2($){return[...$].sort((f,J)=>{let W=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return W(f.source)-W(J.source);return f.name.localeCompare(J.name)})}function fj($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function $j($,f){if($.userInstructionService)return await f($.userInstructionService);let J=fj($);if(!J)return await f(void 0);let W=$.cwd?.trim()||J,Z=Zf({skills:{workspacePath:J,includePluginSkills:!0,cwd:W},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await f(Z)}finally{Z.stop()}}function gF($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let W=J.find((Z)=>Z.id===f.id);if(W)return W}for(let W of J)if(W.filePath===f.path||W.item.name===f.name||W.id===f.name)return W;return}class Hf{async list($={}){return await $j($,async(f)=>{let J=fj($),W=[],Z=[],Q=[],j=[],H=[];if(f){for(let A of f.listRecords("workflow")){let Y=A.item;W.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"workflow",source:FJ(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of f.listRecords("rule")){let Y=A.item;Z.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"rule",source:FJ(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of f.listRecords("skill")){let Y=A.item;Q.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"skill",source:FJ(A.filePath,J),description:Y.description,toggleable:!0})}}if(J)try{for(let A of await k5({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${A.pluginName}:${A.name}:${A.path}`,name:A.name,path:A.path,enabled:A.enabled,kind:"tool",source:A.source,description:A.description,toggleable:!0})}catch{}let X=h0();if(P1({filePath:X}))try{for(let A of C$({filePath:X}))H.push({id:A.name,name:A.name,path:X,enabled:A.disabled!==!0,kind:"mcp",source:FJ(X,J),description:A.transport.type,toggleable:!0})}catch{}return{workflows:W2(W.filter((A)=>UJ(A.path))),rules:W2(Z.filter((A)=>UJ(A.path))),skills:W2(Q.filter((A)=>UJ(A.path))),tools:W2(j),mcp:W2(H.filter((A)=>UJ(A.path)))}})}async toggle($){if($.type==="skills")return await $j($,async(f)=>{let J=gF(f,$),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${$.id??$.name??e3($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=$.enabled??(Z!==void 0?!Z:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??e3($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await h3({filePath:W,enabled:Q}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)M6($.name);else FQ($.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()||h0(),W=$.enabled;if(W===void 0){let Z=C$({filePath:J}).find((Q)=>Q.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);W=Z.disabled===!0}return of({filePath:J,name:f,disabled:!W}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function Z2(){return new Hf}function Jj($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await Z2().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await Z2().toggle(f)}}}function Wj($){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 F0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let W=f&&Object.keys(f).length>0;if(!W&&!J)return;return{...W?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}var Q2="session_not_found";class U1 extends Error{sessionId;code="session_not_found";constructor($,f){super(f??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function F1($){return $ instanceof U1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function I5($){let{hooks:f,logger:J,telemetry:W,extensionContext:Z,extraTools:Q,extensions:j,onTeamEvent:H,onConsecutiveMistakeLimitReached:X,checkpoint:A,compaction:Y,...V}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(W)B.telemetry=W;if(Z)B.extensionContext=Z;if(Q)B.extraTools=Q;if(j)B.extensions=j;if(H)B.onTeamEvent=H;if(X)B.onConsecutiveMistakeLimitReached=X;if(A?.createCheckpoint)B.checkpoint=A;if(Y?.compact)B.compaction=Y;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...A?{checkpoint:{enabled:A.enabled}}:{},...Y?{compaction:{enabled:Y.enabled,strategy:Y.strategy,thresholdRatio:Y.thresholdRatio,reserveTokens:Y.reserveTokens,preserveRecentTokens:Y.preserveRecentTokens,maxInputTokens:Y.maxInputTokens,summarizer:Y.summarizer}}:{}},...K?{localRuntime:K}:{}}}function Zj($){let f=$.config;return"providerId"in f?{...$,config:{...f,...vF($.localRuntime)},localRuntime:$.localRuntime}:$}function x5($,f={}){let J=I5($.config),W=F0(f.defaultCapabilities,$.capabilities),Z=uF(J.localRuntime,$.localRuntime),Q=f.withExtensionContext?.(Z?.extensionContext);if(Q)Z={...Z??{},extensionContext:Q};return{...$,...J,...Z?{localRuntime:Z}:{},...W?{capabilities:W}:{}}}function vF($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:W,onTeamRestored:Z,...Q}=$;return Q}function uF(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}B0();function Qj($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:k.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??U0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function j2($){return!!$&&typeof $==="object"&&!Array.isArray($)}function m5($){let f=$?.trim();return f?f:void 0}function cF($,f){let J=$?.trim();if(!J)return f;let W=Date.parse(J);if(!Number.isFinite(W))return f;return new Date(W).toISOString()}function jj($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function Hj($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function dF($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function lF($,f){let J=$.eventId.trim(),W=$.eventType.trim(),Z=$.source.trim(),Q=m5($.subject),j=m5($.dedupeKey)??`${W}:${Z}:${Q??J}`;return{eventId:J,eventType:W,source:Z,subject:Q,occurredAt:cF($.occurredAt,f),workspaceRoot:m5($.workspaceRoot),payload:j2($.payload)?$.payload:void 0,attributes:j2($.attributes)?$.attributes:void 0,dedupeKey:j}}function g5($,f){if(!f)return;let J=f.split("."),W=$;for(let Z of J){if(!j2(W))return;W=W[Z]}return W}function pF($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},W=g5(J,f);if(W!==void 0)return W;if($.attributes){let Z=g5($.attributes,f);if(Z!==void 0)return Z}if($.payload)return g5($.payload,f);return}function RJ($,f){if(Array.isArray(f))return f.some((J)=>RJ($,J));if(Array.isArray($))return $.some((J)=>RJ(J,f));if(j2(f)){if(!j2($))return!1;return Object.entries(f).every(([J,W])=>RJ($[J],W))}return Object.is($,f)}function rF($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,W])=>RJ(pF($,J),W))}class v5{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=lF($,f),W=this.store.insertEventLog(J,{receivedAtIso:f});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),Q=[],j=[],H=[];for(let Y of Z){if(!rF(J,Y.filters)){Q.push({specId:Y.specId,externalId:Y.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(Y);let V=this.materializeForSpec(Y,J,W.record.receivedAt);if(V.run)H.push(V.run);else Q.push({specId:Y.specId,externalId:Y.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let X=j.length===0?"unmatched":H.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:X,matchedSpecCount:j.length,queuedRunCount:H.length,suppressedCount:Q.filter((Y)=>Y.reason!=="filter_mismatch").length});let A=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:X,matchedSpecCount:j.length,queuedRunCount:H.length}),{event:A??W.record,duplicate:!1,matchedSpecs:j,queuedRuns:H,suppressions:Q}}catch(Z){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let W=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let X=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:W});if(X){let A=dF(X.scheduledFor,jj(J,Z)),Y=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:f.eventId,scheduledFor:A});if(Y)return{run:Y,reason:"dedupe_window"}}}let Q=$.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:W,sinceIso:Hj(J,Q)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:Hj(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?jj(J,Z):J}),reason:"dedupe_window"}}}class H2{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of f)if(this.materializeOneOff(W))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)try{if(this.materializeSchedule(W))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as JR}from"node:path";import{buildClineSystemPrompt as WR}from"@cline/shared";import{nowIso as Vj}from"@cline/shared/db";import{basename as iF,resolve as nF}from"node:path";import{performance as Xj}from"node:perf_hooks";import{processWorkspaceInfo as Aj}from"@cline/shared";import aF from"simple-git";function R1($){return nF($)}async function LJ($){return(await u5($)).info}function DJ($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function u5($){let f=R1($),J={rootPath:f,hint:iF(f)},W;try{let Z=aF({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let H=j.map((X)=>{let A=X.refs.fetch||X.refs.push;return`${X.name}: ${A}`});J.associatedRemoteUrls=H}}catch(j){W??=DJ(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){W??=DJ(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){W??=DJ(j)}return{info:J,vcsType:"git",error:W}}catch(Z){return{info:J,vcsType:"none",error:DJ(Z)}}}async function c5($){let f=await LJ($);return Aj(f)}async function Yj($){let f=Xj.now(),J=await u5($),W=Xj.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:Aj(Z),durationMs:W,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as tF,writeFileSync as sF}from"node:fs";import{join as oF}from"node:path";import{resolveCronReportsDir as eF}from"@cline/shared/storage";function E$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function D1($,f){if(f===void 0||f===null)return;return`${$}: ${E$(f)}`}function $R($,f,J){let W=[`runId: ${E$($.runId)}`,`specId: ${E$(f.specId)}`,`externalId: ${E$(f.externalId)}`,`title: ${E$(f.title)}`,`triggerKind: ${E$($.triggerKind)}`,`status: ${E$($.status)}`,`sourcePath: ${E$(f.sourcePath)}`],Z=[D1("sessionId",$.sessionId),D1("startedAt",$.startedAt),D1("completedAt",$.completedAt),D1("triggerEventId",$.triggerEventId),D1("triggerEventType",J?.eventType),D1("triggerEventSource",J?.source),D1("triggerEventSubject",J?.subject)];for(let Q of Z)if(Q)W.push(Q);return`---
165
- ${W.join(`
163
+ `);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,H=j+W;if(this.buffer.length<H)break;$.push(this.buffer.slice(j,H)),this.buffer=this.buffer.slice(H)}return $}}class i5{buffer="";decoder=new Bj("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`
164
+ `);if(J<0)break;let Q=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),Q.length>0)$.push(Q)}return $}}class Kj{registration;process;nextRequestId=1;pending=new Map;framedParser=new r5;newlineParser=new i5;stderrBuffer="";connected=!1;protocolMode="newline";constructor(f){this.registration=f}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 f=["newline","framed"],$;for(let J of f){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:sU,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},eU),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){$=Q instanceof Error?Q:Error(String(Q))}}throw $??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let f=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!f)return;f.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter(($)=>typeof $?.name==="string"&&typeof $.inputSchema==="object"&&$.inputSchema!==null).map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}async callTool(f){return this.request("tools/call",{name:f.name,arguments:f.arguments??{}})}spawnProcess(f){let $=this.registration.transport;if($.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${$.type}`);this.framedParser=new r5,this.newlineParser=new i5,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=aU($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.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: ${DJ(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(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){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($){this.handleProtocolFailure($)}}handleProtocolFailure(f){let $=this.process;if(!$)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}": ${DJ(f)}.${J}`)),$.kill()}async request(f,$,J=oU){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:$}:{}},j=new Promise((H,X)=>{let A=setTimeout(()=>{this.pending.delete(Z),X(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(Z,{resolve:H,reject:X,timeout:A})});try{Q.stdin.write(this.protocolMode==="framed"?Yj(W):Vj(W))}catch(H){let X=this.pending.get(Z);if(X)clearTimeout(X.timeout),this.pending.delete(Z);throw H}return j}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?Yj(Q):Vj(Q))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}class Pj{registration;options;client;authContext;constructor(f,$){this.registration=f;this.options=$}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 f=RJ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??Aj});this.authContext=f;try{let $=new tU({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=UJ({registration:this.registration,oauthProvider:f.provider,fetch:this.options.fetch});await $.connect(J),await f.clearError(),this.client=$}catch($){let J=$ instanceof Xj?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):DJ($);throw await f.markError(J),Error(J)}}async disconnect(){let f=this.client;this.client=void 0,await f?.close()}async listTools(){let f=await this.ensureConnectedClient();try{return(await f.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch($){return await this.handleOperationError($)}}async callTool(f){let $=await this.ensureConnectedClient();try{return await $.callTool({name:f.name,arguments:f.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(f){let $=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!f)return`${$} Run authorizeMcpServerOAuth for this server.`;return`${$} Run authorizeMcpServerOAuth for this server and complete this URL: ${f}`}async handleOperationError(f){let $=this.authContext??RJ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??Aj}),J=f instanceof Xj?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):DJ(f);throw await $.markError(J),Error(J)}}function LJ(f={}){return($)=>$.transport.type==="stdio"?new Kj($):new Pj($,f)}FJ();function k0(){return Date.now()}function fR(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class Y2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(f){this.clientFactory=f.clientFactory,this.toolsCacheTtlMs=f.toolsCacheTtlMs??5000}async registerServer(f){await this.runExclusive(f.name,async()=>{let $=this.servers.get(f.name);if(!$){this.servers.set(f.name,{registration:{...f},status:"disconnected",updatedAt:k0()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=k0(),J)await this.disconnectState($),$.client=void 0,$.toolCache=void 0,$.toolCacheUpdatedAt=void 0})}async unregisterServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($),this.servers.delete(f)})}async connectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.connectState($)})}async disconnectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($)})}async setServerDisabled(f,$){await this.runExclusive(f,async()=>{let J=this.requireServer(f);if(J.registration={...J.registration,disabled:$},J.updatedAt=k0(),$)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map((f)=>({name:f.registration.name,status:f.status,disabled:f.registration.disabled===!0,lastError:f.lastError,toolCount:f.toolCache?.length??0,updatedAt:f.updatedAt,metadata:f.registration.metadata})).sort((f,$)=>f.name.localeCompare($.name))}async listTools(f){let $=this.requireServer(f),J=$.toolCacheUpdatedAt??0;if($.toolCache&&k0()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),Q=await(await this.ensureConnectedClient($)).listTools(),Z=fR(Q);return $.toolCache=Z,$.toolCacheUpdatedAt=k0(),$.updatedAt=k0(),Z})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=k0(),J.callTool({name:f.toolName,arguments:f.arguments,context:f.context})})}async dispose(){let f=[...this.servers.keys()];for(let $ of f)await this.unregisterServer($)}async ensureConnectedClient(f){if(await this.connectState(f),!f.client)throw Error(`MCP server "${f.registration.name}" does not have an initialized client.`);return f.client}async connectState(f){if(f.registration.disabled)throw Error(`MCP server "${f.registration.name}" is disabled and cannot be connected.`);if(f.status==="connected"&&f.client)return;f.status="connecting",f.updatedAt=k0();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=k0()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=k0(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=k0();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=k0()}}requireServer(f){let $=this.servers.get(f);if(!$)throw Error(`Unknown MCP server: ${f}`);return $}async runExclusive(f,$){let J=this.operationLocks.get(f)??Promise.resolve(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set(f,W),await J.catch(()=>{return});try{return await $()}finally{if(Q?.(),this.operationLocks.get(f)===W)this.operationLocks.delete(f)}}}import{createHash as $R}from"node:crypto";var Gj=128,JR=/[^a-zA-Z0-9_-]+/g,Fj=8,QR=1,ZR="mcp_tool";function WR(f){return $R("sha1").update(f).digest("hex").slice(0,Fj)}function jR(f){return f.replace(JR,"_")}var OJ=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,Q=jR(J);if(Q===J&&J.length<=Gj)return J;let Z=WR(J),W=Gj-QR-Fj;return`${Q.slice(0,W)||ZR}_${Z}`};function n5(f){return{[(f.nameTransform??OJ)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function Uj(f){let $={};for(let J of f.toolNames)Object.assign($,n5({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as HR}from"@cline/shared";function XR(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function _J(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??OJ;return $.map((Q)=>{let Z=J({serverName:f.serverName,toolName:Q.name});return HR({name:Z,description:XR(f.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(W,j)=>f.provider.callTool({serverName:f.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}t0();import{stat as AR}from"node:fs/promises";t0();var YR=32,P1=new Map;function VR(f,$){if(!P1.has(f)&&P1.size>=YR){let J=P1.keys().next().value;if(J)P1.delete(J)}P1.set(f,$)}async function BR(f){let $=await Promise.all(f.pluginPaths.map(async(J)=>{try{let Q=await AR(J);return`${J}:${Q.mtimeMs}:${Q.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:f.workspacePath,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId,pathStats:$})}function Rj(f,$){return f.map((J)=>({...J,enabled:!$.has(J.name)}))}function KR(f){return f.sort(($,J)=>{let Q=$.name.localeCompare(J.name);if(Q!==0)return Q;return $.path.localeCompare(J.path)})}function PR(f,$){if(!f.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(Q,{workspaceInfo:$}),J}async function Dj(f){let $=u1({workspacePath:f.workspacePath,cwd:f.cwd}),J=Yf(f.disabledToolNames);if($.length===0)return{tools:[],failures:[],warnings:[]};let Q=await BR({pluginPaths:$,workspacePath:f.workspacePath,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId}),Z=P1.get(Q);if(Z)return{tools:Rj(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let W=[],j=[],H=[],X;try{X=await E8({pluginPaths:$,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId,workspaceInfo:{rootPath:f.workspacePath}}),j=[...X.failures],H=[...X.warnings];for(let V of X.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of PR(V,{rootPath:f.workspacePath}))W.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=$.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await X?.shutdown().catch(()=>{})}let A=KR(W);return VR(Q,{tools:A,failures:j,warnings:H}),{tools:Rj(A,J),failures:j,warnings:H}}async function a5(f){return(await Dj(f)).tools}function zJ(f,$){if(!$)return"global";let J=FR($,f);return!J.startsWith("..")&&!GR(J)?"workspace":"global"}function V2(f){return[...f].sort(($,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($.source!==J.source)return Q($.source)-Q(J.source);return $.name.localeCompare(J.name)})}function _j(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function Oj(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=_j(f);if(!J)return await $(void 0);let Q=f.cwd?.trim()||J,Z=B1({skills:{workspacePath:J,includePluginSkills:!0,cwd:Q},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await $(Z)}finally{Z.stop()}}function UR(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let Q=J.find((Z)=>Z.id===$.id);if(Q)return Q}for(let Q of J)if(Q.filePath===$.path||Q.item.name===$.name||Q.id===$.name)return Q;return}class G1{async list(f={}){return await Oj(f,async($)=>{let J=_j(f),Q=[],Z=[],W=[],j=[],H=[];if($){for(let A of $.listRecords("workflow")){let Y=A.item;Q.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"workflow",source:zJ(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of $.listRecords("rule")){let Y=A.item;Z.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"rule",source:zJ(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of $.listRecords("skill")){let Y=A.item;W.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"skill",source:zJ(A.filePath,J),description:Y.description,toggleable:!0})}}if(J)try{for(let A of await a5({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))j.push({id:`${A.pluginName}:${A.name}:${A.path}`,name:A.name,path:A.path,enabled:A.enabled,kind:"tool",source:A.source,description:A.description,toggleable:!0})}catch{}let X=b0();if(D$({filePath:X}))try{for(let A of xf({filePath:X}))H.push({id:A.name,name:A.name,path:X,enabled:A.disabled!==!0,kind:"mcp",source:zJ(X,J),description:A.transport.type,toggleable:!0})}catch{}return{workflows:V2(Q.filter((A)=>TJ(A.path))),rules:V2(Z.filter((A)=>TJ(A.path))),skills:V2(W.filter((A)=>TJ(A.path))),tools:V2(j),mcp:V2(H.filter((A)=>TJ(A.path)))}})}async toggle(f){if(f.type==="skills")return await Oj(f,async($)=>{let J=UR($,f),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${f.id??f.name??Lj(f.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=f.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??Lj(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await o3({filePath:Q,enabled:W}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)m6(f.name);else gW(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}if(f.type==="mcp"){let $=f.name?.trim()||f.id?.trim();if(!$)throw Error("MCP server settings toggle requires a server name.");let J=f.path?.trim()||b0(),Q=f.enabled;if(Q===void 0){let Z=xf({filePath:J}).find((W)=>W.name===$);if(!Z)throw Error(`Unknown MCP server: ${$}`);Q=Z.disabled===!0}return j2({filePath:J,name:$,disabled:!Q}),{snapshot:await this.list(f),changedTypes:["mcp"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function B2(){return new G1}function Tj(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await B2().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await B2().toggle($)}}}function zj(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}function R0(...f){let $,J;for(let Z of f){if(!Z)continue;if(Z.toolExecutors)$={...$??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let Q=$&&Object.keys($).length>0;if(!Q&&!J)return;return{...Q?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}var K2="session_not_found";class L$ extends Error{sessionId;code="session_not_found";constructor(f,$){super($??(f?`session not found: ${f}`:"session not found"));this.sessionId=f;this.name="SessionNotFoundError"}}function O$(f){return f instanceof L$||typeof f==="object"&&f!==null&&"code"in f&&f.code==="session_not_found"}function t5(f){let{hooks:$,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:H,onConsecutiveMistakeLimitReached:X,checkpoint:A,compaction:Y,...V}=f,B={};if($)B.hooks=$;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(H)B.onTeamEvent=H;if(X)B.onConsecutiveMistakeLimitReached=X;if(A?.createCheckpoint)B.checkpoint=A;if(Y?.compact)B.compaction=Y;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...A?{checkpoint:{enabled:A.enabled}}:{},...Y?{compaction:{enabled:Y.enabled,strategy:Y.strategy,thresholdRatio:Y.thresholdRatio,reserveTokens:Y.reserveTokens,preserveRecentTokens:Y.preserveRecentTokens,maxInputTokens:Y.maxInputTokens,summarizer:Y.summarizer}}:{}},...K?{localRuntime:K}:{}}}function Mj(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...RR(f.localRuntime)},localRuntime:f.localRuntime}:f}function s5(f,$={}){let J=t5(f.config),Q=R0($.defaultCapabilities,f.capabilities),Z=DR(J.localRuntime,f.localRuntime),W=$.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...f,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function RR(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=f;return W}function DR(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}V0();function Nj(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:x.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??U0.CORE,providerId:f.input.config.providerId,modelId:f.input.config.modelId,enableTools:f.input.config.enableTools,enableSpawnAgent:f.input.config.enableSpawnAgent,enableAgentTeams:f.input.config.enableAgentTeams,clientName:f.clientName,runtimeAddress:f.runtimeAddress}})}function P2(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function o5(f){let $=f?.trim();return $?$:void 0}function LR(f,$){let J=f?.trim();if(!J)return $;let Q=Date.parse(J);if(!Number.isFinite(Q))return $;return new Date(Q).toISOString()}function qj(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function yj(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function OR(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function _R(f,$){let J=f.eventId.trim(),Q=f.eventType.trim(),Z=f.source.trim(),W=o5(f.subject),j=o5(f.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:LR(f.occurredAt,$),workspaceRoot:o5(f.workspaceRoot),payload:P2(f.payload)?f.payload:void 0,attributes:P2(f.attributes)?f.attributes:void 0,dedupeKey:j}}function e5(f,$){if(!$)return;let J=$.split("."),Q=f;for(let Z of J){if(!P2(Q))return;Q=Q[Z]}return Q}function TR(f,$){if(f.attributes&&Object.hasOwn(f.attributes,$))return f.attributes[$];if(f.payload&&Object.hasOwn(f.payload,$))return f.payload[$];let J={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},Q=e5(J,$);if(Q!==void 0)return Q;if(f.attributes){let Z=e5(f.attributes,$);if(Z!==void 0)return Z}if(f.payload)return e5(f.payload,$);return}function MJ(f,$){if(Array.isArray($))return $.some((J)=>MJ(f,J));if(Array.isArray(f))return f.some((J)=>MJ(J,$));if(P2($)){if(!P2(f))return!1;return Object.entries($).every(([J,Q])=>MJ(f[J],Q))}return Object.is(f,$)}function zR(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,Q])=>MJ(TR(f,J),Q))}class f9{store;nowFn;logger;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now()),this.logger=f.logger}ingestEvent(f){let $=new Date(this.nowFn()).toISOString(),J=_R(f,$),Q=this.store.insertEventLog(J,{receivedAtIso:$});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=[],H=[];for(let Y of Z){if(!zR(J,Y.filters)){W.push({specId:Y.specId,externalId:Y.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(Y);let V=this.materializeForSpec(Y,J,Q.record.receivedAt);if(V.run)H.push(V.run);else W.push({specId:Y.specId,externalId:Y.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let X=j.length===0?"unmatched":H.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:X,matchedSpecCount:j.length,queuedRunCount:H.length,suppressedCount:W.filter((Y)=>Y.reason!=="filter_mismatch").length});let A=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:X,matchedSpecCount:j.length,queuedRunCount:H.length}),{event:A??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:H,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=$.dedupeKey??$.eventId,Z=f.debounceSeconds??0;if(Z>0){let X=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:Q});if(X){let A=OR(X.scheduledFor,qj(J,Z)),Y=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:$.eventId,scheduledFor:A});if(Y)return{run:Y,reason:"dedupe_window"}}}let W=f.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:Q,sinceIso:yj(J,W)}))return{reason:"dedupe_window"};let j=f.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:yj(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:Z>0?qj(J,Z):J}),reason:"dedupe_window"}}}class G2{store;nowFn;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now())}materializeAll(){let f={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of $)if(this.materializeOneOff(Q))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of J)try{if(this.materializeSchedule(Q))f.scheduleQueued+=1}catch{}return f}materializeOneOff(f){if(f.triggerKind!=="one_off")return!1;if(!f.enabled||f.removed)return!1;if(this.store.hasOneOffRunForRevision(f.specId,f.revision))return!1;return this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(f){if(f.triggerKind!=="schedule")return!1;if(!f.enabled||f.removed)return!1;if(!f.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:f.specId,nowMs:this.nowFn()}).queued}}import{basename as bR}from"node:path";import{buildClineSystemPrompt as kR}from"@cline/shared";import{nowIso as Ej}from"@cline/shared/db";import{basename as MR,resolve as NR}from"node:path";import{performance as wj}from"node:perf_hooks";import{processWorkspaceInfo as Cj}from"@cline/shared";import qR from"simple-git";function _$(f){return NR(f)}async function qJ(f){return(await $9(f)).info}function NJ(f){if(f instanceof Error)return{errorType:f.name?.trim()||f.constructor.name||"Error",message:f.message};return{errorType:"Error",message:String(f)}}async function $9(f){let $=_$(f),J={rootPath:$,hint:MR($)},Q;try{let Z=qR({baseDir:$});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let H=j.map((X)=>{let A=X.refs.fetch||X.refs.push;return`${X.name}: ${A}`});J.associatedRemoteUrls=H}}catch(j){Q??=NJ(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){Q??=NJ(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){Q??=NJ(j)}return{info:J,vcsType:"git",error:Q}}catch(Z){return{info:J,vcsType:"none",error:NJ(Z)}}}async function J9(f){let $=await qJ(f);return Cj($)}async function Sj(f){let $=wj.now(),J=await $9(f),Q=wj.now()-$,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:Cj(Z),durationMs:Q,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as yR,writeFileSync as wR}from"node:fs";import{join as CR}from"node:path";import{resolveCronReportsDir as SR}from"@cline/shared/storage";function gf(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function T$(f,$){if($===void 0||$===null)return;return`${f}: ${gf($)}`}function ER(f,$,J){let Q=[`runId: ${gf(f.runId)}`,`specId: ${gf($.specId)}`,`externalId: ${gf($.externalId)}`,`title: ${gf($.title)}`,`triggerKind: ${gf(f.triggerKind)}`,`status: ${gf(f.status)}`,`sourcePath: ${gf($.sourcePath)}`],Z=[T$("sessionId",f.sessionId),T$("startedAt",f.startedAt),T$("completedAt",f.completedAt),T$("triggerEventId",f.triggerEventId),T$("triggerEventType",J?.eventType),T$("triggerEventSource",J?.source),T$("triggerEventSubject",J?.subject)];for(let W of Z)if(W)Q.push(W);return`---
165
+ ${Q.join(`
166
166
  `)}
167
167
  ---
168
- `}function fR($){let f=[];if($.triggerEvent){let J=$.triggerEvent,W=[`- 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 hR(f){let $=[];if(f.triggerEvent){let J=f.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);$.push(`## Trigger Event
169
169
 
170
- ${W.join(`
170
+ ${Q.join(`
171
171
  `)}
172
- `)}if($.error)f.push(`## Error
172
+ `)}if(f.error)$.push(`## Error
173
173
 
174
- ${$.error}
175
- `);if($.finalText&&$.finalText.trim().length>0)f.push(`## Summary
174
+ ${f.error}
175
+ `);if(f.finalText&&f.finalText.trim().length>0)$.push(`## Summary
176
176
 
177
- ${$.finalText.trim()}
178
- `);if($.usage){let J=$.usage,W=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",$.durationMs!==void 0?`- durationMs: ${$.durationMs}`:""].filter((Z)=>Z.length>0);if(W.length>0)f.push(`## Usage
177
+ ${f.finalText.trim()}
178
+ `);if(f.usage){let J=f.usage,Q=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",f.durationMs!==void 0?`- durationMs: ${f.durationMs}`:""].filter((Z)=>Z.length>0);if(Q.length>0)$.push(`## Usage
179
179
 
180
- ${W.join(`
180
+ ${Q.join(`
181
181
  `)}
182
- `)}if($.toolCalls&&$.toolCalls.length>0){let J=$.toolCalls.map((W)=>{let Z=[`- ${W.name}`];if(W.durationMs!==void 0)Z.push(`(${W.durationMs}ms)`);if(W.error)Z.push(`error: ${W.error}`);return Z.join(" ")});f.push(`## Tool Calls
182
+ `)}if(f.toolCalls&&f.toolCalls.length>0){let J=f.toolCalls.map((Q)=>{let Z=[`- ${Q.name}`];if(Q.durationMs!==void 0)Z.push(`(${Q.durationMs}ms)`);if(Q.error)Z.push(`error: ${Q.error}`);return Z.join(" ")});$.push(`## Tool Calls
183
183
 
184
184
  ${J.join(`
185
185
  `)}
186
- `)}return f.join(`
187
- `)}function d5($){let f=eF($.specs);tF(f,{recursive:!0});let J=oF(f,`${$.run.runId}.md`),W=`${$R($.run,$.spec,$.data.triggerEvent)}
188
- ${fR($.data)}`;return sF(J,W,"utf8"),J}class l5{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=W)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var ZR=15000,QR=90,Bj=["rules","skills","plugins"];function jR($,f){return new Set($.extensions??Bj).has(f)}function HR($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of $.tools)J[W]={enabled:!0,autoApprove:!0};if(f==="yolo")J[j0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function XR($){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 p5 extends Error{constructor($){super($);this.name="TimeoutError"}}async function AR($,f){if(f<=0)return $;let J,W=new Promise((Z,Q)=>{J=setTimeout(()=>{Q(new p5("cron run timed out"))},f)});try{return await Promise.race([$,W])}finally{if(J)clearTimeout(J)}}class X2{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 l5($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??QR)*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??ZR);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:W.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:Vj(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,W)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let Q=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,H,X=Date.now(),A;if(J.timeoutSeconds&&J.timeoutSeconds>0)A=X+J.timeoutSeconds*1000;try{H=this.startClaimLeaseHeartbeat($);let Y=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(Y)).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:Y,prompt:this.buildPrompt(J,Q)},K=this.options.runtimeHandlers.sendSession(j,B),G=A?Math.max(1,A-Date.now()):0,P=(await AR(K,G)).result,U=Date.now(),F=d5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:P.text,usage:P.usage,toolCalls:P.toolCalls,durationMs:U-X,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,Vj())}catch(Y){let V=Y instanceof p5;if(j&&V)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=Y instanceof Error?Y.message:String(Y),K=Date.now(),G=d5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-X,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:B,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(H?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let W=this.store.getRun(J);if(!W)return;let Z=W.status==="done"?"success":W.status==="cancelled"?"aborted":W.status==="running"?"running":W.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.externalId,executionId:W.runId,sessionId:W.sessionId,triggeredAt:new Date(W.scheduledFor??W.createdAt).getTime(),startedAt:W.startedAt?new Date(W.startedAt).getTime():void 0,endedAt:W.completedAt?new Date(W.completedAt).getTime():void 0,status:Z,errorMessage:W.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let W={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
186
+ `)}return $.join(`
187
+ `)}function Q9(f){let $=SR(f.specs);yR($,{recursive:!0});let J=CR($,`${f.run.runId}.md`),Q=`${ER(f.run,f.spec,f.data.triggerEvent)}
188
+ ${hR(f.data)}`;return wR(J,Q,"utf8"),J}class Z9{globalMaxConcurrency;activeExecutions=new Map;constructor(f){this.globalMaxConcurrency=Math.max(1,Math.floor(f))}acquire(f,$,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get(f)??new Set;if(Z.size>=Q)return!1;return Z.add($),this.activeExecutions.set(f,Z),!0}release(f,$){let J=this.activeExecutions.get(f);if(!J)return;if(J.delete($),J.size===0)this.activeExecutions.delete(f)}getGlobalActiveCount(){let f=0;for(let $ of this.activeExecutions.values())f+=$.size;return f}}var IR=15000,xR=90,hj=["rules","skills","plugins"];function gR(f,$){return new Set(f.extensions??hj).has($)}function mR(f,$){if(f.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let Q of f.tools)J[Q]={enabled:!0,autoApprove:!0};if($==="yolo")J[K0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function vR(f){let $=f?.trim();if(!$)return;return["# Notes Directory",`Use ${$} 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 W9 extends Error{constructor(f){super(f);this.name="TimeoutError"}}async function cR(f,$){if($<=0)return f;let J,Q=new Promise((Z,W)=>{J=setTimeout(()=>{W(new W9("cron run timed out"))},$)});try{return await Promise.race([f,Q])}finally{if(J)clearTimeout(J)}}class F2{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor(f){this.store=f.store,this.materializer=f.materializer,this.options=f,this.limiter=new Z9(f.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,(f.claimLeaseSeconds??xR)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let f=Math.max(2000,this.options.pollIntervalMs??IR);await this.tick(),this.timer=setInterval(()=>void this.tick(),f)}async stop(){let f=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!f)return;let $=[...this.activeRuns.entries()];await Promise.all($.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 f=this.store.claimDueRuns({nowIso:Ej(),leaseMs:this.claimLeaseMs});await Promise.allSettled(f.map(($)=>this.executeClaim($)))}catch(f){let $=this.options.logger;if($)if($.error)$.error("cron.runner.tick.failed",{error:f});else $.log("cron.runner.tick.failed",{error:f})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([f,$])=>{let J=this.store.getRun(f);return J?[{...J,...$}]:[]})}async executeClaim(f){let $=f.run,J=this.store.getSpec($.specId);if(!J){this.store.completeRun($.runId,{status:"failed",error:"spec not found",claimToken:f.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun($.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:f.claimToken});return}let Q=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,$.runId,Q)){this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,$.runId),this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set($.runId,{claimToken:f.claimToken});let W=$.triggerEventId?this.store.getEventLog($.triggerEventId):void 0,j,H,X=Date.now(),A;if(J.timeoutSeconds&&J.timeoutSeconds>0)A=X+J.timeoutSeconds*1000;try{H=this.startClaimLeaseHeartbeat(f);let Y=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(Y)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set($.runId,{claimToken:f.claimToken,sessionId:j}),this.store.attachSessionIdToRun($.runId,j);let B={config:Y,prompt:this.buildPrompt(J,W)},K=this.options.runtimeHandlers.sendSession(j,B),P=A?Math.max(1,A-Date.now()):0,G=(await cR(K,P)).result,F=Date.now(),U=Q9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:j,status:"done"},spec:J,data:{finalText:G.text,usage:G.usage,toolCalls:G.toolCalls,durationMs:F-X,triggerEvent:W}});this.store.completeRun($.runId,{status:"done",sessionId:j,reportPath:U,claimToken:f.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,$.runId),this.store.updateSpecLastRunAt(J.specId,Ej())}catch(Y){let V=Y instanceof W9;if(j&&V)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=Y instanceof Error?Y.message:String(Y),K=Date.now(),P=Q9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-X,triggerEvent:W}});this.store.completeRun($.runId,{status:"failed",sessionId:j,reportPath:P,error:B,claimToken:f.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,$.runId)}finally{if(H?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete($.runId),this.limiter.release(J.specId,$.runId)}}publishScheduleExecutionEvent(f,$,J){if($.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(f,{scheduleId:$.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=f.prompt??"";if(!$)return J;let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload};return`${J}
190
190
 
191
191
  Trigger event:
192
- ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,W))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,W){let Z=XR($.notesDirectory),Q=k8(void 0,Z),j=await c5(f),H=WR({ide:"Cline Cron",workspaceRoot:f,workspaceName:JR(f),metadata:j,rules:$.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?k8(H,Q)??H:H}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),W=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,Q=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:Q,provider:J,model:W,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:HR($,j),configExtensions:Bj.filter((H)=>jR($,H))}}}import{existsSync as CR,readdirSync as ER,readFileSync as bR,statSync as kR}from"node:fs";import{relative as IR}from"node:path";import{resolveCronSpecsDir as xR}from"@cline/shared/storage";function A2($,f,J,W){let Z=new Set;function Q(j){let H=j.toLowerCase();if(W){let A=W.indexOf(H);if(A!==-1)return A+f}let X=Number(j);if(!Number.isInteger(X)||X<f||X>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return X}for(let j of $.split(",")){if(j==="*"){for(let A=f;A<=J;A+=1)Z.add(A);continue}let H=j.indexOf("/");if(H!==-1){let A=j.slice(0,H),Y=Number(j.slice(H+1));if(!Number.isInteger(Y)||Y<1)throw Error(`Invalid step "${j.slice(H+1)}"`);let V=f,B=J;if(A!=="*"){let K=A.indexOf("-");if(K!==-1)V=Q(A.slice(0,K)),B=Q(A.slice(K+1));else V=Q(A)}if(V>B)throw Error(`Invalid cron range "${A}"`);for(let K=V;K<=B;K+=Y)Z.add(K);continue}let X=j.indexOf("-");if(X!==-1){let A=Q(j.slice(0,X)),Y=Q(j.slice(X+1));if(A>Y)throw Error(`Invalid cron range "${j}"`);for(let V=A;V<=Y;V+=1)Z.add(V);continue}Z.add(Q(j))}return[...Z].sort((j,H)=>j-H)}var YR=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Gj=["sun","mon","tue","wed","thu","fri","sat"];function Y2($,f,J){let W=$[f];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return W}function r5($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function i5($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:A2(Y2(f,0,$),0,59),hours:A2(Y2(f,1,$),0,23),daysOfMonth:A2(Y2(f,2,$),1,31),months:A2(Y2(f,3,$),1,12,YR),daysOfWeek:A2(Y2(f,4,$),0,6,Gj)}}function n5($){i5($)}function Pj($,f,J=Date.now()){L1($,J,f)}var Kj=new Map,VR=new Map(Gj.map(($,f)=>[$,f]));function Uj($){let f=$?.trim();return f?f:void 0}function Fj($){let f=Kj.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 Kj.set($,J),J}function BR($){let f=Uj($);if(!f)return;Fj(f).format(new Date)}function KR($,f){let J=Fj(f).formatToParts(new Date($)),W=new Map(J.map((j)=>[j.type,j.value])),Z=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=VR.get(Z);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function GR($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function PR($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function UR($,f,J){let W=i5($),Z=new Date(f);Z.setSeconds(0,0);let Q=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let H=j.getTime();while(Q<=H){if(PR(W,KR(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function L1($,f,J){let W=Uj(J);if(W)return BR(W),UR($,f,W);let Z=i5($),Q=new Date(f);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(Q<=j){let{month:H,dayOfMonth:X,dayOfWeek:A,hour:Y,minute:V}=GR(Q.getTime());if(!Z.months.includes(H)){let B=Z.months.find((G)=>G>H)??r5(Z.months,"months"),K=B<=H?1:0;Q=new Date(Q.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(X)||!Z.daysOfWeek.includes(A)){Q=new Date(Q.getFullYear(),Q.getMonth(),X+1,0,0,0,0);continue}if(!Z.hours.includes(Y)){let B=Z.hours.find((G)=>G>Y)??r5(Z.hours,"hours"),K=B<=Y?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(V)){let B=Z.minutes.find((G)=>G>V)??r5(Z.minutes,"minutes"),K=B<=V?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+K,B,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as FR}from"node:crypto";import RR from"yaml";function DR($){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 LR($){let f=$.replace(/\r\n/g,`
193
- `);if(!f.startsWith(`---
194
- `))return{frontmatter:void 0,body:$};let J=f.slice(4),W=J.indexOf(`
195
- ---`);if(W===-1)return{frontmatter:void 0,body:$};let Z=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
196
- `))Q=Q.slice(1);return{frontmatter:Z,body:Q}}function E0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function OR($){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 s5($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function zR($){let f=s5($);if(!f)return;let J=E0(f.providerId),W=E0(f.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function _R($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function Dj($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let W=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return W;return W.length>0?W:void 0}var TR=new Set(o1);function NR($){let f=Dj($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!TR.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var MR=new Set(["rules","skills","plugins"]);function yR($){let f=Dj($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!MR.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function a5($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function t5($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function o5($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>o5(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${f.map(([J,W])=>`${JSON.stringify(J)}:${o5(W)}`).join(",")}}`}function Lj($,f){let J=FR("sha256");return J.update(o5($)),J.update(`
197
- `),J.update(f),J.digest("hex")}function qR($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var wR=["schedule","timezone"],SR=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],hR=["cwd"];function Rj($,f,J,W,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:Lj(W,J),error:Z}}function o0($,f,J,W,Z,Q){return{externalId:$,relativePath:f,triggerKind:J,body:W,contentHash:Z,error:Q}}function Oj($){let f=$.relativePath.replace(/\\/g,"/"),J=DR(f),{frontmatter:W,body:Z}=LR($.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let F=RR.parse(W);if(F&&typeof F==="object"&&!Array.isArray(F))Q=F;else if(F!==null&&F!==void 0)return Rj(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(F){return Rj(f,J,Z,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let j=Lj(Q,Z),H=E0(Q.id),X=H??f;if(J!=="schedule"){for(let F of wR)if(Q[F]!==void 0)return o0(X,f,J,Z,j,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of hR)if(Q[F]!==void 0)return o0(X,f,J,Z,j,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let F of SR)if(Q[F]!==void 0)return o0(X,f,J,Z,j,`field "${F}" is only allowed on .event.md specs`)}let A=E0(Q.prompt),Y=Z.trim(),V=A??(Y.length>0?Y:void 0);if(!V)return o0(X,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=E0(Q.workspaceRoot);if(!B)return o0(X,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=NR(Q.tools),G=yR(Q.extensions)}catch(F){return o0(X,f,J,Z,j,F instanceof Error?F.message:String(F))}let R=_R(Q.mode);if(Q.mode!==void 0&&R===void 0)return o0(X,f,J,Z,j,"mode must be one of: act, plan, yolo");let P={id:H,title:E0(Q.title)??H??qR(f),prompt:V,workspaceRoot:B,mode:R??"yolo",systemPrompt:E0(Q.systemPrompt),modelSelection:zR(Q.modelSelection),maxIterations:a5(Q.maxIterations),timeoutSeconds:a5(Q.timeoutSeconds),tools:K,notesDirectory:E0(Q.notesDirectory),extensions:G,source:E0(Q.source)??"user",tags:OR(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:s5(Q.metadata)},U;if(J==="schedule"){let F=E0(Q.schedule);if(!F)return o0(X,f,J,Z,j,"schedule is required for *.cron.md specs");let z=E0(Q.timezone);try{Pj(F,z)}catch(D){return o0(X,f,J,Z,j,D instanceof Error?D.message:String(D))}U={...P,triggerKind:"schedule",schedule:F,timezone:z}}else if(J==="event"){let F=E0(Q.event);if(!F)return o0(X,f,J,Z,j,"event is required for .event.md specs");U={...P,triggerKind:"event",event:F,filters:s5(Q.filters),debounceSeconds:t5(Q.debounceSeconds),dedupeWindowSeconds:t5(Q.dedupeWindowSeconds),cooldownSeconds:t5(Q.cooldownSeconds),maxParallel:a5(Q.maxParallel)}}else U={...P,triggerKind:"one_off"};return{externalId:X,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:U}}function mR($,f){return IR($,f).replace(/\\/g,"/")}function gR($){if(!CR($))return[];let f=[],J=[$];while(J.length>0){let W=J.pop();if(!W)continue;let Z;try{Z=ER(W,{withFileTypes:!0})}catch{continue}for(let Q of Z){let j=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(j);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;f.push(j)}}return f}class e5{store;cronDir;constructor($){this.store=$.store,this.cronDir=xR($.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=gR(this.cronDir),J=new Set;for(let Z of f){let Q=mR(this.cronDir,Z);J.add(Q),$.scanned+=1;let j=await this.reconcileFile(Q,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of W)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),W,Z;try{W=bR(f,"utf8"),Z=kR(f).mtimeMs}catch{return}let j=Oj({relativePath:$,raw:W}),H=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"&&H.record.enabled)this.applyScheduleNextRunAt(H.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==H.record.scheduleExpr||J.timezone!==H.record.timezone});return{relativePath:$,result:H,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),W=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=L1($.scheduleExpr,W,$.timezone),Q=new Date(Z).toISOString();if($.nextRunAt!==Q)this.store.updateSpecNextRunAt($.specId,Q)}catch{}}}import{existsSync as vR,mkdirSync as uR,watch as cR}from"node:fs";import{relative as dR,resolve as lR}from"node:path";var pR=250;class $W{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??pR),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{uR($,{recursive:!0}),this.watcher=cR($,{recursive:!0},(f,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=lR(this.reconciler.getCronDir(),$);if(!vR(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=dR(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}import{randomUUID as V2}from"node:crypto";import{asOptionalString as E,asString as r,loadSqliteDb as iR,nowIso as X0}from"@cline/shared/db";import{resolveCronDbPath as nR}from"@cline/shared/storage";var rR=[`CREATE TABLE IF NOT EXISTS cron_specs (
192
+ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim(f.run.runId,f.claimToken,Q))clearInterval(J)},$);return()=>clearInterval(J)}async buildSystemPrompt(f,$,J,Q){let Z=vR(f.notesDirectory),W=l8(void 0,Z),j=await J9($),H=kR({ide:"Cline Cron",workspaceRoot:$,workspaceName:bR($),metadata:j,rules:f.systemPrompt?void 0:W,mode:J,providerId:Q,overridePrompt:f.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return f.systemPrompt?l8(H,W)??H:H}async buildStartRequest(f){let $=(f.workspaceRoot??"").trim(),J=(f.providerId??"").trim(),Q=(f.modelId??"").trim(),Z=f.metadata?.__hubRuntimeOptions&&typeof f.metadata.__hubRuntimeOptions==="object"&&!Array.isArray(f.metadata.__hubRuntimeOptions)?f.metadata.__hubRuntimeOptions:void 0,W=typeof f.metadata?.__hubScheduleCwd==="string"&&f.metadata.__hubScheduleCwd.trim()?f.metadata.__hubScheduleCwd.trim():$;if(!$)throw Error("cron spec requires workspaceRoot");let j=f.mode==="plan"?"plan":f.mode==="act"?"act":"yolo";return{workspaceRoot:$,cwd:W,provider:J,model:Q,mode:j,source:f.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt(f,$,j,J),maxIterations:f.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:mR(f,j),configExtensions:hj.filter((H)=>gR(f,H))}}}import{existsSync as YD,readdirSync as VD,readFileSync as BD,statSync as KD}from"node:fs";import{relative as PD}from"node:path";import{resolveCronSpecsDir as GD}from"@cline/shared/storage";function U2(f,$,J,Q){let Z=new Set;function W(j){let H=j.toLowerCase();if(Q){let A=Q.indexOf(H);if(A!==-1)return A+$}let X=Number(j);if(!Number.isInteger(X)||X<$||X>J)throw Error(`Invalid cron value "${j}" for range [${$}-${J}]`);return X}for(let j of f.split(",")){if(j==="*"){for(let A=$;A<=J;A+=1)Z.add(A);continue}let H=j.indexOf("/");if(H!==-1){let A=j.slice(0,H),Y=Number(j.slice(H+1));if(!Number.isInteger(Y)||Y<1)throw Error(`Invalid step "${j.slice(H+1)}"`);let V=$,B=J;if(A!=="*"){let K=A.indexOf("-");if(K!==-1)V=W(A.slice(0,K)),B=W(A.slice(K+1));else V=W(A)}if(V>B)throw Error(`Invalid cron range "${A}"`);for(let K=V;K<=B;K+=Y)Z.add(K);continue}let X=j.indexOf("-");if(X!==-1){let A=W(j.slice(0,X)),Y=W(j.slice(X+1));if(A>Y)throw Error(`Invalid cron range "${j}"`);for(let V=A;V<=Y;V+=1)Z.add(V);continue}Z.add(W(j))}return[...Z].sort((j,H)=>j-H)}var uR=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],kj=["sun","mon","tue","wed","thu","fri","sat"];function R2(f,$,J){let Q=f[$];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${$+1}`);return Q}function j9(f,$){let J=f[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${$}`);return J}function H9(f){let $=f.trim().split(/\s+/);if($.length!==5)throw Error(`Invalid cron pattern "${f}": expected 5 fields, got ${$.length}`);return{minutes:U2(R2($,0,f),0,59),hours:U2(R2($,1,f),0,23),daysOfMonth:U2(R2($,2,f),1,31),months:U2(R2($,3,f),1,12,uR),daysOfWeek:U2(R2($,4,f),0,6,kj)}}function X9(f){H9(f)}function Ij(f,$,J=Date.now()){z$(f,J,$)}var bj=new Map,dR=new Map(kj.map((f,$)=>[f,$]));function xj(f){let $=f?.trim();return $?$:void 0}function gj(f){let $=bj.get(f);if($)return $;let J=new Intl.DateTimeFormat("en-US",{timeZone:f,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return bj.set(f,J),J}function lR(f){let $=xj(f);if(!$)return;gj($).format(new Date)}function pR(f,$){let J=gj($).formatToParts(new Date(f)),Q=new Map(J.map((j)=>[j.type,j.value])),Z=Q.get("weekday")?.toLowerCase().slice(0,3)??"",W=dR.get(Z);if(W===void 0)throw Error(`Unable to resolve weekday for timezone "${$}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:W,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function rR(f){let $=new Date(f);return{month:$.getMonth()+1,dayOfMonth:$.getDate(),dayOfWeek:$.getDay(),hour:$.getHours(),minute:$.getMinutes()}}function iR(f,$){return f.months.includes($.month)&&f.daysOfMonth.includes($.dayOfMonth)&&f.daysOfWeek.includes($.dayOfWeek)&&f.hours.includes($.hour)&&f.minutes.includes($.minute)}function nR(f,$,J){let Q=H9(f),Z=new Date($);Z.setSeconds(0,0);let W=Z.getTime()+60000,j=new Date($);j.setFullYear(j.getFullYear()+4);let H=j.getTime();while(W<=H){if(iR(Q,pR(W,J)))return W;W+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${f}" in timezone "${J}"`)}function z$(f,$,J){let Q=xj(J);if(Q)return lR(Q),nR(f,$,Q);let Z=H9(f),W=new Date($);W.setSeconds(0,0),W=new Date(W.getTime()+60000);let j=new Date($);j.setFullYear(j.getFullYear()+4);while(W<=j){let{month:H,dayOfMonth:X,dayOfWeek:A,hour:Y,minute:V}=rR(W.getTime());if(!Z.months.includes(H)){let B=Z.months.find((P)=>P>H)??j9(Z.months,"months"),K=B<=H?1:0;W=new Date(W.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(X)||!Z.daysOfWeek.includes(A)){W=new Date(W.getFullYear(),W.getMonth(),X+1,0,0,0,0);continue}if(!Z.hours.includes(Y)){let B=Z.hours.find((P)=>P>Y)??j9(Z.hours,"hours"),K=B<=Y?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(V)){let B=Z.minutes.find((P)=>P>V)??j9(Z.minutes,"minutes"),K=B<=V?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 "${f}"`)}import{createHash as aR}from"node:crypto";import tR from"yaml";function sR(f){let $=f.replace(/\\/g,"/");if($.startsWith("events/")&&$.endsWith(".event.md"))return"event";if($.endsWith(".cron.md"))return"schedule";return"one_off"}function oR(f){let $=f.replace(/\r\n/g,`
193
+ `);if(!$.startsWith(`---
194
+ `))return{frontmatter:void 0,body:f};let J=$.slice(4),Q=J.indexOf(`
195
+ ---`);if(Q===-1)return{frontmatter:void 0,body:f};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 I0(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function eR(f){if(!Array.isArray(f))return;let $=f.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return $.length>0?$:void 0}function V9(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return f}function fD(f){let $=V9(f);if(!$)return;let J=I0($.providerId),Q=I0($.modelId);if(J===void 0&&Q===void 0)return;return{providerId:J,modelId:Q}}function $D(f){if(typeof f!=="string")return;let $=f.trim().toLowerCase();if($==="act"||$==="plan"||$==="yolo")return $;return}function vj(f,$={}){let J=Array.isArray(f)?f:typeof f==="string"?f.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 JD=new Set(Z1);function QD(f){let $=vj(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((Q)=>!JD.has(Q));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return $}var ZD=new Set(["rules","skills","plugins"]);function WD(f){let $=vj(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((Q)=>!ZD.has(Q));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return $}function A9(f){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return;return Math.floor(f)}function Y9(f){if(typeof f!=="number"||!Number.isFinite(f)||f<0)return;return Math.floor(f)}function B9(f){if(f===null||typeof f!=="object")return JSON.stringify(f??null);if(Array.isArray(f))return`[${f.map((J)=>B9(J)).join(",")}]`;let $=Object.entries(f).filter(([,J])=>J!==void 0);return $.sort(([J],[Q])=>J<Q?-1:J>Q?1:0),`{${$.map(([J,Q])=>`${JSON.stringify(J)}:${B9(Q)}`).join(",")}}`}function cj(f,$){let J=aR("sha256");return J.update(B9(f)),J.update(`
197
+ `),J.update($),J.digest("hex")}function jD(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var HD=["schedule","timezone"],XD=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],AD=["cwd"];function mj(f,$,J,Q,Z){return{externalId:f,relativePath:f,triggerKind:$,body:J,contentHash:cj(Q,J),error:Z}}function ff(f,$,J,Q,Z,W){return{externalId:f,relativePath:$,triggerKind:J,body:Q,contentHash:Z,error:W}}function uj(f){let $=f.relativePath.replace(/\\/g,"/"),J=sR($),{frontmatter:Q,body:Z}=oR(f.raw),W={};if(Q!==void 0&&Q.trim().length>0)try{let U=tR.parse(Q);if(U&&typeof U==="object"&&!Array.isArray(U))W=U;else if(U!==null&&U!==void 0)return mj($,J,Z,{},"frontmatter must be a YAML mapping")}catch(U){return mj($,J,Z,{},U instanceof Error?`failed to parse frontmatter: ${U.message}`:"failed to parse frontmatter")}let j=cj(W,Z),H=I0(W.id),X=H??$;if(J!=="schedule"){for(let U of HD)if(W[U]!==void 0)return ff(X,$,J,Z,j,`field "${U}" is only allowed on *.cron.md specs`)}for(let U of AD)if(W[U]!==void 0)return ff(X,$,J,Z,j,`field "${U}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let U of XD)if(W[U]!==void 0)return ff(X,$,J,Z,j,`field "${U}" is only allowed on .event.md specs`)}let A=I0(W.prompt),Y=Z.trim(),V=A??(Y.length>0?Y:void 0);if(!V)return ff(X,$,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=I0(W.workspaceRoot);if(!B)return ff(X,$,J,Z,j,"workspaceRoot is required");let K,P;try{K=QD(W.tools),P=WD(W.extensions)}catch(U){return ff(X,$,J,Z,j,U instanceof Error?U.message:String(U))}let R=$D(W.mode);if(W.mode!==void 0&&R===void 0)return ff(X,$,J,Z,j,"mode must be one of: act, plan, yolo");let G={id:H,title:I0(W.title)??H??jD($),prompt:V,workspaceRoot:B,mode:R??"yolo",systemPrompt:I0(W.systemPrompt),modelSelection:fD(W.modelSelection),maxIterations:A9(W.maxIterations),timeoutSeconds:A9(W.timeoutSeconds),tools:K,notesDirectory:I0(W.notesDirectory),extensions:P,source:I0(W.source)??"user",tags:eR(W.tags),enabled:typeof W.enabled==="boolean"?W.enabled:!0,metadata:V9(W.metadata)},F;if(J==="schedule"){let U=I0(W.schedule);if(!U)return ff(X,$,J,Z,j,"schedule is required for *.cron.md specs");let _=I0(W.timezone);try{Ij(U,_)}catch(L){return ff(X,$,J,Z,j,L instanceof Error?L.message:String(L))}F={...G,triggerKind:"schedule",schedule:U,timezone:_}}else if(J==="event"){let U=I0(W.event);if(!U)return ff(X,$,J,Z,j,"event is required for .event.md specs");F={...G,triggerKind:"event",event:U,filters:V9(W.filters),debounceSeconds:Y9(W.debounceSeconds),dedupeWindowSeconds:Y9(W.dedupeWindowSeconds),cooldownSeconds:Y9(W.cooldownSeconds),maxParallel:A9(W.maxParallel)}}else F={...G,triggerKind:"one_off"};return{externalId:X,relativePath:$,triggerKind:J,body:Z,contentHash:j,spec:F}}function FD(f,$){return PD(f,$).replace(/\\/g,"/")}function UD(f){if(!YD(f))return[];let $=[],J=[f];while(J.length>0){let Q=J.pop();if(!Q)continue;let Z;try{Z=VD(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;$.push(j)}}return $}class K9{store;cronDir;constructor(f){this.store=f.store,this.cronDir=GD(f.specs??(f.workspaceRoot?{scope:"workspace",workspaceRoot:f.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let f={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},$=UD(this.cronDir),J=new Set;for(let Z of $){let W=FD(this.cronDir,Z);J.add(W),f.scanned+=1;let j=await this.reconcileFile(W,Z);if(j){if(f.changes.push(j),f.upserted+=1,j.parse.error)f.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of Q)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),f.removed+=1;return this.refreshScheduleNextRunAt(),f}async reconcileFile(f,$){let J=this.store.getSpecBySourcePath(f),Q,Z;try{Q=BD($,"utf8"),Z=KD($).mtimeMs}catch{return}let j=uj({relativePath:f,raw:Q}),H=this.store.upsertSpec({externalId:j.externalId,sourcePath:f,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"&&H.record.enabled)this.applyScheduleNextRunAt(H.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==H.record.scheduleExpr||J.timezone!==H.record.timezone});return{relativePath:f,result:H,parse:j}}handleFileDeleted(f){this.store.markSpecRemoved(f.specId),this.store.cancelQueuedRunsForSpec(f.specId)}refreshScheduleNextRunAt(){let f=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let $ of f)this.applyScheduleNextRunAt($,{forceReset:!1})}applyScheduleNextRunAt(f,$){if(!f.scheduleExpr)return;if(!$.forceReset&&f.nextRunAt)return;try{let J=Date.now(),Q=f.lastRunAt?Math.max(J,new Date(f.lastRunAt).getTime()):J,Z=z$(f.scheduleExpr,Q,f.timezone),W=new Date(Z).toISOString();if(f.nextRunAt!==W)this.store.updateSpecNextRunAt(f.specId,W)}catch{}}}import{existsSync as RD,mkdirSync as DD,watch as LD}from"node:fs";import{relative as OD,resolve as _D}from"node:path";var TD=250;class P9{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor(f){this.reconciler=f.reconciler,this.debounceMs=Math.max(0,f.debounceMs??TD),this.onError=f.onError??(()=>{}),this.onReconciled=f.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let f=this.reconciler.getCronDir();try{DD(f,{recursive:!0}),this.watcher=LD(f,{recursive:!0},($,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($){this.onError($)}}stop(){for(let f of this.pending.values())clearTimeout(f);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile(f){let $=this.pending.get(f);if($)clearTimeout($);let J=setTimeout(()=>{this.pending.delete(f),this.reconcileNow(f)},this.debounceMs);this.pending.set(f,J)}async reconcileNow(f){try{let $=_D(this.reconciler.getCronDir(),f);if(!RD($)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=OD(this.reconciler.getCronDir(),$).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,$),await this.onReconciled()}catch($){this.onError($)}}}import{randomUUID as D2}from"node:crypto";import{asOptionalString as b,asString as p,loadSqliteDb as MD,nowIso as X0}from"@cline/shared/db";import{resolveCronDbPath as ND}from"@cline/shared/storage";var zD=[`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(W,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 zj($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of rR)$.exec(f)}function OJ($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function fW($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let W=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function O1($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function b$($){return{specId:r($.spec_id),externalId:r($.external_id),sourcePath:r($.source_path),triggerKind:r($.trigger_kind),sourceMtimeMs:O1($.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:OJ(E($.filters_json)),debounceSeconds:O1($.debounce_seconds),dedupeWindowSeconds:O1($.dedupe_window_seconds),cooldownSeconds:O1($.cooldown_seconds),mode:E($.mode),systemPrompt:E($.system_prompt),providerId:E($.provider_id),modelId:E($.model_id),maxIterations:O1($.max_iterations),timeoutSeconds:O1($.timeout_seconds),maxParallel:O1($.max_parallel),tools:fW(E($.tools_json),{preserveEmpty:!0}),notesDirectory:E($.notes_directory),extensions:fW(E($.extensions_json),{preserveEmpty:!0}),source:E($.source),tags:fW(E($.tags_json)),metadata:OJ(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 JW($){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 _j($){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:OJ(E($.payload_json)),attributes:OJ(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 Tj($){return $?JSON.stringify($):null}var aR=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function Nj($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function tR($,f,J,W){for(let Z of aR){let Q=$[Z],j=f[Z];if(Nj(Q)!==Nj(j))return!0}if(J===!1&&W===!0)return!0;return!1}function sR($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function oR($){return`hub/schedules/${$}.cron.md`}function eR($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function WW($){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:eR($)}}function Mj($){return JSON.stringify(WW($))}function $D($,f){let J=$.metadata?{...$.metadata}:{},W=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:W,tags:f.tags??$.tags,runtimeOptions:Q,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class B2{db;constructor($={}){let f=$.dbPath??nR();this.db=iR(f),zj(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?b$(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?b$(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?b$(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>b$(j))}createHubSchedule($){let f=`sched_${V2()}`,J=this.upsertSpec({externalId:f,sourcePath:oR(f),triggerKind:"schedule",sourceHash:Mj($),parseStatus:"valid",spec:WW($)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
288
+ ON cron_specs(source_path);`];function dj(f){f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec("PRAGMA foreign_keys = ON;");for(let $ of zD)f.exec($)}function yJ(f){if(!f)return;try{let $=JSON.parse(f);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return}function G9(f,$={}){if(!f)return;try{let J=JSON.parse(f);if(!Array.isArray(J))return;let Q=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if($.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function M$(f){if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="bigint")return Number(f);return}function mf(f){return{specId:p(f.spec_id),externalId:p(f.external_id),sourcePath:p(f.source_path),triggerKind:p(f.trigger_kind),sourceMtimeMs:M$(f.source_mtime_ms),sourceHash:b(f.source_hash),parseStatus:p(f.parse_status)==="invalid"?"invalid":"valid",parseError:b(f.parse_error),enabled:Number(f.enabled??0)===1,removed:Number(f.removed??0)===1,title:p(f.title),prompt:b(f.prompt),workspaceRoot:b(f.workspace_root),scheduleExpr:b(f.schedule_expr),timezone:b(f.timezone),eventType:b(f.event_type),filters:yJ(b(f.filters_json)),debounceSeconds:M$(f.debounce_seconds),dedupeWindowSeconds:M$(f.dedupe_window_seconds),cooldownSeconds:M$(f.cooldown_seconds),mode:b(f.mode),systemPrompt:b(f.system_prompt),providerId:b(f.provider_id),modelId:b(f.model_id),maxIterations:M$(f.max_iterations),timeoutSeconds:M$(f.timeout_seconds),maxParallel:M$(f.max_parallel),tools:G9(b(f.tools_json),{preserveEmpty:!0}),notesDirectory:b(f.notes_directory),extensions:G9(b(f.extensions_json),{preserveEmpty:!0}),source:b(f.source),tags:G9(b(f.tags_json)),metadata:yJ(b(f.metadata_json)),revision:Number(f.revision??1),lastMaterializedRunId:b(f.last_materialized_run_id),lastRunAt:b(f.last_run_at),nextRunAt:b(f.next_run_at),createdAt:p(f.created_at),updatedAt:p(f.updated_at)}}function F9(f){return{runId:p(f.run_id),specId:p(f.spec_id),specRevision:Number(f.spec_revision??1),triggerKind:p(f.trigger_kind),status:p(f.status),claimToken:b(f.claim_token),claimStartedAt:b(f.claim_started_at),claimUntilAt:b(f.claim_until_at),scheduledFor:b(f.scheduled_for),triggerEventId:b(f.trigger_event_id),startedAt:b(f.started_at),completedAt:b(f.completed_at),sessionId:b(f.session_id),reportPath:b(f.report_path),error:b(f.error),attemptCount:Number(f.attempt_count??0),createdAt:p(f.created_at),updatedAt:p(f.updated_at)}}function lj(f){return{eventId:p(f.event_id),eventType:p(f.event_type),source:p(f.source),subject:b(f.subject),occurredAt:p(f.occurred_at),receivedAt:p(f.received_at),workspaceRoot:b(f.workspace_root),dedupeKey:b(f.dedupe_key),payload:yJ(b(f.payload_json)),attributes:yJ(b(f.attributes_json)),processingStatus:p(f.processing_status),matchedSpecCount:Number(f.matched_spec_count??0),queuedRunCount:Number(f.queued_run_count??0),suppressedCount:Number(f.suppressed_count??0),error:b(f.error),createdAt:p(f.created_at),updatedAt:p(f.updated_at)}}function pj(f){return f?JSON.stringify(f):null}var qD=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function rj(f){if(f===void 0)return null;if(f&&typeof f==="object")return JSON.stringify(f);return f}function yD(f,$,J,Q){for(let Z of qD){let W=f[Z],j=$[Z];if(rj(W)!==rj(j))return!0}if(J===!1&&Q===!0)return!0;return!1}function wD(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function CD(f){return`hub/schedules/${f}.cron.md`}function SD(f){let $={...f.metadata??{},...f.createdBy?{__hubScheduleCreatedBy:f.createdBy}:{},...f.cwd?{__hubScheduleCwd:f.cwd}:{},...f.runtimeOptions?{__hubRuntimeOptions:f.runtimeOptions}:{}};return Object.keys($).length>0?$:void 0}function U9(f){return{triggerKind:"schedule",title:f.name.trim(),prompt:f.prompt,workspaceRoot:f.workspaceRoot.trim(),schedule:f.cronPattern.trim(),mode:f.mode??"act",systemPrompt:f.systemPrompt,modelSelection:f.modelSelection?JSON.parse(JSON.stringify(f.modelSelection)):void 0,maxIterations:typeof f.maxIterations==="number"?Math.floor(f.maxIterations):void 0,timeoutSeconds:typeof f.timeoutSeconds==="number"?Math.floor(f.timeoutSeconds):void 0,maxParallel:typeof f.maxParallel==="number"?Math.max(1,Math.floor(f.maxParallel)):1,source:"hub-schedule",tags:f.tags?.filter(($)=>$.trim().length>0),enabled:f.enabled!==!1,metadata:SD(f)}}function ij(f){return JSON.stringify(U9(f))}function ED(f,$){let J=f.metadata?{...f.metadata}:{},Q=$.createdBy===null?void 0:$.createdBy!==void 0?$.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=$.cwd!==void 0?$.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,W=$.runtimeOptions!==void 0?$.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:$.name??f.title,cronPattern:$.cronPattern??f.scheduleExpr??"",prompt:$.prompt??f.prompt??"",workspaceRoot:$.workspaceRoot??f.workspaceRoot??"",cwd:Z,modelSelection:$.modelSelection!==void 0?$.modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:$.enabled??f.enabled,mode:$.mode??(f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"),systemPrompt:$.systemPrompt===null?void 0:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,maxIterations:$.maxIterations===null?void 0:$.maxIterations!==void 0?$.maxIterations:f.maxIterations,timeoutSeconds:$.timeoutSeconds===null?void 0:$.timeoutSeconds!==void 0?$.timeoutSeconds:f.timeoutSeconds,maxParallel:$.maxParallel??f.maxParallel??1,createdBy:Q,tags:$.tags??f.tags,runtimeOptions:W,metadata:$.metadata!==void 0?$.metadata:Object.keys(J).length>0?J:void 0}}class L2{db;constructor(f={}){let $=f.dbPath??ND();this.db=MD($),dj(this.db)}close(){this.db.close?.()}getSpecBySourcePath(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get(f);return $?mf($):void 0}getSpec(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f);return $?mf($):void 0}getSpecByExternalId(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get(f);return $?mf($):void 0}listSpecs(f={}){let $=[],J=[];if(f.triggerKind)$.push("trigger_kind = ?"),J.push(f.triggerKind);if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.parseStatus)$.push("parse_status = ?"),J.push(f.parseStatus);if(!f.includeRemoved)$.push("removed = 0");let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"",Z=Math.max(1,Math.floor(f.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>mf(j))}createHubSchedule(f){let $=`sched_${D2()}`,J=this.upsertSpec({externalId:$,sourcePath:CD($),triggerKind:"schedule",sourceHash:ij(f),parseStatus:"valid",spec:U9(f)});this.initializeScheduleNextRun(J.record.specId);let Q=this.getSpec(J.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule(f){let $=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?b$(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let Q of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
291
- WHERE ${f.join(" AND ")}
292
- ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>b$(Q))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let W=$D(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:Mj(W),parseStatus:"valid",spec:WW(W)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:X0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
290
+ ORDER BY created_at ASC LIMIT 1`).get(f);return $?mf($):void 0}listHubSchedules(f={}){let $=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.tags&&f.tags.length>0)for(let W of f.tags)$.push("tags_json LIKE ?"),J.push(`%"${W.trim()}"%`);let Q=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
291
+ WHERE ${$.join(" AND ")}
292
+ ORDER BY created_at DESC LIMIT ?`).all(...J,Q).map((W)=>mf(W))}updateHubSchedule(f,$){let J=this.getHubSchedule(f);if(!J)return;let Q=ED(J,$),Z=this.upsertSpec({externalId:f,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:ij(Q),parseStatus:"valid",spec:U9(Q)});if($.cronPattern!==void 0||$.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule(f){let $=this.getHubSchedule(f);if(!$)return!1;return this.markSpecRemoved($.specId),this.cancelQueuedRunsForSpec($.specId),!0}enqueueHubScheduleRun(f,$="manual"){let J=this.getHubSchedule(f);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:$,scheduledFor:X0()})}listEventSpecsForType(f){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)=>b$(J))}upsertSpec($){let f=X0(),J=this.getSpecBySourcePath($.sourcePath),W=$.spec,Z={title:W?.title??J?.title??sR($.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},Q=$.parseStatus==="valid"&&(W?.enabled??!0);if(!J){let Y=`cspec_${V2()}`;this.insertSpecRow(Y,$,Z,Q,f);let V=this.getSpec(Y);if(!V)throw Error("failed to insert cron_spec row");return{record:V,created:!0,revisionChanged:!0}}let H=J.sourceHash!==$.sourceHash&&tR(J,Z,J.enabled,Q),X=H?J.revision+1:J.revision;this.updateSpecRow(J.specId,$,Z,Q,X,f);let A=this.getSpec(J.specId);if(!A)throw Error("failed to reload cron_spec after update");return{record:A,created:!1,revisionChanged:H}}insertSpecRow($,f,J,W,Z){let Q=f.spec;this.db.prepare(`INSERT INTO cron_specs (
298
+ ORDER BY created_at ASC`).all(f).map((J)=>mf(J))}upsertSpec(f){let $=X0(),J=this.getSpecBySourcePath(f.sourcePath),Q=f.spec,Z={title:Q?.title??J?.title??wD(f.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=f.parseStatus==="valid"&&(Q?.enabled??!0);if(!J){let Y=`cspec_${D2()}`;this.insertSpecRow(Y,f,Z,W,$);let V=this.getSpec(Y);if(!V)throw Error("failed to insert cron_spec row");return{record:V,created:!0,revisionChanged:!0}}let H=J.sourceHash!==f.sourceHash&&yD(J,Z,J.enabled,W),X=H?J.revision+1:J.revision;this.updateSpecRow(J.specId,f,Z,W,X,$);let A=this.getSpec(J.specId);if(!A)throw Error("failed to reload cron_spec after update");return{record:A,created:!1,revisionChanged:H}}insertSpecRow(f,$,J,Q,Z){let W=$.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,
@@ -306,7 +306,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
306
306
  tools_json, notes_directory, extensions_json, source,
307
307
  tags_json, metadata_json, revision,
308
308
  created_at, updated_at
309
- ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run($,f.externalId,f.sourcePath,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,W?1:0,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,Q?.tags?JSON.stringify(Q.tags):null,Q?.metadata?JSON.stringify(Q.metadata):null,1,Z,Z)}updateSpecRow($,f,J,W,Z,Q){let j=f.spec;this.db.prepare(`UPDATE cron_specs SET
309
+ ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f,$.externalId,$.sourcePath,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,Q?1:0,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,W?.tags?JSON.stringify(W.tags):null,W?.metadata?JSON.stringify(W.metadata):null,1,Z,Z)}updateSpecRow(f,$,J,Q,Z,W){let j=$.spec;this.db.prepare(`UPDATE cron_specs SET
310
310
  external_id = ?, trigger_kind = ?,
311
311
  source_mtime_ms = ?, source_hash = ?, parse_status = ?, parse_error = ?,
312
312
  enabled = ?, removed = 0, title = ?, prompt = ?,
@@ -318,63 +318,63 @@ ${JSON.stringify(W,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,W?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,Q,$)}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(L1(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 W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let Z=b$(W);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let Q=Z.nextRunAt;if(!Q){let X=new Date(L1(Z.scheduleExpr,f,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(X,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X}}if(new Date(Q).getTime()>f)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Q};let j=`crun_${V2()}`,H;try{H=new Date(L1(Z.scheduleExpr,f,Z.timezone)).toISOString()}catch{H=void 0}return this.db.prepare(`INSERT INTO cron_runs (
321
+ WHERE spec_id = ?`).run($.externalId,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.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,f)}markSpecRemoved(f){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(X0(),f)}updateSpecNextRunAt(f,$){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run($??null,X0(),f)}updateSpecLastRunAt(f,$){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run($,X0(),f)}updateLastMaterializedRunId(f,$){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run($,X0(),f)}initializeScheduleNextRun(f){let $=this.getSpec(f);if(!$||$.triggerKind!=="schedule"||!$.enabled||!$.scheduleExpr){this.updateSpecNextRunAt(f,void 0);return}let J=new Date(z$($.scheduleExpr,Date.now(),$.timezone)).toISOString();this.updateSpecNextRunAt(f,J)}materializeDueScheduleRun(f){let $=f.nowMs,J=new Date($).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let Z=mf(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 X=new Date(z$(Z.scheduleExpr,$,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(X,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X}}if(new Date(W).getTime()>$)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:W};let j=`crun_${D2()}`,H;try{H=new Date(z$(Z.scheduleExpr,$,Z.timezone)).toISOString()}catch{H=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
325
- ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(j,Z.specId,Z.revision,"schedule","queued",Q,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
325
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(j,Z.specId,Z.revision,"schedule","queued",W,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
326
326
  last_materialized_run_id = ?,
327
327
  last_run_at = ?,
328
328
  next_run_at = ?,
329
329
  updated_at = ?
330
- WHERE spec_id = ?`).run(j,J,H??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:H}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?JW(f):void 0}insertEventLog($,f={}){let J=X0(),W=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let Q=$.eventType.trim();if(!Q)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let H=$.occurredAt.trim()||W,X=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
330
+ WHERE spec_id = ?`).run(j,J,H??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:H}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun(f){let $=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get(f);return $?F9($):void 0}insertEventLog(f,$={}){let J=X0(),Q=$.receivedAtIso??J,Z=f.eventId.trim();if(!Z)throw Error("automation event requires eventId");let W=f.eventType.trim();if(!W)throw Error("automation event requires eventType");let j=f.source.trim();if(!j)throw Error("automation event requires source");let H=f.occurredAt.trim()||Q,X=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,Q,j,$.subject?.trim()||null,H,W,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,Tj($.payload),Tj($.attributes),"received",0,0,0,null,J,J).changes??0,A=this.getEventLog(Z);if(!A)throw Error("failed to insert cron_event_log row");return{record:A,created:X===1}}getEventLog($){let f=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return f?_j(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 W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${W}
336
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,W,j,f.subject?.trim()||null,H,Q,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,pj(f.payload),pj(f.attributes),"received",0,0,0,null,J,J).changes??0,A=this.getEventLog(Z);if(!A)throw Error("failed to insert cron_event_log row");return{record:A,created:X===1}}getEventLog(f){let $=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get(f);return $?lj($):void 0}listEventLogs(f={}){let $=[],J=[];if(f.eventType)$.push("event_type = ?"),J.push(f.eventType);if(f.source)$.push("source = ?"),J.push(f.source);if(f.processingStatus)$.push("processing_status = ?"),J.push(f.processingStatus);let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"",Z=Math.max(1,Math.floor(f.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)=>_j(j))}updateEventLogProcessing($,f){return(this.db.prepare(`UPDATE cron_event_log SET
338
+ LIMIT ?`).all(...J,Z).map((j)=>lj(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 H=j.map(()=>"?").join(",");f.push(`status IN (${H})`);for(let X of j)J.push(X)}}let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>JW(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
345
+ WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,X0(),f).changes??0)===1}listRuns(f={}){let $=[],J=[];if(f.specId)$.push("spec_id = ?"),J.push(f.specId);if(f.status){let j=Array.isArray(f.status)?f.status:[f.status];if(j.length>0){let H=j.map(()=>"?").join(",");$.push(`status IN (${H})`);for(let X of j)J.push(X)}}let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"",Z=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>F9(j))}hasRecentEventRunForDedupe(f){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'
349
349
  AND e.dedupe_key = ?
350
350
  AND e.received_at >= ?
351
- LIMIT 1`).get($.specId,$.dedupeKey,$.sinceIso)}hasRecentEventRunForSpec($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
351
+ LIMIT 1`).get(f.specId,f.dedupeKey,f.sinceIso)}hasRecentEventRunForSpec(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
352
352
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
353
353
  WHERE r.spec_id = ?
354
354
  AND r.trigger_kind = 'event'
355
355
  AND e.received_at >= ?
356
- LIMIT 1`).get($.specId,$.sinceIso)}findQueuedEventRunForDedupe($){let f=this.db.prepare(`SELECT r.* FROM cron_runs r
356
+ LIMIT 1`).get(f.specId,f.sinceIso)}findQueuedEventRunForDedupe(f){let $=this.db.prepare(`SELECT r.* FROM cron_runs r
357
357
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
358
358
  WHERE r.spec_id = ?
359
359
  AND r.trigger_kind = 'event'
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?JW(f):void 0}updateQueuedEventRunForDebounce($){let f=X0();if((this.db.prepare(`UPDATE cron_runs SET
363
+ LIMIT 1`).get(f.specId,f.dedupeKey);return $?F9($):void 0}updateQueuedEventRunForDebounce(f){let $=X0();if((this.db.prepare(`UPDATE cron_runs SET
364
364
  trigger_event_id = ?,
365
365
  scheduled_for = ?,
366
366
  updated_at = ?
367
367
  WHERE run_id = ?
368
368
  AND trigger_kind = 'event'
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
369
+ AND status = 'queued'`).run(f.triggerEventId,f.scheduledFor,$,f.runId).changes??0)!==1)return;return this.getRun(f.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_${V2()}`,J=X0();this.db.prepare(`INSERT INTO cron_runs (
372
+ LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${D2()}`,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
376
- ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(f,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId($.specId,f);let W=this.getRun(f);if(!W)throw Error("failed to insert cron_run row");return W}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
377
- WHERE spec_id = ? AND status = 'queued'`).run(X0(),$).changes??0}claimDueRuns($){let f=$.nowIso,J=Math.max(1000,Math.floor($.leaseMs)),W=new Date(new Date(f).getTime()+J).toISOString(),Z=Math.max(1,Math.floor($.limit??25)),Q=[];this.db.exec("BEGIN IMMEDIATE;");try{let j=this.db.prepare(`SELECT * FROM cron_runs
376
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run($,f.specId,f.specRevision,f.triggerKind,"queued",f.scheduledFor??null,f.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId(f.specId,$);let Q=this.getRun($);if(!Q)throw Error("failed to insert cron_run row");return Q}cancelQueuedRunsForSpec(f){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
377
+ WHERE spec_id = ? AND status = 'queued'`).run(X0(),f).changes??0}claimDueRuns(f){let $=f.nowIso,J=Math.max(1000,Math.floor(f.leaseMs)),Q=new Date(new Date($).getTime()+J).toISOString(),Z=Math.max(1,Math.floor(f.limit??25)),W=[];this.db.exec("BEGIN IMMEDIATE;");try{let j=this.db.prepare(`SELECT * FROM cron_runs
378
378
  WHERE (
379
379
  status = 'queued'
380
380
  OR (
@@ -386,7 +386,7 @@ ${JSON.stringify(W,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 H of j){let X=r(H.run_id);if(!X)continue;let A=`cclaim_${V2()}`;if((this.db.prepare(`UPDATE cron_runs SET
389
+ LIMIT ?`).all($,$,Z);for(let H of j){let X=p(H.run_id);if(!X)continue;let A=`cclaim_${D2()}`;if((this.db.prepare(`UPDATE cron_runs SET
390
390
  status = 'running',
391
391
  claim_token = ?,
392
392
  claim_started_at = ?,
@@ -407,8 +407,8 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
407
407
  AND claim_until_at <= ?
408
408
  AND completed_at IS NULL
409
409
  )
410
- )`).run(A,f,W,f,f,X,f).changes??0)!==1)continue;let V=this.getRun(X);if(!V)continue;Q.push({run:V,claimToken:A,claimUntilAt:W})}this.db.exec("COMMIT;")}catch(j){throw this.db.exec("ROLLBACK;"),j}return Q}renewClaim($,f,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
411
- WHERE run_id = ? AND claim_token = ?`).run(J,X0(),$,f).changes??0)===1}completeRun($,f){let J=f.completedAtIso??X0(),W=f.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
410
+ )`).run(A,$,Q,$,$,X,$).changes??0)!==1)continue;let V=this.getRun(X);if(!V)continue;W.push({run:V,claimToken:A,claimUntilAt:Q})}this.db.exec("COMMIT;")}catch(j){throw this.db.exec("ROLLBACK;"),j}return W}renewClaim(f,$,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
411
+ WHERE run_id = ? AND claim_token = ?`).run(J,X0(),f,$).changes??0)===1}completeRun(f,$){let J=$.completedAtIso??X0(),Q=$.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
412
412
  status = ?,
413
413
  session_id = COALESCE(?, session_id),
414
414
  report_path = COALESCE(?, report_path),
@@ -418,7 +418,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
418
418
  claim_token = NULL,
419
419
  claim_until_at = NULL,
420
420
  updated_at = ?
421
- ${W}`).run(f.status,f.sessionId??null,f.reportPath??null,f.error??null,J,J,$,...f.claimToken?[f.claimToken]:[]).changes??0)>0}requeueRun($){let f=X0();return(this.db.prepare(`UPDATE cron_runs SET
421
+ ${Q}`).run($.status,$.sessionId??null,$.reportPath??null,$.error??null,J,J,f,...$.claimToken?[$.claimToken]:[]).changes??0)>0}requeueRun(f){let $=X0();return(this.db.prepare(`UPDATE cron_runs SET
422
422
  status = 'queued',
423
423
  claim_started_at = NULL,
424
424
  claim_token = NULL,
@@ -430,41 +430,41 @@ ${JSON.stringify(W,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 K2{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new B2({dbPath:$.dbPath});let f=$.specs;this.reconciler=new e5({store:this.store,specs:f}),this.materializer=new H2({store:this.store}),this.eventIngress=new v5({store:this.store,logger:$.logger}),this.runner=new X2({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new $W({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=$.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}import{readdir as BD,readFile as Ij}from"node:fs/promises";import{join as xj}from"node:path";import{formatDisplayUserInput as KD,normalizeUserInput as GD}from"@cline/shared";import{resolveSessionDataDir as mj}from"@cline/shared/storage";import{mkdirSync as WD,writeFileSync as ZD}from"node:fs";import{dirname as QD}from"node:path";import{normalizeUserInput as jD}from"@cline/shared";import{nanoid as HD}from"nanoid";import{nanoid as fD}from"nanoid";function G2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function zJ($,f){let J=G2($),W=G2(f),Z=`${J}__${W}`;return Z.length>180?Z.slice(0,180):Z}function ZW($,f){let J=G2($),W=G2(f);return`${J}__teamtask__${W}__${fD(6)}`}function P2($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+12),Q=Z.lastIndexOf("__");if(Q<=0)return null;let j=Z.slice(0,Q),H=Z.slice(Q+2);if(!W||!j||!H)return null;return{rootSessionId:W,agentId:j,teamTaskId:H}}function _J($){if(P2($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+f.length);if(!W||!Z)return null;return{rootSessionId:W,agentId:Z}}function QW($){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 JD=i.enum(_6),_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:JD,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 yj($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function HW($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let W=[],Z=new Set;for(let Q of J){if(Z.has(Q.name))continue;Z.add(Q.name),W.push(Q)}return W}function qj($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function A$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function jW($,f){let J={...$};J.id=A$(J.id)??HD();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:A$(W?.id)??A$(J.modelId)??A$(f?.id),provider:A$(W?.provider)??A$(J.providerId)??A$(f?.provider),family:A$(W?.family)??A$(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 TJ($){return $.map((f)=>jW(f))}function NJ($,f,J=[]){let W=$.map((X,A)=>{let Y=J[A],B=Y?.role===X.role&&JSON.stringify(Y.content)===JSON.stringify(X.content)?{...Y,...X}:{...X};return jW(B)}),Z=J.length,Q=[];for(let X=Z;X<W.length;X+=1)if(W[X]?.role==="assistant")Q.push(X);if(Q.length===0){let X=[...W].reverse().findIndex((A)=>A.role==="assistant");if(X===-1)return W;Q.push(W.length-1-X)}let j=Q[Q.length-1],H=Q.some((X)=>W[X]?.metrics);for(let X of Q){let A=W[X],Y=A.metrics;if(!Y&&X===j&&!H){let V=f.usage;Y={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}W[X]={...jW(A,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...Y?{metrics:Y}:{},ts:A.ts??f.endedAt.getTime()}}return W}function U2($){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 XD=120;function z1($){let f=$?.trim();return f?f.slice(0,XD):void 0}function XW($){let f=jD($??"").trim();if(!f)return;return z1(f.split(`
434
- `)[0]?.trim())}function k$($){if(!$)return;let f={...$},J=z1(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 F2($){let f=k$($.metadata)??{},J=$.title!==void 0?z1($.title):XW($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function AW($){let f=P2($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=_J($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function YW($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:TJ($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function wj($,f,J){WD(QD($),{recursive:!0}),ZD($,`${JSON.stringify(YW({updatedAt:f,context:J,messages:[]}),null,2)}
435
- `,"utf8")}function Sj($,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 hj($,f,J){let W=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let Q=await f(Z);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}import{existsSync as AD}from"node:fs";import{readFile as YD}from"node:fs/promises";import{formatDisplayUserInput as Cj}from"@cline/shared";class R2{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 I$($){let f=$?.trim();if(!f||!AD(f))return[];try{let J=(await YD(f,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return Ej(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let Z=W.messages;if(Array.isArray(Z))return Ej(Z)}return[]}catch{return[]}}function VD($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:Cj($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:Cj(f.text)}})}}function Ej($){return $.map(VD)}function VW($){return $?{...$}:void 0}async function bj($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let W=await f.upsertSubagentSessionFromHook($);if(!W)return;await f.appendSubagentHookAudit(W,$),await f.applySubagentStatus(W,$)}function D2($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function b0($){let f=D2($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function MJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function PD($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function KW($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function UD($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function FD($){return $.isSubagent!==!0&&!D2($.parentSessionId)}function RD($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let W of f){let Z=Number.parseInt(W,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function GW($){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=KW($);if(f===0)return[];let J=mj(),Z=(await BD(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:RD(j.name.trim())})).sort((j,H)=>H.recency-j.recency||H.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let H=j.name.trim();if(!H)return;let X=xj(J,H,`${H}.json`),A=await Ij(X,"utf8").catch(()=>{return});if(!A)return;let Y;try{Y=JSON.parse(A)}catch{return}let V=_0.safeParse(Y);if(!V.success)return;return GW(V.data)}))).filter((j)=>Boolean(j)).sort((j,H)=>H.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function LD($,f,J){let W=KW(f);if(W===0)return await $.listSessions(0),[];let Z=J.includeSubagents?W:UD(W),Q=await $.listSessions(Z);return(J.includeSubagents?Q:Q.filter(FD)).slice(0,W)}function OD($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let Z=W.text?.trim();if(Z)f.push(Z)}return f.join(`
436
- `).trim()}function kj($){return $.replace(/\s+/g," ").trim()}function zD($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function _D($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let W=kj(OD(J.content));if(!W)continue;let Z=f==="user"?kj(KD(W)):W,Q=GD(Z.split(`
437
- `)[0]??Z);return zD(Q,50)}return}function TD($){let f=0;for(let J of $)f+=MJ(J.metrics?.cost)??0;return f}function ND($){let f,J;for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(!f)f=b0(Z.modelInfo?.provider);if(!J)J=b0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function MD($){return b0($?.provider)??b0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function yD($){return b0($?.model)??b0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function BW($,f){let J=PD($.metadata),W=D2(f?.title)??D2(J?.title),Z=MJ(f?.totalCost)??MJ(J?.totalCost),Q=J||W!==void 0||Z!==void 0?{...J??{},...W!==void 0?{title:W}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:b0(f?.provider)??b0($.provider)??MD(J)??"",model:b0(f?.model)??b0($.model)??yD(J)??"",metadata:Q}}function qD($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function wD($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!qD(J)}async function SD($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let W=await $.readSessionMessages(J.sessionId);return wD(J,W)?{...J,status:"idle"}:J}))}async function hD($,f){return await Promise.all(f.map(async(J)=>{let W=BW(J),Z=Boolean(D2(W.metadata?.title)),Q=Boolean(b0(W.provider)),j=Boolean(b0(W.model)),H=MJ(W.metadata?.totalCost),X=H!==void 0&&H>0;if(Z&&Q&&j&&X)return W;let A=await $.readSessionMessages(J.sessionId);if(A.length===0)return W;let Y=ND(A),V=TD(A);return BW(J,{title:Z?void 0:_D(A),provider:Q?void 0:Y.provider,model:j?void 0:Y.model,totalCost:X||V<=0?void 0:V})}))}async function PW($,f={}){let J=KW(f.limit),W=f.includeSubagents===!0,Z=await LD($,J,{includeSubagents:W}),Q=f.includeManifestFallback===!0&&Z.length<J?await DD(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let A of[...Z,...Q]){if(j.has(A.sessionId))continue;j.set(A.sessionId,A)}let H=Q.length===0?Z:Array.from(j.values()).sort((A,Y)=>Y.startedAt.localeCompare(A.startedAt)).slice(0,J),X=await SD($,H);if(f.hydrate===!1)return X.map((A)=>BW(A));return await hD($,X)}async function CD($){let f=$.trim();if(!f)return;let J=xj(mj(),f,`${f}.json`),W=await Ij(J,"utf8").catch(()=>{return});if(!W)return;try{let Z=_0.safeParse(JSON.parse(W));return Z.success?Z.data.messages_path:void 0}catch{return}}async function ED($,f={}){let J=new Map;return await PW({listSessions:async(Z)=>{let Q=await $.listSessions(Z);J.clear();for(let j of Q)J.set(j.sessionId,j);return Q.map(U2)},readSessionMessages:async(Z)=>{let Q=J.get(Z)?.messagesPath??await CD(Z);return await I$(Q)}},f)}import{captureSdkError as AA}from"@cline/shared";import{createSessionId as SL,resolveHubCommandTimeoutMs as hL}from"@cline/shared";import{spawn as HL}from"node:child_process";import{closeSync as XL,mkdirSync as AL,openSync as YL}from"node:fs";import{basename as VL,dirname as BL,join as KL}from"node:path";import{fileURLToPath as GL}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as PL,isHubDaemonProcess as tj,withResolvedClineBuildEnv as UL}from"@cline/shared";import{createHash as bD,randomBytes as kD}from"node:crypto";import{existsSync as ID}from"node:fs";import{chmod as xD,mkdir as UW,readFile as dj,rm as FW,writeFile as lj}from"node:fs/promises";import{dirname as pj,join as RW}from"node:path";import{resolveClineDataDir as DW,resolveClineDir as Ik}from"@cline/shared/storage";var vj="0.0.45";var L2={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:vj,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 mD="CLINE_HUB_DISCOVERY_PATH",gD="CLINE_HUB_BUILD_ID",uj=30000,vD=15000,uD=100;function cD($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function dD($){return bD("sha256").update($).digest("hex").slice(0,12)}function lD($){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 rj(){return kD(32).toString("hex")}function pD($){return new Promise((f)=>setTimeout(f,$))}function rD($){return`${$}.lock`}async function iD($){try{let f=JSON.parse(await dj(RW($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function cj($){await FW($,{recursive:!0,force:!0}).catch(()=>{return})}function Xf(){return process.env[gD]?.trim()||String(L2.version)}function _1($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${dD($)}`,J=process.env[mD]?.trim()||RW(DW(),"locks","hub","owners",`${cD(f)}.json`);return{ownerId:f,discoveryPath:J}}function mk($=`hub-${Date.now().toString(36)}`){return _1($)}async function K0($){try{let f=JSON.parse(await dj($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,coreVersion:typeof f.coreVersion==="string"?f.coreVersion:void 0,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function ij($,f){await UW(pj($),{recursive:!0}),await FW($,{force:!0}).catch(()=>{return}),await lj($,`${JSON.stringify(f,null,2)}
438
- `,{encoding:"utf8",mode:384}),await xD($,384)}async function e0($){await FW($,{force:!0}).catch(()=>{return})}async function nj($,f){let J=rD($);await UW(pj(J),{recursive:!0});let W=Date.now()+vD;while(!0)try{await UW(J,{recursive:!1}),await lj(RW(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
439
- `,"utf8");try{return await f()}finally{await cj(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await iD(J),H=j?Date.now()-Date.parse(j.acquiredAt):uj+1;if(!j||!lD(j.pid)||H>uj){await cj(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await pD(uD)}}async function x$($){try{let f=await fetch(nD($));if(!f.ok)return;return await f.json()}catch{return}}function Y$($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function nD($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function gk($){return ID($)}import{CLINE_HUB_DEV_PORT as aD,CLINE_HUB_PORT as tD,resolveClineBuildEnv as sD}from"@cline/shared";var oD="CLINE_HUB_HOST",eD="CLINE_HUB_PORT",$L="CLINE_HUB_PATHNAME",fL="127.0.0.1",JL=tD,WL="/hub";function aj($){return sD($)==="development"?aD:JL}function ZL($={}){return($.env??process.env)[oD]?.trim()||fL}function yJ($={}){let J=($.env??process.env)[eD]?.trim();if(!J)return aj($);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return aj($);return W}function QL($={}){return($.env??process.env)[$L]?.trim()||WL}function m$($={},f={}){return{host:$.host??ZL(f),port:$.port??yJ(f),pathname:$.pathname??QL(f)}}var jL="shared:cline";function pk($){let f=R1($.trim());return _1(`workspace:${f||$.trim()}`)}function R0($=jL){return _1($)}var FL=8000,RL=200,DL=3000,LL=100,OL=[100,250,500,1000,2000],zL="--cline-hub-daemon";function _L($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function TL(){try{let $=KL(DW(),"logs","hub-daemon.log");return AL(BL($),{recursive:!0}),{fd:YL($,"a"),logPath:$}}catch{return}}function O2($){let f=$.buildId?.trim();return!!f&&f===Xf()}async function T1($){try{return await x$($)}catch{return}}async function NL($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await T1($))?.url)return!0;await new Promise((Z)=>setTimeout(Z,LL))}return!1}async function z2($,f){if(O2($))return;if(await LW($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await NL($.url,DL),await e0(f).catch(()=>{return})}function ML(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return GL(new URL(`./entry.${$}`,import.meta.url))}function yL($,f){let J=ML(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let Z=VL(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),H=Q?[zL]:[...j?["--conditions=development"]:[],J];return{launcher:W,args:[...H,"--cwd",$,..._L(f)],cwd:$,env:{...UL(process.env),CLINE_NO_INTERACTIVE:"1",[PL]:"1"}}}function qL($){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 wL($,f={}){if(tj())return;let J=yL($,f),W=TL();try{HL(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)XL(W.fd)}}async function qJ($,f={}){for(let J=0;;J++)try{wL($,f);return}catch(W){let Z=OL[J];if(!qL(W)||Z===void 0)throw W;await new Promise((Q)=>setTimeout(Q,Z))}}function sj($,f={}){if(tj())return;let J=R0(),W=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=m$(f),Q=Y$(Z.host,Z.port,Z.pathname);K0(J.discoveryPath).then(async(j)=>{if(j?.url){let Y=await T1(j.url);if(Y?.url&&O2(Y)&&await g$(Y.url,{authToken:j.authToken}))return;if(Y?.url)await z2({...Y,authToken:j.authToken},J.discoveryPath);else await e0(J.discoveryPath).catch(()=>{return})}let H=await T1(Q);if(H?.url)await z2(H,J.discoveryPath);let A=!W&&Z.port!==0?{...Z,port:0}:Z;await qJ($,A)}).catch(()=>{})}async function JI($,f={}){let J=R0(),W=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=m$(f),j=Y$(Q.host,Q.port,Q.pathname),H=(K)=>{if(!W)Af(K.url,K.authToken);return K},X=await K0(J.discoveryPath);if(X?.url){let K=await T1(X.url);if(K?.url&&O2(K)&&await g$(K.url,{authToken:X.authToken}))return H({url:K.url,authToken:X.authToken});if(K?.url)await z2({...K,authToken:X.authToken},J.discoveryPath);else await e0(J.discoveryPath).catch(()=>{return})}let A=await T1(j);if(A?.url)await z2(A,J.discoveryPath);let V=!Z&&Q.port!==0?{...Q,port:0}:Q;await qJ($,V);let B=Date.now()+FL;while(Date.now()<B){let K=await K0(J.discoveryPath);if(K?.url){let R=await T1(K.url);if(R?.url&&O2(R)&&await g$(R.url,{authToken:K.authToken}))return H({url:R.url,authToken:K.authToken})}let G=await T1(j);if(G?.url&&!O2(G))await z2(G,J.discoveryPath);await new Promise((R)=>setTimeout(R,RL))}throw Error("Timed out waiting for detached hub startup.")}function CL(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function JH($){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 JH($.data);return String($)}function EL($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function oj($){let f=$,J=EL(f.reason);return new k0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:OW,{closeCode:f.code,closeReason:J||void 0})}function bL($,f){if($ instanceof k0)return $;if($ instanceof Error)return new k0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new k0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new k0("hub_connect_failed",J);let W=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new k0("hub_connect_failed",W?`Failed to connect to hub at ${f.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var kL=8000,IL=200,ej="*",$H=8000,xL="cline-hub-auth.",WH=new Map,ZH=new Set,mL=3000,gL=3000,vL=100,OW="Hub connection closed",uL=250,cL=5000,fH=0.5;class k0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function dL($){return $ instanceof k0}class wJ extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function QH($,f){return $ instanceof wJ&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function jH($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=TW($.toString());return J?WH.get(J):void 0}function lL($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function TW($){if(!lL($))return;let f=new URL(Yf($));return f.search="",f.hash="",f.toString()}function zW($){let f=TW($);return!!f&&ZH.has(f)}function Af($,f){let J=TW($);if(J){if(ZH.add(J),f?.trim())WH.set(J,f)}return $}class V${options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new k0("hub_connection_closed",OW);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()||jH($);$.hash="";let W=new(CL())($.toString(),f?[`${xL}${f}`]:void 0);this.socket=W;let Z=!1;this.connectPromise=new Promise((Q,j)=>{let H=!1,X=setTimeout(()=>{if(H)return;H=!0,Z=!0,this.lastCloseError=new k0("hub_connect_timeout",`Timed out connecting to hub after ${$H}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}j(this.lastCloseError)},$H);W.addEventListener("open",()=>{if(H)return;H=!0,clearTimeout(X),Q()}),W.addEventListener("error",(A)=>{if(H)return;H=!0,clearTimeout(X),this.lastCloseError=bL(A,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),W.addEventListener("close",(A)=>{if(H)return;if(H=!0,clearTimeout(X),!Z)this.lastCloseError=oj(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(JH(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!Z)this.lastCloseError=oj(Q),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,W={listener:$,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,W){let Z=0,Q=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,W)}catch(j){if(!Q||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,W){await this.connect();let Z=SL("hubreq_"),Q=hL($,W?.timeoutMs),j=new Promise((X,A)=>{let Y=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;A(new wJ($,"hub_command_timeout",`Hub command ${$} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(Z,{resolve:(V)=>{if(Y)clearTimeout(Y);X(V)},reject:(V)=>{if(Y)clearTimeout(Y);A(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:f}})}catch(X){throw this.pendingReplies.delete(Z),X}let H=await j;if(!H.ok){if(H.error?.code===Q2){let X=J??(typeof f?.sessionId==="string"?f.sessionId:void 0);throw new U1(X,H.error.message)}throw new wJ($,H.error?.code,H.error?.message??`Hub command ${$} failed`)}return H}async recoverLocalHubTransport($){if(!zW(this.currentUrl)||!dL($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await _2({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(uL*2**this.reconnectAttempt,cL),f=Math.round($*(1-fH)+Math.random()*$*fH);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(!zW(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await _2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new k0("hub_connection_closed",OW),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 k0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),W=(this.subscriptionCounts.get(J)??0)+f;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,W),f>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??ej}subscriptionSessionIdFromKey($){return $===ej?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 Yf($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function g$($,f){let J=new V$({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 _W($,f){let J=Yf($),W=await x$(J);if(!W)return{status:"unreachable",url:J};let Z=Xf(),Q=W.buildId?.trim();if(!Q||Q!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await g$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function pL($){let f=Date.now()+kL;while(Date.now()<f){let J=await K0($.discoveryPath);if(J?.url){let W=await _W(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return Af(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,IL))}return}async function rL($){let f=Date.now()+gL;while(Date.now()<f){if(!(await x$($).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,vL))}return!1}function iL($,f){try{return Yf($)===Yf(f)}catch{return!1}}function nL($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle"||W.status==="pending")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function aL($,f,J){let W=new V$({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await W.command("session.list",{limit:500},void 0,{timeoutMs:mL});return!nL(Z.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function NW($={}){if($.endpoint?.trim()){let Z=await _W($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=R0(),J=await K0(f.discoveryPath);if(!J?.url)return;let W=await _W(J.url);if(W.status==="compatible")return Af(W.url,J.authToken);if(W.status==="build_mismatch")await e0(f.discoveryPath).catch(()=>{return});return}async function _2($={}){let f=await NW($);if(f&&await g$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=R0();return await qJ($.workspaceRoot??process.cwd()),await pL(J)}async function LW($,f){let J=new URL($),W=f?.trim()||jH(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function tL(){let $=R0(),f=await K0($.discoveryPath);if(!f?.url)return!1;try{if(await LW(f.url,f.authToken))return!0}catch{}return!1}async function HH($){if(!zW($.url))return;let f=R0(),J=await K0(f.discoveryPath);if(!J?.url||!iL(J.url,$.url))return;if(!await aL(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await tL())return;if(!await rL(J.url))return;return await e0(f.discoveryPath).catch(()=>{return}),await _2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as XH,createSessionId as AH,HUB_CHECKPOINT_CAPABILITY as $O,HUB_COMPACTION_CAPABILITY as fO,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as JO,HUB_HOOK_CAPABILITY_PREFIX as WO,HUB_MISTAKE_LIMIT_CAPABILITY as ZO,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as QO,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as jO,isHubToolExecutorName as HO}from"@cline/shared";function sL($){return $?JSON.parse(JSON.stringify($)):void 0}function oL($){return $?JSON.parse(JSON.stringify($)):void 0}function eL($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,W=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let H=typeof j.ref==="string"?j.ref.trim():"",X=Number(j.createdAt),A=Number(j.runCount);if(!H||!Number.isFinite(X)||!Number.isInteger(A))return[];return[{ref:H,createdAt:X,runCount:A,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=W.at(-1),Q=$?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...Z?{latest:Z}:{},history:W}}function v$($){let{session:f}=$,J=sL(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:oL($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let W=eL(J);return W?{checkpoint:W}:{}})()}}function MW($){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 Vf($){if(!$)return;return JSON.parse(JSON.stringify($))}var XO=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function YH($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function VH($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function BH($){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 N1($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function KH($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(HO)){let Q=f.toolExecutors?.[Z];if(typeof Q!=="function")continue;N1(J,{kind:"toolExecutor",executor:Z,capabilityName:`${QO}${Z}`},async({payload:j,abortSignal:H})=>{let X=Array.isArray(j.args)?[...j.args]:[],A={...BH(j.context),signal:H};return{result:await Q(...X,A)}})}for(let Z of $?.extraTools??[])N1(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:Vf(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:Vf(Z.lifecycle)}:{},capabilityName:`${JO}${Z.name}`},async({payload:Q,abortSignal:j,progress:H})=>{let X={...BH(Q.context),signal:j};return{result:await Z.execute(Q.input,{...X,emitUpdate:(Y)=>{H({update:Y})}})}});let W=$?.hooks;if(W)for(let Z of XO){let Q=W[Z];if(typeof Q!=="function")continue;N1(J,{kind:"hook",name:Z,capabilityName:`${WO}${Z}`},async({payload:j})=>({control:await Q(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;N1(J,{kind:"compaction",capabilityName:fO,config:YH($.compaction)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;N1(J,{kind:"checkpoint",capabilityName:$O,config:YH($.checkpoint)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;N1(J,{kind:"mistakeLimit",capabilityName:ZO},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;N1(J,{kind:"userInstructionService",capabilityName:jO},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 FH($){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 AO($){return FH($)??"Capability request was cancelled."}function YO($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function VO($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function BO($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,W=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function GH($){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 yW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function u$($,f){return yW($?.[f])??0}function KO($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,W=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=W?.teamRole==="teammate"||W?.teamRole==="lead"?W.teamRole:void 0;return{event:{type:"usage",agentId:typeof W?.agentId==="string"?W.agentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,inputTokens:u$(f,"inputTokens"),outputTokens:u$(f,"outputTokens"),cacheReadTokens:u$(f,"cacheReadTokens"),cacheWriteTokens:u$(f,"cacheWriteTokens"),cost:yW(f?.totalCost),totalInputTokens:u$(J,"inputTokens"),totalOutputTokens:u$(J,"outputTokens"),totalCacheReadTokens:u$(J,"cacheReadTokens"),totalCacheWriteTokens:u$(J,"cacheWriteTokens"),totalCost:yW(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:Z}}function GO($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,W=VO(J)?J:J==="failed"?"error":"completed",Z=BO($?.usage??f?.usage);return{type:"done",reason:W,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function SJ($,f){return $.error?.message??`hub command failed: ${f}`}function T2($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function RH($){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:U0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:T2($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:T2($.status)==="completed"?0:T2($.status)==="failed"?1:void 0,status:T2($.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 c$($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function PO($){let f=c$($?.snapshot);if(f)return MW(f);let J=$?.session;return J?RH(J):void 0}function PH($,f,J){let W=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return _0.parse({version:1,session_id:$,source:f.source??U0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:T2(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:W,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function UH($,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 M1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new R2;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=F0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new V$({...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(!QH($,"session.create"))return!1;let f=await HH({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=KH($.localRuntime,f),W=$.config.sessionId?.trim()||AH(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:Vf({...$.config,sessionId:W}),metadata:{...$.sessionMetadata??{},source:$.source??U0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:Vf($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(W,f,J.handlers);let Q;try{Q=await Z()}catch(A){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(W,f,J.handlers);try{Q=await Z()}catch(Y){throw this.cleanupPlannedSession(W),Y}}else throw A}let j=c$(Q.payload?.snapshot),H=Q.payload?.session,X=(j?.sessionId??H?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(X!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(X,f,J.handlers);return{sessionId:X,manifest:j?UH(j,$):PH(X,$,H),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let W=$.start,Z=W?this.resolveCapabilities(W):void 0,Q=W?KH(W.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=W?W.config.sessionId?.trim()||AH():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(j,Q.handlers),this.ensureSessionSubscription(j);let H;try{H=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??$.cwd,sessionConfig:Vf({...W.config,sessionId:j}),metadata:{...W.sessionMetadata??{},source:W.source??U0.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:Vf(W.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!H.ok){let K=typeof H.payload?.error==="string"?H.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let X=c$(H.payload?.snapshot),A=H.payload?.session,Y=(X?.sessionId??A?.sessionId)?.trim();if(J&&!Y){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(Y&&j&&Y!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(Y&&Z)this.sessionCapabilities.set(Y,Z);if(Y&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Y,Q.handlers);if(Y)this.ensureSessionSubscription(Y);let V=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,B=H.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:Y,startResult:Y?{sessionId:Y,manifest:X?UH(X,W??{}):PH(Y,W??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=c$(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,H=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||H?{usage:j,aggregateUsage:H}:void 0}let W=f.payload?.session,Z=GH(W?.usage),Q=GH(W?.aggregateUsage);return Z||Q?{usage:Z,aggregateUsage:Q}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:FH(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(F1(J))return;throw J}return PO(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let Q=c$(Z);return Q?[MW(Q)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(RH)}async listSettings($){let f=await this.client.command("settings.list",VH($));if(!f.ok)throw Error(SJ(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",VH($));if(!f.ok)throw Error(SJ(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 XH(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(SJ(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(SJ(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return F0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:GO($.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=c$($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",W=$.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=KO($.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=c$($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=c$($.payload?.snapshot),W=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:W}}),J?.interactive===!0&&$0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:W,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{XH(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},H=new AbortController;this.activeCapabilityAbortControllers.set(W,H);let X=(A)=>{this.client.command("capability.progress",{requestId:W,payload:A},f).catch((Y)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",Y,$)})};try{let A=await Q({payload:j,abortSignal:H.signal,progress:X});if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:A},f)}catch(A){if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:A instanceof Error?A.message:String(A)},f)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(AO($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",Q=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!W||!Z||!Q)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},H=YO($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:Q,toolInput:H});let X=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:Q,input:H,policy:j})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:W,approved:X.approved,reason:X.reason},f).catch(()=>{})}}class hJ extends M1{constructor($){super({url:Yf($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as UO,mkdirSync as FO}from"node:fs";import{join as RO}from"node:path";import{asBool as N2,asOptionalString as $$,asString as B$,ensureSessionSchema as DO,loadSqliteDb as LO,nowIso as CJ,toBoolInt as M2}from"@cline/shared/db";import{resolveDbDataDir as OO}from"@cline/shared/storage";class d${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??OO()}init(){this.getRawDb()}ensureSessionsDir(){if(!UO(this.sessionsDirPath))FO(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return RO(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=LO(this.sessionDbPath());return DO($,{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=CJ();this.run(`INSERT OR REPLACE INTO sessions (
433
+ WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,X0(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,X0(),f)}}class O2{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new L2({dbPath:f.dbPath});let $=f.specs;this.reconciler=new K9({store:this.store,specs:$}),this.materializer=new G2({store:this.store}),this.eventIngress=new f9({store:this.store,logger:f.logger}),this.runner=new F2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:f.workspaceRoot,specs:$,logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency}),this.watcher=new P9({reconciler:this.reconciler,debounceMs:f.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=f.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(f){return this.store.listSpecs(f)}getSpec(f){return this.store.getSpec(f)}listRuns(f){return this.store.listRuns(f)}getRun(f){return this.store.getRun(f)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns(f=20){return this.store.listRuns({status:"queued",limit:f})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent(f){return this.eventIngress.ingestEvent(f)}listEventLogs(f){return this.store.listEventLogs(f)}getEventLog(f){return this.store.getEventLog(f)}}import{readdir as lD,readFile as QH}from"node:fs/promises";import{join as ZH}from"node:path";import{formatDisplayUserInput as pD,normalizeUserInput as rD}from"@cline/shared";import{resolveSessionDataDir as WH}from"@cline/shared/storage";import{mkdirSync as kD,writeFileSync as ID}from"node:fs";import{dirname as xD}from"node:path";import{normalizeUserInput as gD}from"@cline/shared";import{nanoid as mD}from"nanoid";import{nanoid as hD}from"nanoid";function _2(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function wJ(f,$){let J=_2(f),Q=_2($),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function R9(f,$){let J=_2(f),Q=_2($);return`${J}__teamtask__${Q}__${hD(6)}`}function T2(f){let J=f.indexOf("__teamtask__");if(J<=0)return null;let Q=f.slice(0,J),Z=f.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),H=Z.slice(W+2);if(!Q||!j||!H)return null;return{rootSessionId:Q,agentId:j,teamTaskId:H}}function CJ(f){if(T2(f))return null;let $="__",J=f.indexOf($);if(J<=0)return null;let Q=f.slice(0,J),Z=f.slice(J+$.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function D9(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as r}from"zod";var bD=r.enum(I6),N0=r.object({version:r.literal(1),session_id:r.string().min(1),source:r.string().min(1),pid:r.number().int(),started_at:r.string().min(1),ended_at:r.string().min(1).optional(),exit_code:r.number().int().nullable().optional(),status:bD,interactive:r.boolean(),provider:r.string().min(1),model:r.string().min(1),cwd:r.string().min(1),workspace_root:r.string().min(1),team_name:r.string().min(1).optional(),enable_tools:r.boolean(),enable_spawn:r.boolean(),enable_teams:r.boolean(),prompt:r.string().optional(),metadata:r.record(r.string(),r.unknown()).optional(),messages_path:r.string().min(1).optional()});function nj(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function O9(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 aj(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function Pf(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function L9(f,$){let J={...f};J.id=Pf(J.id)??mD();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:Pf(Q?.id)??Pf(J.modelId)??Pf($?.id),provider:Pf(Q?.provider)??Pf(J.providerId)??Pf($?.provider),family:Pf(Q?.family)??Pf($?.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 SJ(f){return f.map(($)=>L9($))}function EJ(f,$,J=[]){let Q=f.map((X,A)=>{let Y=J[A],B=Y?.role===X.role&&JSON.stringify(Y.content)===JSON.stringify(X.content)?{...Y,...X}:{...X};return L9(B)}),Z=J.length,W=[];for(let X=Z;X<Q.length;X+=1)if(Q[X]?.role==="assistant")W.push(X);if(W.length===0){let X=[...Q].reverse().findIndex((A)=>A.role==="assistant");if(X===-1)return Q;W.push(Q.length-1-X)}let j=W[W.length-1],H=W.some((X)=>Q[X]?.metrics);for(let X of W){let A=Q[X],Y=A.metrics;if(!Y&&X===j&&!H){let V=$.usage;Y={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}Q[X]={...L9(A,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...Y?{metrics:Y}:{},ts:A.ts??$.endedAt.getTime()}}return Q}function z2(f){return{sessionId:f.sessionId,source:f.source,pid:f.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??void 0,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:f.parentSessionId??void 0,parentAgentId:f.parentAgentId??void 0,agentId:f.agentId??void 0,conversationId:f.conversationId??void 0,isSubagent:f.isSubagent,prompt:f.prompt??void 0,metadata:f.metadata??void 0,messagesPath:f.messagesPath??void 0,updatedAt:f.updatedAt}}var vD=120;function N$(f){let $=f?.trim();return $?$.slice(0,vD):void 0}function _9(f){let $=gD(f??"").trim();if(!$)return;return N$($.split(`
434
+ `)[0]?.trim())}function vf(f){if(!f)return;let $={...f},J=N$(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function M2(f){let $=vf(f.metadata)??{},J=f.title!==void 0?N$(f.title):_9(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function T9(f){let $=T2(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=CJ(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function z9(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:SJ(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function tj(f,$,J){kD(xD(f),{recursive:!0}),ID(f,`${JSON.stringify(z9({updatedAt:$,context:J,messages:[]}),null,2)}
435
+ `,"utf8")}function sj(f,$){return N0.parse({version:1,session_id:f.sessionId,source:f.source,pid:f.pid,started_at:f.startedAt,ended_at:$?.endedAt??f.endedAt??void 0,exit_code:$?.exitCode??f.exitCode??void 0,status:$?.status??f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName??void 0,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt??void 0,metadata:$?.metadata??f.metadata??void 0,messages_path:f.messagesPath??void 0})}async function oj(f,$,J){let Q=0;while(!0){let Z=await f();if(Z===void 0)return{updated:!1};let W=await $(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 cD}from"node:fs";import{readFile as uD}from"node:fs/promises";import{formatDisplayUserInput as ej}from"@cline/shared";class N2{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function cf(f){let $=f?.trim();if(!$||!cD($))return[];try{let J=(await uD($,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return fH(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return fH(Z)}return[]}catch{return[]}}function dD(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:ej(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:ej($.text)}})}}function fH(f){return f.map(dD)}function M9(f){return f?{...f}:void 0}async function $H(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let Q=await $.upsertSubagentSessionFromHook(f);if(!Q)return;await $.appendSubagentHookAudit(Q,f),await $.applySubagentStatus(Q,f)}function q2(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function x0(f){let $=q2(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function hJ(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function iD(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function q9(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function nD(f){if(f===0)return 0;return Math.min(Math.max(f*2,20),2000)}function aD(f){return f.isSubagent!==!0&&!q2(f.parentSessionId)}function tD(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let Q of $){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function y9(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function sD(f){let $=q9(f);if($===0)return[];let J=WH(),Z=(await lD(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:tD(j.name.trim())})).sort((j,H)=>H.recency-j.recency||H.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let H=j.name.trim();if(!H)return;let X=ZH(J,H,`${H}.json`),A=await QH(X,"utf8").catch(()=>{return});if(!A)return;let Y;try{Y=JSON.parse(A)}catch{return}let V=N0.safeParse(Y);if(!V.success)return;return y9(V.data)}))).filter((j)=>Boolean(j)).sort((j,H)=>H.startedAt.localeCompare(j.startedAt)).slice(0,$)}async function oD(f,$,J){let Q=q9($);if(Q===0)return await f.listSessions(0),[];let Z=J.includeSubagents?Q:nD(Q),W=await f.listSessions(Z);return(J.includeSubagents?W:W.filter(aD)).slice(0,Q)}function eD(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)$.push(Z)}return $.join(`
436
+ `).trim()}function JH(f){return f.replace(/\s+/g," ").trim()}function fL(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function $L(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let Q=JH(eD(J.content));if(!Q)continue;let Z=$==="user"?JH(pD(Q)):Q,W=rD(Z.split(`
437
+ `)[0]??Z);return fL(W,50)}return}function JL(f){let $=0;for(let J of f)$+=hJ(J.metrics?.cost)??0;return $}function QL(f){let $,J;for(let Q=f.length-1;Q>=0;Q-=1){let Z=f[Q];if(!$)$=x0(Z.modelInfo?.provider);if(!J)J=x0(Z.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function ZL(f){return x0(f?.provider)??x0(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function WL(f){return x0(f?.model)??x0(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function N9(f,$){let J=iD(f.metadata),Q=q2($?.title)??q2(J?.title),Z=hJ($?.totalCost)??hJ(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...f,provider:x0($?.provider)??x0(f.provider)??ZL(J)??"",model:x0($?.model)??x0(f.model)??WL(J)??"",metadata:W}}function jL(f){let $=f.content;if(!Array.isArray($))return!1;return $.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function HL(f,$){if(f.status!=="running"||f.interactive!==!0)return!1;let J=$.at(-1);return J?.role==="assistant"&&!jL(J)}async function XL(f,$){return await Promise.all($.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let Q=await f.readSessionMessages(J.sessionId);return HL(J,Q)?{...J,status:"idle"}:J}))}async function AL(f,$){return await Promise.all($.map(async(J)=>{let Q=N9(J),Z=Boolean(q2(Q.metadata?.title)),W=Boolean(x0(Q.provider)),j=Boolean(x0(Q.model)),H=hJ(Q.metadata?.totalCost),X=H!==void 0&&H>0;if(Z&&W&&j&&X)return Q;let A=await f.readSessionMessages(J.sessionId);if(A.length===0)return Q;let Y=QL(A),V=JL(A);return N9(J,{title:Z?void 0:$L(A),provider:W?void 0:Y.provider,model:j?void 0:Y.model,totalCost:X||V<=0?void 0:V})}))}async function w9(f,$={}){let J=q9($.limit),Q=$.includeSubagents===!0,Z=await oD(f,J,{includeSubagents:Q}),W=$.includeManifestFallback===!0&&Z.length<J?await sD(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let A of[...Z,...W]){if(j.has(A.sessionId))continue;j.set(A.sessionId,A)}let H=W.length===0?Z:Array.from(j.values()).sort((A,Y)=>Y.startedAt.localeCompare(A.startedAt)).slice(0,J),X=await XL(f,H);if($.hydrate===!1)return X.map((A)=>N9(A));return await AL(f,X)}async function YL(f){let $=f.trim();if(!$)return;let J=ZH(WH(),$,`${$}.json`),Q=await QH(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=N0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function VL(f,$={}){let J=new Map;return await w9({listSessions:async(Z)=>{let W=await f.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map(z2)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await YL(Z);return await cf(W)}},$)}import{captureSdkError as bA}from"@cline/shared";import{createSessionId as XO,resolveHubCommandTimeoutMs as AO}from"@cline/shared";import{spawn as mL}from"node:child_process";import{closeSync as vL,mkdirSync as cL,openSync as uL}from"node:fs";import{basename as dL,dirname as lL,join as pL}from"node:path";import{fileURLToPath as rL}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as iL,isHubDaemonProcess as UH,withResolvedClineBuildEnv as nL}from"@cline/shared";import{createHash as BL,randomBytes as KL}from"node:crypto";import{existsSync as PL}from"node:fs";import{chmod as GL,mkdir as C9,readFile as YH,rm as S9,writeFile as VH}from"node:fs/promises";import{dirname as BH,join as E9}from"node:path";import{resolveClineDataDir as h9,resolveClineDir as yI}from"@cline/shared/storage";var HH="0.0.46";var y2={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:HH,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 FL="CLINE_HUB_DISCOVERY_PATH",UL="CLINE_HUB_BUILD_ID",XH=30000,RL=15000,DL=100;function LL(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function OL(f){return BL("sha256").update(f).digest("hex").slice(0,12)}function _L(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function KH(){return KL(32).toString("hex")}function TL(f){return new Promise(($)=>setTimeout($,f))}function zL(f){return`${f}.lock`}async function ML(f){try{let $=JSON.parse(await YH(E9(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function AH(f){await S9(f,{recursive:!0,force:!0}).catch(()=>{return})}function F1(){return process.env[UL]?.trim()||String(y2.version)}function q$(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${OL(f)}`,J=process.env[FL]?.trim()||E9(h9(),"locks","hub","owners",`${LL($)}.json`);return{ownerId:$,discoveryPath:J}}function CI(f=`hub-${Date.now().toString(36)}`){return q$(f)}async function P0(f){try{let $=JSON.parse(await YH(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function PH(f,$){await C9(BH(f),{recursive:!0}),await S9(f,{force:!0}).catch(()=>{return}),await VH(f,`${JSON.stringify($,null,2)}
438
+ `,{encoding:"utf8",mode:384}),await GL(f,384)}async function $f(f){await S9(f,{force:!0}).catch(()=>{return})}async function GH(f,$){let J=zL(f);await C9(BH(J),{recursive:!0});let Q=Date.now()+RL;while(!0)try{await C9(J,{recursive:!1}),await VH(E9(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
439
+ `,"utf8");try{return await $()}finally{await AH(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await ML(J),H=j?Date.now()-Date.parse(j.acquiredAt):XH+1;if(!j||!_L(j.pid)||H>XH){await AH(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await TL(DL)}}async function uf(f){try{let $=await fetch(NL(f));if(!$.ok)return;return await $.json()}catch{return}}function Gf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function NL(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function SI(f){return PL(f)}import{CLINE_HUB_DEV_PORT as qL,CLINE_HUB_PORT as yL,resolveClineBuildEnv as wL}from"@cline/shared";var CL="CLINE_HUB_HOST",SL="CLINE_HUB_PORT",EL="CLINE_HUB_PATHNAME",hL="127.0.0.1",bL=yL,kL="/hub";function FH(f){return wL(f)==="development"?qL:bL}function IL(f={}){return(f.env??process.env)[CL]?.trim()||hL}function bJ(f={}){let J=(f.env??process.env)[SL]?.trim();if(!J)return FH(f);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return FH(f);return Q}function xL(f={}){return(f.env??process.env)[EL]?.trim()||kL}function df(f={},$={}){return{host:f.host??IL($),port:f.port??bJ($),pathname:f.pathname??xL($)}}var gL="shared:cline";function xI(f){let $=_$(f.trim());return q$(`workspace:${$||f.trim()}`)}function D0(f=gL){return q$(f)}var aL=8000,tL=200,sL=3000,oL=100,eL=[100,250,500,1000,2000],fO="--cline-hub-daemon";function $O(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function JO(){try{let f=pL(h9(),"logs","hub-daemon.log");return cL(lL(f),{recursive:!0}),{fd:uL(f,"a"),logPath:f}}catch{return}}function w2(f){let $=f.buildId?.trim();return!!$&&$===F1()}async function y$(f){try{return await uf(f)}catch{return}}async function QO(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await y$(f))?.url)return!0;await new Promise((Z)=>setTimeout(Z,oL))}return!1}async function C2(f,$){if(w2(f))return;if(await b9(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await QO(f.url,sL),await $f($).catch(()=>{return})}function ZO(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return rL(new URL(`./entry.${f}`,import.meta.url))}function WO(f,$){let J=ZO(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=dL(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),H=W?[fO]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...H,"--cwd",f,...$O($)],cwd:f,env:{...nL(process.env),CLINE_NO_INTERACTIVE:"1",[iL]:"1"}}}function jO(f){if(!f||typeof f!=="object")return!1;if(("code"in f?f.code:void 0)==="ETXTBSY")return!0;let J="message"in f?f.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function HO(f,$={}){if(UH())return;let J=WO(f,$),Q=JO();try{mL(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(Q)vL(Q.fd)}}async function kJ(f,$={}){for(let J=0;;J++)try{HO(f,$);return}catch(Q){let Z=eL[J];if(!jO(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function RH(f,$={}){if(UH())return;let J=D0(),Q=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=df($),W=Gf(Z.host,Z.port,Z.pathname);P0(J.discoveryPath).then(async(j)=>{if(j?.url){let Y=await y$(j.url);if(Y?.url&&w2(Y)&&await lf(Y.url,{authToken:j.authToken}))return;if(Y?.url)await C2({...Y,authToken:j.authToken},J.discoveryPath);else await $f(J.discoveryPath).catch(()=>{return})}let H=await y$(W);if(H?.url)await C2(H,J.discoveryPath);let A=!Q&&Z.port!==0?{...Z,port:0}:Z;await kJ(f,A)}).catch(()=>{})}async function nI(f,$={}){let J=D0(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=df($),j=Gf(W.host,W.port,W.pathname),H=(K)=>{if(!Q)U1(K.url,K.authToken);return K},X=await P0(J.discoveryPath);if(X?.url){let K=await y$(X.url);if(K?.url&&w2(K)&&await lf(K.url,{authToken:X.authToken}))return H({url:K.url,authToken:X.authToken});if(K?.url)await C2({...K,authToken:X.authToken},J.discoveryPath);else await $f(J.discoveryPath).catch(()=>{return})}let A=await y$(j);if(A?.url)await C2(A,J.discoveryPath);let V=!Z&&W.port!==0?{...W,port:0}:W;await kJ(f,V);let B=Date.now()+aL;while(Date.now()<B){let K=await P0(J.discoveryPath);if(K?.url){let R=await y$(K.url);if(R?.url&&w2(R)&&await lf(R.url,{authToken:K.authToken}))return H({url:R.url,authToken:K.authToken})}let P=await y$(j);if(P?.url&&!w2(P))await C2(P,J.discoveryPath);await new Promise((R)=>setTimeout(R,tL))}throw Error("Timed out waiting for detached hub startup.")}function YO(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function TH(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return TH(f.data);return String(f)}function VO(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function DH(f){let $=f,J=VO($.reason);return new g0("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:k9,{closeCode:$.code,closeReason:J||void 0})}function BO(f,$){if(f instanceof g0)return f;if(f instanceof Error)return new g0("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new g0("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new g0("hub_connect_failed",J);let Q=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new g0("hub_connect_failed",Q?`Failed to connect to hub at ${$.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var KO=8000,PO=200,LH="*",OH=8000,GO="cline-hub-auth.",zH=new Map,MH=new Set,FO=3000,UO=3000,RO=100,k9="Hub connection closed",DO=250,LO=5000,_H=0.5;class g0 extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function OO(f){return f instanceof g0}class IJ extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function NH(f,$){return f instanceof IJ&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function qH(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=g9(f.toString());return J?zH.get(J):void 0}function _O(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function g9(f){if(!_O(f))return;let $=new URL(R1(f));return $.search="",$.hash="",$.toString()}function I9(f){let $=g9(f);return!!$&&MH.has($)}function U1(f,$){let J=g9(f);if(J){if(MH.add(J),$?.trim())zH.set(J,$)}return f}class Ff{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new g0("hub_connection_closed",k9);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.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 f=new URL(this.currentUrl),$=this.options.authToken?.trim()||qH(f);f.hash="";let Q=new(YO())(f.toString(),$?[`${GO}${$}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let H=!1,X=setTimeout(()=>{if(H)return;H=!0,Z=!0,this.lastCloseError=new g0("hub_connect_timeout",`Timed out connecting to hub after ${OH}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},OH);Q.addEventListener("open",()=>{if(H)return;H=!0,clearTimeout(X),W()}),Q.addEventListener("error",(A)=>{if(H)return;H=!0,clearTimeout(X),this.lastCloseError=BO(A,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(A)=>{if(H)return;if(H=!0,clearTimeout(X),!Z)this.lastCloseError=DH(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(TH(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=DH(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=$?.sessionId?.trim()||void 0,Q={listener:f,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=f!=="client.register"&&f!=="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=XO("hubreq_"),W=AO(f,Q?.timeoutMs),j=new Promise((X,A)=>{let Y=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;A(new IJ(f,"hub_command_timeout",`Hub command ${f} 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:(V)=>{if(Y)clearTimeout(Y);X(V)},reject:(V)=>{if(Y)clearTimeout(Y);A(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:$}})}catch(X){throw this.pendingReplies.delete(Z),X}let H=await j;if(!H.ok){if(H.error?.code===K2){let X=J??(typeof $?.sessionId==="string"?$.sessionId:void 0);throw new L$(X,H.error.message)}throw new IJ(f,H.error?.code,H.error?.message??`Hub command ${f} failed`)}return H}async recoverLocalHubTransport(f){if(!I9(this.currentUrl)||!OO(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await S2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,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 f=Math.min(DO*2**this.reconnectAttempt,LO),$=Math.round(f*(1-_H)+Math.random()*f*_H);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!I9(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await S2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new g0("hub_connection_closed",k9),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.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(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new g0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),Q=(this.subscriptionCounts.get(J)??0)+$;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,Q),$>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??LH}subscriptionSessionIdFromKey(f){return f===LH?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function R1(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function lf(f,$){let J=new Ff({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function x9(f,$){let J=R1(f),Q=await uf(J);if(!Q)return{status:"unreachable",url:J};let Z=F1(),W=Q.buildId?.trim();if(!W||W!==Z)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await lf(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function TO(f){let $=Date.now()+KO;while(Date.now()<$){let J=await P0(f.discoveryPath);if(J?.url){let Q=await x9(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return U1(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,PO))}return}async function zO(f){let $=Date.now()+UO;while(Date.now()<$){if(!(await uf(f).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,RO))}return!1}function MO(f,$){try{return R1(f)===R1($)}catch{return!1}}function NO(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.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 qO(f,$,J){let Q=new Ff({url:f,authToken:$,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:FO});return!NO(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function m9(f={}){if(f.endpoint?.trim()){let Z=await x9(f.endpoint);return Z.status==="compatible"?Z.url:void 0}let $=D0(),J=await P0($.discoveryPath);if(!J?.url)return;let Q=await x9(J.url);if(Q.status==="compatible")return U1(Q.url,J.authToken);if(Q.status==="build_mismatch")await $f($.discoveryPath).catch(()=>{return});return}async function S2(f={}){let $=await m9(f);if($&&await lf($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=D0();return await kJ(f.workspaceRoot??process.cwd()),await TO(J)}async function b9(f,$){let J=new URL(f),Q=$?.trim()||qH(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 yO(){let f=D0(),$=await P0(f.discoveryPath);if(!$?.url)return!1;try{if(await b9($.url,$.authToken))return!0}catch{}return!1}async function yH(f){if(!I9(f.url))return;let $=D0(),J=await P0($.discoveryPath);if(!J?.url||!MO(J.url,f.url))return;if(!await qO(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await yO())return;if(!await zO(J.url))return;return await $f($.discoveryPath).catch(()=>{return}),await S2({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}import{captureSdkError as wH,createSessionId as CH,HUB_CHECKPOINT_CAPABILITY as EO,HUB_COMPACTION_CAPABILITY as hO,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as bO,HUB_HOOK_CAPABILITY_PREFIX as kO,HUB_MISTAKE_LIMIT_CAPABILITY as IO,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as xO,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as gO,isHubToolExecutorName as mO}from"@cline/shared";function wO(f){return f?JSON.parse(JSON.stringify(f)):void 0}function CO(f){return f?JSON.parse(JSON.stringify(f)):void 0}function SO(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,Q=(Array.isArray($?.history)?$.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let H=typeof j.ref==="string"?j.ref.trim():"",X=Number(j.createdAt),A=Number(j.runCount);if(!H||!Number.isFinite(X)||!Number.isInteger(A))return[];return[{ref:H,createdAt:X,runCount:A,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=f?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function pf(f){let{session:$}=f,J=wO($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:CO(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...f.aggregateUsage?{aggregateUsage:{...f.aggregateUsage}}:{},...(()=>{let Q=SO(J);return Q?{checkpoint:Q}:{}})()}}function v9(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function D1(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var vO=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function SH(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function EH(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function hH(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function w$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function bH(f,$){let J={manifest:[],handlers:new Map};for(let Z of Object.keys($.toolExecutors??{}).filter(mO)){let W=$.toolExecutors?.[Z];if(typeof W!=="function")continue;w$(J,{kind:"toolExecutor",executor:Z,capabilityName:`${xO}${Z}`},async({payload:j,abortSignal:H})=>{let X=Array.isArray(j.args)?[...j.args]:[],A={...hH(j.context),signal:H};return{result:await W(...X,A)}})}for(let Z of f?.extraTools??[])w$(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:D1(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:D1(Z.lifecycle)}:{},capabilityName:`${bO}${Z.name}`},async({payload:W,abortSignal:j,progress:H})=>{let X={...hH(W.context),signal:j};return{result:await Z.execute(W.input,{...X,emitUpdate:(Y)=>{H({update:Y})}})}});let Q=f?.hooks;if(Q)for(let Z of vO){let W=Q[Z];if(typeof W!=="function")continue;w$(J,{kind:"hook",name:Z,capabilityName:`${kO}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if(f?.compaction?.compact){let Z=f.compaction.compact;w$(J,{kind:"compaction",capabilityName:hO,config:SH(f.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if(f?.checkpoint?.createCheckpoint){let Z=f.checkpoint.createCheckpoint;w$(J,{kind:"checkpoint",capabilityName:EO,config:SH(f.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if(f?.onConsecutiveMistakeLimitReached){let Z=f.onConsecutiveMistakeLimitReached;w$(J,{kind:"mistakeLimit",capabilityName:IO},async({payload:W})=>({result:await Z(W.context)}))}if(f?.userInstructionService){let Z=f.userInstructionService;w$(J,{kind:"userInstructionService",capabilityName:gO},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 gH(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message.trim()||void 0;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return}function cO(f){return gH(f)??"Capability request was cancelled."}function uO(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function dO(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function lO(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,Q=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function kH(f){if(!f)return;return{inputTokens:typeof f.inputTokens==="number"?f.inputTokens:0,outputTokens:typeof f.outputTokens==="number"?f.outputTokens:0,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 c9(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function rf(f,$){return c9(f?.[$])??0}function pO(f){let $=f?.delta&&typeof f.delta==="object"?f.delta:void 0,J=f?.totals&&typeof f.totals==="object"?f.totals:void 0,Q=f?.agent&&typeof f.agent==="object"?f.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:rf($,"inputTokens"),outputTokens:rf($,"outputTokens"),cacheReadTokens:rf($,"cacheReadTokens"),cacheWriteTokens:rf($,"cacheWriteTokens"),cost:c9($?.totalCost),totalInputTokens:rf(J,"inputTokens"),totalOutputTokens:rf(J,"outputTokens"),totalCacheReadTokens:rf(J,"cacheReadTokens"),totalCacheWriteTokens:rf(J,"cacheWriteTokens"),totalCost:c9(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function rO(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,Q=dO(J)?J:J==="failed"?"error":"completed",Z=lO(f?.usage??$?.usage);return{type:"done",reason:Q,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:Z}}function xJ(f,$){return f.error?.message??`hub command failed: ${$}`}function E2(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function mH(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:U0.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:E2(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:E2(f.status)==="completed"?0:E2(f.status)==="failed"?1:void 0,status:E2(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function nf(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function iO(f){let $=nf(f?.snapshot);if($)return v9($);let J=f?.session;return J?mH(J):void 0}function IH(f,$,J){let Q=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return N0.parse({version:1,session_id:f,source:$.source??U0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:E2(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:Q,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function xH(f,$){return N0.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class C${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new N2;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=R0(f.capabilities)??{},this.telemetry=f.telemetry,this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new Ff({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!NH(f,"session.create"))return!1;let $=await yH({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=bH(f.localRuntime,$),Q=f.config.sessionId?.trim()||CH(),Z=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:D1({...f.config,sessionId:Q}),metadata:{...f.sessionMetadata??{},source:f.source??U0.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:D1(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(Q,$,J.handlers);let W;try{W=await Z()}catch(A){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(Q,$,J.handlers);try{W=await Z()}catch(Y){throw this.cleanupPlannedSession(Q),Y}}else throw A}let j=nf(W.payload?.snapshot),H=W.payload?.session,X=(j?.sessionId??H?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(X!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(X,$,J.handlers);return{sessionId:X,manifest:j?xH(j,f):IH(X,f,H),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let Q=f.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?bH(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||CH():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 H;try{H=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??f.cwd,sessionConfig:D1({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??U0.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:D1(Q.toolPolicies)}:{}},$)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!H.ok){let K=typeof H.payload?.error==="string"?H.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let X=nf(H.payload?.snapshot),A=H.payload?.session,Y=(X?.sessionId??A?.sessionId)?.trim();if(J&&!Y){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(Y&&j&&Y!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(Y&&Z)this.sessionCapabilities.set(Y,Z);if(Y&&W.handlers.size>0)this.sessionClientContributionHandlers.set(Y,W.handlers);if(Y)this.ensureSessionSubscription(Y);let V=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,B=H.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:Y,startResult:Y?{sessionId:Y,manifest:X?xH(X,Q??{}):IH(Y,Q??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,mode:f.mode,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=nf($.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,H=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||H?{usage:j,aggregateUsage:H}:void 0}let Q=$.payload?.session,Z=kH(Q?.usage),W=kH(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:gH($)},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $;try{$=await this.client.command("session.get",void 0,f)}catch(J){if(O$(J))return;throw J}return iO($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((Z)=>{let W=nf(Z);return W?[v9(W)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(mH)}async listSettings(f){let $=await this.client.command("settings.list",EH(f));if(!$.ok)throw Error(xJ($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",EH(f));if(!$.ok)throw Error(xJ($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw wH(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(xJ(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:$,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(xJ(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return R0(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:rO(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,f)});return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,f)});return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=nf(f.payload?.snapshot),Q=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",Q=f.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"usage.updated":{let J=pO(f.payload);this.events.emit({type:"agent_event",payload:{sessionId:$,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=nf(f.payload?.snapshot),Q=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=nf(f.payload?.snapshot),Q=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:Q}}),J?.interactive===!0&&$0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:$,reason:Q,ts:f.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError(f,$,J){try{wH(this.telemetry,{component:"core",operation:f,error:$,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof f.payload?.requestId==="string"?f.payload.requestId:"",Z=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get($)?.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 ${$}.`},$).catch(()=>{});return}let j=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},H=new AbortController;this.activeCapabilityAbortControllers.set(Q,H);let X=(A)=>{this.client.command("capability.progress",{requestId:Q,payload:A},$).catch((Y)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",Y,f)})};try{let A=await W({payload:j,abortSignal:H.signal,progress:X});if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:A},$)}catch(A){if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:A instanceof Error?A.message:String(A)},$)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(cO(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",Z=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",W=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!Q||!Z||!W)return;let j=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},H=uO(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:$,toolCallId:Z,toolName:W,toolInput:H});let X=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:Z,toolName:W,input:H,policy:j})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:X.approved,reason:X.reason},$).catch(()=>{})}}class gJ extends C${constructor(f){super({url:R1(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}import{existsSync as nO,mkdirSync as aO}from"node:fs";import{join as tO}from"node:path";import{asBool as h2,asOptionalString as Jf,asString as Uf,ensureSessionSchema as sO,loadSqliteDb as oO,nowIso as mJ,toBoolInt as b2}from"@cline/shared/db";import{resolveDbDataDir as eO}from"@cline/shared/storage";class af{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??eO()}init(){this.getRawDb()}ensureSessionsDir(){if(!nO(this.sessionsDirPath))aO(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return tO(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=oO(this.sessionDbPath());return sO(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=mJ();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,M2($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,M2($.enableTools),M2($.enableSpawn),M2($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,M2($.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(CJ()),J.push($.sessionId),this.run(`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`,J)}updateStatus($,f,J){this.update({sessionId:$,status:f,endedAt:$0(f)?null:CJ(),exitCode:$0(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,
444
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,b2(f.interactive),f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,b2(f.enableTools),b2(f.enableSpawn),b2(f.enableTeams),f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,b2(f.isSubagent),f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"",f.hookPath??"",f.messagesPath??null,$])}update(f){let $=[],J=[];if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(f.metadata?JSON.stringify(f.metadata):null);if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId);if($.length===0)return;$.push("updated_at = ?"),J.push(mJ()),J.push(f.sessionId),this.run(`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`,J)}updateStatus(f,$,J){this.update({sessionId:f,status:$,endedAt:$0($)?null:mJ(),exitCode:$0($)?null:J??($==="failed"?1:0)})}get(f){let $=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:B$(f.session_id),source:B$(f.source),pid:Number(f.pid??0),startedAt:B$(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:B$(f.status),interactive:N2(f.interactive),provider:B$(f.provider),model:B$(f.model),cwd:B$(f.cwd),workspaceRoot:B$(f.workspace_root),teamName:$$(f.team_name),enableTools:N2(f.enable_tools),enableSpawn:N2(f.enable_spawn),enableTeams:N2(f.enable_teams),parentSessionId:$$(f.parent_session_id),parentAgentId:$$(f.parent_agent_id),agentId:$$(f.agent_id),conversationId:$$(f.conversation_id),isSubagent:N2(f.is_subagent),prompt:$$(f.prompt),metadata:(()=>{let J=$$(f.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:$$(f.hook_path),messagesPath:$$(f.messages_path),updatedAt:$$(f.updated_at)??CJ()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let W of f){let Z=this.get(B$(W.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}EJ();import{existsSync as cW,mkdirSync as Az,readFileSync as SH,renameSync as Yz,writeFileSync as Vz}from"node:fs";import{join as hH}from"node:path";import{resolveSessionDataDir as Bz}from"@cline/shared/storage";import{dirname as Hz}from"node:path";import{nanoid as Xz}from"nanoid";import{execFile as bO}from"node:child_process";import{promisify as kO}from"node:util";var IO=kO(bO);function qW($,f){$?.log(f,{severity:"warn"})}function xO($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,Z=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:Z}}async function q1($,f){let J=await IO("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function wW($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:W}=await q1($,["for-each-ref","--format=%(refname)",J]),Z=W.trim().split(`
450
- `).filter(Boolean);await Promise.allSettled(Z.map((Q)=>q1($,["update-ref","-d",Q])))}catch{}}async function DH($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((W)=>q1($,["update-ref",`refs/cline/checkpoints/${f}/${W.runCount}`,W.ref])))}function mO($,f){let J=$.findIndex((W)=>W.runCount===f.runCount);if(J<0)return[...$,f];return $.map((W,Z)=>Z===J?f:W)}function LH($){let f=$.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await q1($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await W())return;let Q=async(A)=>{try{let V=(await q1($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!V)return;return{ref:V,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(Y){qW($.logger,`${A}: ${Y instanceof Error?Y.message:String(Y)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,H="";try{H=(await q1($.cwd,["stash","create",j])).stdout.trim()}catch(A){return qW($.logger,`Checkpoint snapshot failed: ${A instanceof Error?A.message:String(A)}`),Q("Checkpoint HEAD fallback failed")}if(!H)return Q("Checkpoint HEAD fallback failed");let X=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await q1($.cwd,["update-ref",X,H])}catch(A){qW($.logger,`Checkpoint store failed: ${A instanceof Error?A.message:String(A)}`);return}return{ref:H,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||f<1)return;let j=await Z();if(!j)return;let H=await $.readSessionMetadata(),X=xO(H);if(X?.latest.ref===j.ref)return;let A=mO(X?.history??[],j);await $.writeSessionMetadata({...H??{},checkpoint:{latest:j,history:A}});return}}}import{existsSync as kJ,mkdirSync as gO,readdirSync as vO,rmdirSync as uO,rmSync as cO,unlinkSync as dO}from"node:fs";import{dirname as OH,join as bJ}from"node:path";function n(){return new Date().toISOString()}function y2($){if(!$||!kJ($))return;try{dO($)}catch{}}function lO($){let f=P2($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=_J($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class SW{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return bJ(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!kJ(f))gO(f,{recursive:!0});return f}sessionMessagesPath($){return bJ(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return bJ(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!kJ(f)){f=OH(f);continue}try{if(vO(f).length>0)break;uO(f)}catch{break}f=OH(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!kJ($))return;try{cO($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:W,fileStem:Z}=lO($),Q=this.sessionArtifactsDir(W);return{messagesPath:bJ(Q,`${Z}.messages.json`)}}}import{appendFileSync as pO,existsSync as rO,mkdirSync as zH,readFileSync as iO,writeFileSync as _H}from"node:fs";import{dirname as TH,join as nO}from"node:path";import{ensureHookLogDir as aO}from"@cline/shared/storage";class hW{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new SW(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){wj(f,J,AW($))}writeSessionManifest($,f){zH(TH($),{recursive:!0}),_H($,`${JSON.stringify(_0.parse(f),null,2)}
451
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!rO(f))return{path:f};try{return{path:f,manifest:_0.parse(JSON.parse(iO(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let W=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=YW({updatedAt:n(),context:AW($),messages:f,systemPrompt:J}),Q=`${JSON.stringify(Z,null,2)}
452
- `;if(zH(TH(W),{recursive:!0}),_H(W,Q,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:W,contents:Q,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,W,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??nO(aO(),"hooks.jsonl");pO(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:W,sessionId:f,pid:J,source:Z})}
453
- `,"utf8")}}import{appendFileSync as tO}from"node:fs";import{join as sO}from"node:path";import{resolveRootSessionId as NH}from"@cline/shared";import{ensureHookLogDir as oO}from"@cline/shared/storage";import{z as CW}from"zod";var eO="subagent",$z=CW.looseObject({task:CW.string().optional(),systemPrompt:CW.string().optional()});class IJ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,W){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:eO,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:F2({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=NH($.sessionContext);if(!f)return;let J=$z.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let W=zJ(f,$.agentId),Z=await this.adapter.getSession(W),Q=n(),j=this.manifestStore.artifacts.subagentArtifactPaths(W,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),H=$.prompt??Z?.prompt??void 0;if(!H)H=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:H,startedAt:Q,...j})),this.manifestStore.initializeMessagesFile(W,j.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??H??null,metadata:F2({metadata:Z.metadata??void 0,prompt:Z.prompt??H??null}),expectedStatusLock:Z.statusLock}),W}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=NH($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=zJ(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($,QW(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let W=$0(f)?null:n(),Z=$0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:W,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,f)}async onTeamTaskStart($,f,J){let W=await this.adapter.getSession($);if(!W)return;let Z=ZW($,f),Q=n(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:Q,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,Q);let H=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(H)??[];X.push(Z),this.teamTaskSessionsByAgent.set(H,X)}async onTeamTaskEnd($,f,J,W,Z,Q){let j=this.teamTaskQueueKey($,f),H=this.teamTaskSessionsByAgent.get(j);if(!H||H.length===0)return;let X=H.shift();if(H.length===0)this.teamTaskSessionsByAgent.delete(j);if(!X)return;let A=Z?.messages??Q,Y=this.toPersistedMessages(A,Z,Q);if(Y)await this.manifestStore.persistSessionMessages(X,Y);await this.applySubagentStatusBySessionId(X,J),this.teamTaskLastHeartbeatBySession.delete(X),this.teamTaskLastProgressLineBySession.delete(X)}async onTeamTaskProgress($,f,J,W){let Z=this.teamTaskQueueKey($,f),Q=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!Q)return;let j=J.trim();if(!j)return;let H=W?.kind??"progress";if(H==="heartbeat"){let A=Date.now(),Y=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(A-Y<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,A)}let X=H==="heartbeat"?"[progress] heartbeat":H==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(Q)===X)return;this.teamTaskLastProgressLineBySession.set(Q,X)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(W)await this.manifestStore.persistSessionMessages(J,W);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??sO(oO(),"hooks.jsonl");tO(J,`${JSON.stringify({ts:n(),...$})}
454
- `,"utf8")}}import{formatUserInputBlock as jz}from"@cline/shared";function f$(){return new Date().toISOString()}function MH($,f){if(f<=0)return 0;return Math.round($/f*100)}function fz($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let W=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let Q of Z.requiredSections)if(!J.has(`${Z.id}:${Q}`))W.add(`${Z.id}:${Q}`)}return[...W].sort((Z,Q)=>Z.localeCompare(Q))}function xJ($,f){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},H=0,X=0;for(let P of f.members)if(J[P.status]+=1,P.role==="lead")H+=1;else X+=1;let A=[],Y=[],V=f.tasks.filter((P)=>P.status==="completed").length,B=new Map(f.tasks.map((P)=>[P.id,P]));for(let P of f.tasks){if(W[P.status]+=1,P.status==="blocked"){A.push(P.id);continue}if(P.status!=="pending")continue;if(P.dependsOn.every((F)=>{return B.get(F)?.status==="completed"}))Y.push(P.id)}let K=[],G,R=0;for(let P of f.runs){if(Z[P.status]+=1,P.status==="queued"||P.status==="running")K.push(P.id);let U=P.startedAt.getTime();if(U>=R)R=U,G=P.id}for(let P of f.outcomes)Q[P.status]+=1;for(let P of f.outcomeFragments)j[P.status]+=1;return{teamName:$,updatedAt:f$(),members:{total:f.members.length,byStatus:J,leadCount:H,teammateCount:X},tasks:{total:f.tasks.length,byStatus:W,blockedTaskIds:A,readyTaskIds:Y,completionPct:MH(V,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:Q,finalizedPct:MH(Q.finalized,f.outcomes.length),missingRequiredSections:fz(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function mJ($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:f$(),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:f$(),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:f$(),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:f$(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:f$(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:f$(),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:f$(),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:f$(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:f$()}}import{sanitizeFileName as Jz,TeamMessageType as h}from"@cline/shared";import{nanoid as Wz}from"nanoid";import{TeamMessageType as Yx}from"@cline/shared";function EW($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function yH($,f){return $?.status==="stopped"&&EW(f)}var Zz=600000,qH="recovered_queued";function Qz($){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 bW{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,W]of Object.entries($))this.addAgent(J,W)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:h.AgentEvent,agentId:$,event:Z})}},W=new h$(J);if(J.onEvent)W.subscribeEvents(J.onEvent);this.agents.set($,W),this.configs.set($,f)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:h.TaskStart,agentId:$,message:f});try{let W=await J.run(f);return this.emitEvent({type:h.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:h.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:h.TaskStart,agentId:$,message:f});try{let W=await J.continue(f);return this.emitEvent({type:h.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:h.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async runParallel($){let f=$.map(async(J)=>{let W=this.agents.get(J.agentId);if(!W)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:h.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);return this.emitEvent({type:h.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:h.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let W=this.agents.get(J.agentId);if(!W){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:h.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);this.emitEvent({type:h.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:h.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return f}async runPipeline($,f,J){let W=[],Z=f;for(let Q of $){let j=this.agents.get(Q);if(!j){W.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:h.TaskStart,agentId:Q,message:Z});try{let H=await j.run(Z);this.emitEvent({type:h.TaskEnd,agentId:Q,result:H}),W.push({agentId:Q,result:H});let X=$.indexOf(Q)+1;if(X<$.length){let A=$[X];Z=J?J(H,A):`Previous agent output:
449
+ FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:Uf($.session_id),source:Uf($.source),pid:Number($.pid??0),startedAt:Uf($.started_at),endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:Uf($.status),interactive:h2($.interactive),provider:Uf($.provider),model:Uf($.model),cwd:Uf($.cwd),workspaceRoot:Uf($.workspace_root),teamName:Jf($.team_name),enableTools:h2($.enable_tools),enableSpawn:h2($.enable_spawn),enableTeams:h2($.enable_teams),parentSessionId:Jf($.parent_session_id),parentAgentId:Jf($.parent_agent_id),agentId:Jf($.agent_id),conversationId:Jf($.conversation_id),isSubagent:h2($.is_subagent),prompt:Jf($.prompt),metadata:(()=>{let J=Jf($.metadata_json);if(!J)return;try{let Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:Jf($.hook_path),messagesPath:Jf($.messages_path),updatedAt:Jf($.updated_at)??mJ()}}list(f=200){let $=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[f]),J=[];for(let Q of $){let Z=this.get(Uf(Q.session_id));if(Z)J.push(Z)}return J}delete(f,$=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}}vJ();import{existsSync as jQ,mkdirSync as JT,readFileSync as JX,renameSync as QT,writeFileSync as ZT}from"node:fs";import{join as QX}from"node:path";import{resolveSessionDataDir as WT}from"@cline/shared/storage";import{dirname as fT}from"node:path";import{nanoid as $T}from"nanoid";import{execFile as B_}from"node:child_process";import{promisify as K_}from"node:util";var P_=K_(B_);function u9(f,$){f?.log($,{severity:"warn"})}function G_(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;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 E$(f,$){let J=await P_("git",["-C",f,...$],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function d9(f,$){if(!f)return;let J=`refs/cline/checkpoints/${$}/`;try{let{stdout:Q}=await E$(f,["for-each-ref","--format=%(refname)",J]),Z=Q.trim().split(`
450
+ `).filter(Boolean);await Promise.allSettled(Z.map((W)=>E$(f,["update-ref","-d",W])))}catch{}}async function vH(f,$,J){if(!f||J.length===0)return;await Promise.allSettled(J.map((Q)=>E$(f,["update-ref",`refs/cline/checkpoints/${$}/${Q.runCount}`,Q.ref])))}function F_(f,$){let J=f.findIndex((Q)=>Q.runCount===$.runCount);if(J<0)return[...f,$];return f.map((Q,Z)=>Z===J?$:Q)}function cH(f){let $=f.initialRunCount??0,J,Q=async()=>{if(J!==void 0)return J;try{J=(await E$(f.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if(f.createCheckpoint)return await f.createCheckpoint({cwd:f.cwd,sessionId:f.sessionId,runCount:$});if(!await Q())return;let W=async(A)=>{try{let V=(await E$(f.cwd,["rev-parse","HEAD"])).stdout.trim();if(!V)return;return{ref:V,createdAt:Date.now(),runCount:$,kind:"commit"}}catch(Y){u9(f.logger,`${A}: ${Y instanceof Error?Y.message:String(Y)}`);return}},j=`cline checkpoint session=${f.sessionId} run=${$}`,H="";try{H=(await E$(f.cwd,["stash","create",j])).stdout.trim()}catch(A){return u9(f.logger,`Checkpoint snapshot failed: ${A instanceof Error?A.message:String(A)}`),W("Checkpoint HEAD fallback failed")}if(!H)return W("Checkpoint HEAD fallback failed");let X=`refs/cline/checkpoints/${f.sessionId}/${$}`;try{await E$(f.cwd,["update-ref",X,H])}catch(A){u9(f.logger,`Checkpoint store failed: ${A instanceof Error?A.message:String(A)}`);return}return{ref:H,createdAt:Date.now(),runCount:$,kind:"stash"}};return{beforeRun:async({snapshot:W})=>{if(W.parentAgentId!=null)return;$+=1;return},beforeModel:async({snapshot:W})=>{if(W.parentAgentId!=null||W.iteration!==1||$<1)return;let j=await Z();if(!j)return;let H=await f.readSessionMetadata(),X=G_(H);if(X?.latest.ref===j.ref)return;let A=F_(X?.history??[],j);await f.writeSessionMetadata({...H??{},checkpoint:{latest:j,history:A}});return}}}import{existsSync as uJ,mkdirSync as U_,readdirSync as R_,rmdirSync as D_,rmSync as L_,unlinkSync as O_}from"node:fs";import{dirname as uH,join as cJ}from"node:path";function n(){return new Date().toISOString()}function k2(f){if(!f||!uJ(f))return;try{O_(f)}catch{}}function __(f){let $=T2(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=CJ(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class l9{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return cJ(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!uJ($))U_($,{recursive:!0});return $}sessionMessagesPath(f){return cJ(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return cJ(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!uJ($)){$=uH($);continue}try{if(R_($).length>0)break;D_($)}catch{break}$=uH($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!uJ(f))return;try{L_(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:Q,fileStem:Z}=__(f),W=this.sessionArtifactsDir(Q);return{messagesPath:cJ(W,`${Z}.messages.json`)}}}import{appendFileSync as T_,existsSync as z_,mkdirSync as dH,readFileSync as M_,writeFileSync as lH}from"node:fs";import{dirname as pH,join as N_}from"node:path";import{ensureHookLogDir as q_}from"@cline/shared/storage";class p9{adapter;messagesArtifactUploader;logger;artifacts;constructor(f,$,J){this.adapter=f;this.messagesArtifactUploader=$;this.logger=J;this.artifacts=new l9(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile(f,$,J){tj($,J,T9(f))}writeSessionManifest(f,$){dH(pH(f),{recursive:!0}),lH(f,`${JSON.stringify(N0.parse($),null,2)}
451
+ `,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!z_($))return{path:$};try{return{path:$,manifest:N0.parse(JSON.parse(M_($,"utf8")))}}catch{return{path:$}}}async resolveArtifactPath(f,$,J){let Z=(await this.adapter.getSession(f))?.[$];return typeof Z==="string"&&Z.trim().length>0?Z:J(f)}async persistSessionMessages(f,$,J){let Q=await this.resolveArtifactPath(f,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=z9({updatedAt:n(),context:T9(f),messages:$,systemPrompt:J}),W=`${JSON.stringify(Z,null,2)}
452
+ `;if(dH(pH(Q),{recursive:!0}),lH(Q,W,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession(f);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:f,path:Q,contents:W,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:f,error:j})}}appendStaleSessionHookLog(f,$,J,Q,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??N_(q_(),"hooks.jsonl");T_(j,`${JSON.stringify({ts:f,hookName:"session_shutdown",reason:Q,sessionId:$,pid:J,source:Z})}
453
+ `,"utf8")}}import{appendFileSync as y_}from"node:fs";import{join as w_}from"node:path";import{resolveRootSessionId as rH}from"@cline/shared";import{ensureHookLogDir as C_}from"@cline/shared/storage";import{z as r9}from"zod";var S_="subagent",E_=r9.looseObject({task:r9.string().optional(),systemPrompt:r9.string().optional()});class dJ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(f,$,J,Q){this.adapter=f;this.manifestStore=$;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:$.sessionId,source:S_,pid:process.ppid,startedAt:$.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId??null,isSubagent:!0,prompt:$.prompt,metadata:M2({prompt:$.prompt}),hookPath:"",messagesPath:$.messagesPath,updatedAt:$.startedAt}}async queueSpawnRequest(f){if(f.hookName!=="tool_call"||f.parent_agent_id!==null)return;if(f.tool_call?.name!=="spawn_agent")return;let $=rH(f.sessionContext);if(!$)return;let J=E_.safeParse(f.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:$,parentAgentId:f.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession(f){let $=f.rootSessionId;if(!$)return;let J=await this.adapter.getSession($);if(!J)return;let Q=wJ($,f.agentId),Z=await this.adapter.getSession(Q),W=n(),j=this.manifestStore.artifacts.subagentArtifactPaths(Q,f.agentId,this.activeTeamTaskSessionId($,f.parentAgentId)),H=f.prompt??Z?.prompt??void 0;if(!H)H=await this.adapter.claimSpawnRequest($,f.parentAgentId)??`Subagent run by ${f.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:Q,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:H,startedAt:W,...j})),this.manifestStore.initializeMessagesFile(Q,j.messagesPath,W),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:Z.prompt??H??null,metadata:M2({metadata:Z.metadata??void 0,prompt:Z.prompt??H??null}),expectedStatusLock:Z.statusLock}),Q}async upsertSubagentSessionFromHook(f){if(!f.parent_agent_id)return;let $=rH(f.sessionContext);if(!$)return;if(f.hookName==="session_shutdown"){let J=wJ($,f.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:f.agent_id,parentAgentId:f.parent_agent_id,conversationId:f.taskId,rootSessionId:$})}async applySubagentStatus(f,$){await this.applySubagentStatusBySessionId(f,D9($))}async applySubagentStatusBySessionId(f,$){let J=await this.adapter.getSession(f);if(!J)return;let Q=$0($)?null:n(),Z=$0($)?null:$==="failed"?1:0;await this.adapter.updateSession({sessionId:f,status:$,endedAt:Q,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions(f,$){if(!f)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:f,status:"running"});for(let Q of J)await this.applySubagentStatusBySessionId(Q.sessionId,$)}async onTeamTaskStart(f,$,J){let Q=await this.adapter.getSession(f);if(!Q)return;let Z=R9(f,$),W=n(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,$);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:f,parentAgentId:"lead",agentId:$,prompt:J||`Team task for ${$}`,startedAt:W,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,W);let H=this.teamTaskQueueKey(f,$),X=this.teamTaskSessionsByAgent.get(H)??[];X.push(Z),this.teamTaskSessionsByAgent.set(H,X)}async onTeamTaskEnd(f,$,J,Q,Z,W){let j=this.teamTaskQueueKey(f,$),H=this.teamTaskSessionsByAgent.get(j);if(!H||H.length===0)return;let X=H.shift();if(H.length===0)this.teamTaskSessionsByAgent.delete(j);if(!X)return;let A=Z?.messages??W,Y=this.toPersistedMessages(A,Z,W);if(Y)await this.manifestStore.persistSessionMessages(X,Y);await this.applySubagentStatusBySessionId(X,J),this.teamTaskLastHeartbeatBySession.delete(X),this.teamTaskLastProgressLineBySession.delete(X)}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 H=Q?.kind??"progress";if(H==="heartbeat"){let A=Date.now(),Y=this.teamTaskLastHeartbeatBySession.get(W)??0;if(A-Y<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(W,A)}let X=H==="heartbeat"?"[progress] heartbeat":H==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(W)===X)return;this.teamTaskLastProgressLineBySession.set(W,X)}async handleSubAgentStart(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;if($.error){await this.applySubagentStatusBySessionId(J,"failed");return}let Q=this.toPersistedMessages($.agentResult?.messages,$.agentResult);if(Q)await this.manifestStore.persistSessionMessages(J,Q);let Z=$.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(f){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??w_(C_(),"hooks.jsonl");y_(J,`${JSON.stringify({ts:n(),...f})}
454
+ `,"utf8")}}import{formatUserInputBlock as e_}from"@cline/shared";import{existsSync as h_,readdirSync as b_,readFileSync as k_}from"node:fs";import{basename as iH,extname as I_,join as x_}from"node:path";import{resolveAgentConfigSearchPaths as g_}from"@cline/shared/storage";import aH from"yaml";import{z as L0}from"zod";var tH=L0.object({name:L0.string().trim().min(1),description:L0.string().trim().min(1),tools:L0.union([L0.string(),L0.array(L0.string())]).optional(),skills:L0.union([L0.string(),L0.array(L0.string())]).optional(),providerId:L0.string().trim().min(1).optional(),modelId:L0.string().trim().min(1).optional(),maxIterations:L0.number().int().positive().optional()});function m_(f){let $=f.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!$)throw Error("Missing YAML frontmatter block in agent config file.");let J=$[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=J;let Z,W=Array.from(f.matchAll(Q)).filter((j)=>j.index>=J);for(let j of W){let H=j.index,X=f.slice(J,H);try{let A=aH.parse(X);if(!A||typeof A!=="object"||Array.isArray(A))continue;tH.parse(A);let Y=f.slice(H+j[0].length);Z={frontmatter:X,body:Y}}catch{}}if(Z)return Z;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function nH(f){if(f===void 0)return;let $=Array.isArray(f)?f:f.split(",");return Array.from(new Set($.map((J)=>J.trim()).filter((J)=>J.length>0)))}function v_(f){return f.trim().toLowerCase()}function c_(f){let $=I_(f).toLowerCase();return $===".yml"||$===".yaml"}function i9(f,$={}){let{frontmatter:J,body:Q}=m_(f),Z=aH.parse(J);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Agent config frontmatter must be a YAML mapping.");let W=tH.parse(Z),j=Q.trim();if(!j)throw Error("Missing system prompt body in agent config file.");return{name:W.name,description:W.description,tools:nH(W.tools),skills:nH(W.skills),providerId:W.providerId,modelId:W.modelId,maxIterations:W.maxIterations,systemPrompt:j,path:$.path}}function lJ(f){let $=f.searchPaths??g_(f.workspaceRoot),J=new Map,Q=[];for(let W of $.filter(Boolean)){if(!h_(W))continue;let j;try{j=b_(W,{withFileTypes:!0})}catch(H){Q.push({path:W,error:H instanceof Error?H:Error(String(H))});continue}for(let H of j){if(!H.isFile()||!c_(H.name))continue;let X=x_(W,H.name);try{let A=k_(X,"utf8"),Y=i9(A,{path:X}),V=v_(Y.name);if(!J.has(V))J.set(V,Y)}catch(A){Q.push({path:X,error:A instanceof Error?A:Error(String(A))})}}}return{configs:Array.from(J.values()).sort((W,j)=>(W.path?iH(W.path):W.name).localeCompare(j.path?iH(j.path):j.name)),errors:Q}}import{createTool as u_,zodToJsonSchema as d_}from"@cline/shared";import{z as sH}from"zod";var n9="subagent_",pJ=64,l_=sH.object({prompt:sH.string().trim().min(1).describe("Task for the subagent to perform")});function p_(f){let $="",J=!0;for(let Q of f.trim().toLowerCase()){let Z=Q.charCodeAt(0);if(!(Z>=97&&Z<=122||Z>=48&&Z<=57||Q==="_")||Q==="_"){if(!J)$+="_",J=!0;continue}$+=Q,J=!1}return J?$.slice(0,-1):$}function r_(f){let $=2166136261;for(let J=0;J<f.length;J++)$^=f.charCodeAt(J),$=Math.imul($,16777619);return($>>>0).toString(36)}function a9(f){let $=p_(f)||"agent",J=r_(f).slice(0,6),Q=`${n9}${$}`;if(Q.length<=pJ)return Q;let Z=pJ-n9.length-J.length-1,W=$.slice(0,Math.max(1,Z));return`${n9}${W}_${J}`.slice(0,pJ)}function t9(f){let $=new Set,J=[];for(let Q of[...f].sort((Z,W)=>Z.name.localeCompare(W.name))){let Z=a9(Q.name),W=Z,j=2;while($.has(W)){let H=`_${j++}`,X=Math.max(1,pJ-H.length);W=`${Z.slice(0,X)}${H}`}$.add(W),J.push({toolName:W,config:Q})}return J}function i_(f,$){return{...f,providerId:$.providerId??f.providerId,modelId:$.modelId??f.modelId,maxIterations:$.maxIterations??f.maxIterations}}function rJ(f){return t9(f.agents).map(({toolName:$,config:J})=>{return u_({name:$,description:`Use the "${J.name}" subagent: ${J.description}`,inputSchema:d_(l_),execute:async(Z,W)=>{let j=f.configProvider.getRuntimeConfig(),H=A1(i_(j,J)),X=f.createSubAgentTools?await f.createSubAgentTools(J,Z,W):[],A=Y1({kind:"subagent",prompt:J.systemPrompt,configProvider:H,tools:X,maxIterations:J.maxIterations,parentAgentId:W.agentId,abortSignal:W.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),Y=A.getAgentId(),V=A.getConversationId(),B=W.agentId,K={systemPrompt:J.systemPrompt,task:Z.prompt};if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:Y,conversationId:V,parentAgentId:B,input:K})}catch{}try{let P=await A.run(Z.prompt),R={text:P.text,iterations:P.iterations,finishReason:P.finishReason,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Y,conversationId:V,parentAgentId:B,input:K,result:R,agentResult:P})}catch{}return R}catch(P){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Y,conversationId:V,parentAgentId:B,input:K,error:P instanceof Error?P:Error(String(P))})}catch{}throw P}},timeoutMs:300000,retryable:!1})})}function Qf(){return new Date().toISOString()}function oH(f,$){if($<=0)return 0;return Math.round(f/$*100)}function n_(f,$){let J=new Set;for(let Z of $)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let Q=new Set;for(let Z of f){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 iJ(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},H=0,X=0;for(let G of $.members)if(J[G.status]+=1,G.role==="lead")H+=1;else X+=1;let A=[],Y=[],V=$.tasks.filter((G)=>G.status==="completed").length,B=new Map($.tasks.map((G)=>[G.id,G]));for(let G of $.tasks){if(Q[G.status]+=1,G.status==="blocked"){A.push(G.id);continue}if(G.status!=="pending")continue;if(G.dependsOn.every((U)=>{return B.get(U)?.status==="completed"}))Y.push(G.id)}let K=[],P,R=0;for(let G of $.runs){if(Z[G.status]+=1,G.status==="queued"||G.status==="running")K.push(G.id);let F=G.startedAt.getTime();if(F>=R)R=F,P=G.id}for(let G of $.outcomes)W[G.status]+=1;for(let G of $.outcomeFragments)j[G.status]+=1;return{teamName:f,updatedAt:Qf(),members:{total:$.members.length,byStatus:J,leadCount:H,teammateCount:X},tasks:{total:$.tasks.length,byStatus:Q,blockedTaskIds:A,readyTaskIds:Y,completionPct:oH(V,$.tasks.length)},runs:{total:$.runs.length,byStatus:Z,activeRunIds:K,latestRunId:P},outcomes:{total:$.outcomes.length,byStatus:W,finalizedPct:oH(W.finalized,$.outcomes.length),missingRequiredSections:n_($.outcomes,$.outcomeFragments)},fragments:{total:$.outcomeFragments.length,byStatus:j}}}function nJ(f){let{event:$}=f;switch($.type){case"team_task_updated":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),taskId:$.task.id,agentId:$.task.assignee??$.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.run.error};case"run_progress":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.message};case"outcome_created":case"outcome_finalized":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),outcomeId:$.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),outcomeId:$.fragment.outcomeId,fragmentId:$.fragment.id,agentId:$.fragment.sourceAgentId};case"team_message":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),taskId:$.message.taskId,agentId:$.message.fromAgentId,message:$.message.subject};case"team_mission_log":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),taskId:$.entry.taskId,agentId:$.entry.agentId,message:$.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf(),agentId:$.agentId}}return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Qf()}}import{sanitizeFileName as a_,TeamMessageType as E}from"@cline/shared";import{nanoid as t_}from"nanoid";import{TeamMessageType as Bg}from"@cline/shared";function s9(f){if(typeof DOMException<"u"&&f instanceof DOMException&&f.name==="AbortError")return!0;if(!(f instanceof Error))return!1;return f.name==="AbortError"||f.message.toLowerCase().includes("aborted")}function eH(f,$){return f?.status==="stopped"&&s9($)}var s_=600000,fX="recovered_queued";function o_(f){return`This is an automatic recovery of interrupted team run ${f.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
+ ${f.message}`}class o9{agents=new Map;configs=new Map;onTeamEvent;constructor(f,$){if(this.onTeamEvent=$,f)for(let[J,Q]of Object.entries(f))this.addAgent(J,Q)}addAgent(f,$){if(this.agents.has(f))throw Error(`Agent with id "${f}" already exists in the team`);let J={...$,onEvent:(Z)=>{$.onEvent?.(Z),this.emitEvent({type:E.AgentEvent,agentId:f,event:Z})}},Q=new If(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);this.agents.set(f,Q),this.configs.set(f,$)}removeAgent(f){return this.configs.delete(f),this.agents.delete(f)}getAgent(f){return this.agents.get(f)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:E.TaskStart,agentId:f,message:$});try{let Q=await J.run($);return this.emitEvent({type:E.TaskEnd,agentId:f,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:E.TaskEnd,agentId:f,error:Z,messages:J.getMessages()}),Q}}async continueTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:E.TaskStart,agentId:f,message:$});try{let Q=await J.continue($);return this.emitEvent({type:E.TaskEnd,agentId:f,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:E.TaskEnd,agentId:f,error:Z,messages:J.getMessages()}),Q}}async runParallel(f){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:E.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);return this.emitEvent({type:E.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:E.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),{agentId:J.agentId,result:void 0,error:W,metadata:J.metadata}}});return Promise.all($)}async runSequential(f){let $=[];for(let J of f){let Q=this.agents.get(J.agentId);if(!Q){$.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:E.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);this.emitEvent({type:E.TaskEnd,agentId:J.agentId,result:Z}),$.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:E.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),$.push({agentId:J.agentId,result:void 0,error:W,metadata:J.metadata})}}return $}async runPipeline(f,$,J){let Q=[],Z=$;for(let W of f){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:E.TaskStart,agentId:W,message:Z});try{let H=await j.run(Z);this.emitEvent({type:E.TaskEnd,agentId:W,result:H}),Q.push({agentId:W,result:H});let X=f.indexOf(W)+1;if(X<f.length){let A=f[X];Z=J?J(H,A):`Previous agent output:
457
457
  ${H.text}
458
458
 
459
- Please continue from here.`}}catch(H){let X=H instanceof Error?H:Error(String(H));this.emitEvent({type:h.TaskEnd,agentId:Q,error:X,messages:j.getMessages()}),W.push({agentId:Q,result:void 0,error:X});break}}return W}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}class q2{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_${Jz(Wz(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,W=f?.markRead??!0,Z=f?.limit,Q=this.mailbox.filter((H)=>H.toAgentId===$&&(!J||!H.readAt)),j=typeof Z==="number"&&Z>0?Q.slice(Math.max(0,Q.length-Z)):Q;if(W){let H=new Date;for(let X of j)if(!X.readAt)X.readAt=H}return j.map((H)=>({...H}))}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,Bf($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,Bf($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,Bf($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,Bf(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,Bf(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,Bf(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let W={...f,apiTimeoutMs:Zz,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let H=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,H},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:h.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new h$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);let Q={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,Q),this.emitEvent({type:h.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(W){if(!EW(W))throw W}J.status="stopped",this.emitEvent({type:h.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,W),this.emitEvent({type:h.TeamTaskUpdated,task:{...W}}),{...W}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:h.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let W=this.requireTask($);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:h.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...W}}completeTask($,f,J){let W=this.requireTask($);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=f;return this.emitEvent({type:h.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...W}}async routeToTeammate($,f,J){let W=this.members.get($);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${$}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:h.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),Q=Z.length>0?`${this.buildMailboxNotification(Z)}
459
+ Please continue from here.`}}catch(H){let X=H instanceof Error?H:Error(String(H));this.emitEvent({type:E.TaskEnd,agentId:W,error:X,messages:j.getMessages()}),Q.push({agentId:W,result:void 0,error:X});break}}return Q}abortAll(){for(let f of this.agents.values())f.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}class I2{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(f){this.teamName=f.teamName,this.teamId=`t_${a_(t_(10))}`,this.onTeamEvent=f.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,f.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,f.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,f.maxConcurrentRuns??2);let $=f.leadAgentId??"lead";this.members.set($,{agentId:$,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(f){return this.members.get(f)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((f)=>f.role==="teammate").map((f)=>f.agentId)}getTask(f){return this.tasks.get(f)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(f){return Array.from(this.tasks.values()).map(($)=>{let J=this.getUnresolvedDependencies($);return{...$,blockedBy:J,isReady:$.status==="pending"&&!$.assignee&&J.length===0}}).filter(($)=>{if(f?.status&&$.status!==f.status)return!1;if(f?.assignee&&$.assignee!==f.assignee)return!1;return!0})}listMissionLog(f){if(!f||f<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-f))}listMailbox(f,$){let J=$?.unreadOnly??!0,Q=$?.markRead??!0,Z=$?.limit,W=this.mailbox.filter((H)=>H.toAgentId===f&&(!J||!H.readAt)),j=typeof Z==="number"&&Z>0?W.slice(Math.max(0,W.length-Z)):W;if(Q){let H=new Date;for(let X of j)if(!X.readAt)X.readAt=H}return j.map((H)=>({...H}))}getSnapshot(){let f={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())f[J.status]++;let $={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())$[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:f,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:$}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((f)=>({agentId:f.agentId,role:f.role,description:f.description,status:f.status})),tasks:Array.from(this.tasks.values()).map((f)=>({...f})),mailbox:this.mailbox.map((f)=>({...f})),missionLog:this.missionLog.map((f)=>({...f})),runs:Array.from(this.runs.values()).map((f)=>({...f})),outcomes:Array.from(this.outcomes.values()).map((f)=>({...f})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((f)=>({...f}))}}hydrateState(f){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of f.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...f.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...f.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of f.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 f.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of f.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let $=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of $)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of f.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,L1(f.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,L1(f.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,L1(f.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,L1((f.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,L1((f.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,L1((f.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive(f){let $=this.members.get(f);return!!$&&$.role==="teammate"&&!!$.agent}spawnTeammate({agentId:f,config:$}){let J=this.members.get(f);if(J&&J.role!=="teammate")throw Error(`Team member "${f}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${f}" is currently running and cannot be respawned`);let Q={...$,apiTimeoutMs:s_,consumePendingUserMessage:()=>{let j=this.members.get(f);if(!j||!j.pendingSteerMessage)return;let H=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,H},onEvent:(j)=>{$.onEvent?.(j),this.emitEvent({type:E.AgentEvent,agentId:f,event:j}),this.trackMeaningfulEvent(f,j)}},Z=new If(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);let W={agentId:f,role:"teammate",description:$.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set(f,W),this.emitEvent({type:E.TeammateSpawned,agentId:f,role:$.role,teammate:{rolePrompt:$.systemPrompt,modelId:$.modelId,maxIterations:$.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(f);if(!J||J.role!=="teammate")throw Error(`Teammate "${f}" was not found`);try{J.agent?.abort()}catch(Q){if(!s9(Q))throw Q}J.status="stopped",this.emitEvent({type:E.TeammateShutdown,agentId:f,reason:$})}updateTeammateConnections(f){for(let $ of this.members.values()){if($.role!=="teammate"||!$.agent)continue;$.agent.updateConnection(f)}}createTask(f){let $=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,Q={id:$,title:f.title,description:f.description,status:f.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:f.createdBy,assignee:f.assignee,dependsOn:f.dependsOn??[]};return this.tasks.set($,Q),this.emitEvent({type:E.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask(f,$){let J=this.requireTask(f);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=$,J.updatedAt=new Date,this.emitEvent({type:E.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:$,taskId:f,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask(f,$,J){let Q=this.requireTask(f);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=J,this.emitEvent({type:E.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:$,taskId:f,kind:"blocked",summary:J}),{...Q}}completeTask(f,$,J){let Q=this.requireTask(f);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=J,!Q.assignee)Q.assignee=$;return this.emitEvent({type:E.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:$,taskId:f,kind:"done",summary:J}),{...Q}}async routeToTeammate(f,$,J){let Q=this.members.get(f);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${f}" 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:E.TaskStart,agentId:f,message:$});try{let Z=this.listMailbox(f,{unreadOnly:!0,markRead:!0}),W=Z.length>0?`${this.buildMailboxNotification(Z)}
460
460
 
461
- ${f}`:f,j=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:h.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:h.TaskEnd,agentId:$,error:Q,messages:W.agent.getMessages()}),!yH(W,Q))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get($)?.status!=="stopped")W.status="idle"}}startTeammateRun($,f,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:W,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,Z),this.runQueue.push(W),this.emitEvent({type:h.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[W]=this.runQueue.splice(J,1),Z=W?this.runs.get(W):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let Q=this.runs.get(this.runQueue[Z]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>f)f=Q.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===qH;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:h.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let W=f?Qz($):$.message,Z=await this.routeToTeammate($.agentId,W,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:h.RunCompleted,run:{...$}})}catch(W){let Z=W instanceof Error?W.message:String(W??"Unknown error");$.error=Z,$.endedAt=new Date;let Q=this.members.get($.agentId);if(yH(Q,W))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:h.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:h.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 wH(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await wH($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf($);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:h.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:h.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=qH,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:h.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:h.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,W,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let Q=this.members.get(f);if(!Q)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:W,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:h.TeamMessage,message:{...j}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,W){let Z=[];for(let Q of this.members.values()){if(Q.agentId===$)continue;if(Q.role==="lead")continue;Z.push(this.sendMessage($,Q.agentId,f,J,W?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:h.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:h.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:h.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:h.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let W of f.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:h.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(!EW(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==$||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:h.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${W}`}recordProgressStep($,f,J,W=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let Q=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
462
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function wH($){return new Promise((f)=>setTimeout(f,$))}function Bf($,f){let J=0;for(let W of $){if(!W.startsWith(f))continue;let Z=Number.parseInt(W.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function kW($,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}),gJ($);break}default:break}}async function IW($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let W=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",$,f.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function xW($,f,J,W){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:mJ({teamName:Z,sessionId:f,event:J}),summary:xJ(Z,$.runtime.teamRuntime.exportState())}})}function w2($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function mW($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&w2($)}function gJ($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function gW($){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 vW($,f){let J=f.map((Q)=>{let j=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)j.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")j.push(` iterations=${Q.iterations}`);if(Q.error)j.push(` error=${Q.error}`);return j.join("")}),W=$.activeTeamRunIds.size,Z=W>0?`There are still ${W} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return S2(`System-delivered teammate async run updates:
461
+ ${$}`:$,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:E.TaskEnd,agentId:f,result:j}),this.recordProgressStep(f,`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:E.TaskEnd,agentId:f,error:W,messages:Q.agent.getMessages()}),!eH(Q,W))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get(f)?.status!=="stopped")Q.status="idle"}}startTeammateRun(f,$,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,agentId:f,taskId:J?.taskId,status:"queued",message:$,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:E.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let f;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let $=this.selectNextDispatchableQueuedRun();f=$.nextDelayedAttemptAt;let J=$.index;if(J<0){this.scheduleQueuedRunDispatch(f);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(f)}selectNextDispatchableQueuedRun(){let f=-1,$=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>$)$=W.priority,f=Z}return{index:f,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch(f){if(!f)return;let $=Math.max(0,f.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},$)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let f=0;for(let $ of this.runs.values())if($.status==="running")f++;return f}async executeQueuedRun(f){let $=f.currentActivity===fX;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:E.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let Q=$?o_(f):f.message,Z=await this.routeToTeammate(f.agentId,Q,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=Z,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:E.RunCompleted,run:{...f}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");f.error=Z,f.endedAt=new Date;let W=this.members.get(f.agentId);if(eH(W,Q))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:E.RunCancelled,run:{...f},reason:Z});else if(f.retryCount<f.maxRetries)f.retryCount++,f.status="queued",f.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**f.retryCount)),this.runQueue.push(f.id),this.recordRunProgress(f,`retry_scheduled_${f.retryCount}`);else f.status="failed",f.currentActivity="failed",this.emitEvent({type:E.RunFailed,run:{...f}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns(f){let $=f?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!$&&!["running","queued"].includes(J.status))return!1;if(f?.status&&J.status!==f.status)return!1;if(f?.agentId&&J.agentId!==f.agentId)return!1;return!0}).map((J)=>({...J}))}getRun(f){let $=this.runs.get(f);return $?{...$}:void 0}async awaitRun(f,$=250){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);while(J.status==="queued"||J.status==="running")await $X($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await $X(f);return this.listRuns()}cancelRun(f,$){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=$,J.endedAt=new Date,J.currentActivity="cancelled";let Q=this.runQueue.indexOf(f);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:E.RunCancelled,run:{...J},reason:$}),{...J}}recoverActiveRuns(f="runtime_recovered"){let $=[];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:E.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=f,J.currentActivity=fX,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:E.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),$}markStaleRunsInterrupted(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=f,J.endedAt=new Date,J.currentActivity="interrupted",$.push({...J}),this.emitEvent({type:E.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,Q,Z){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let W=this.members.get($);if(!W)throw Error(`Unknown recipient "${$}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:E.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. 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===f)continue;if(W.role==="lead")continue;Z.push(this.sendMessage(f,W.agentId,$,J,Q?.taskId))}return Z}appendMissionLog(f){if(!this.members.has(f.agentId))throw Error(`Unknown team member "${f.agentId}"`);let $={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:f.agentId,taskId:f.taskId,kind:f.kind,summary:f.summary,evidence:f.evidence,nextAction:f.nextAction};this.missionLog.push($);let J=this.members.get(f.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:E.TeamMissionLog,entry:{...$}}),{...$}}createOutcome(f){let $={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:f.title,status:"draft",requiredSections:[...new Set(f.requiredSections)],createdBy:f.createdBy,createdAt:new Date};return this.outcomes.set($.id,$),this.emitEvent({type:E.OutcomeCreated,outcome:{...$}}),{...$}}listOutcomes(){return Array.from(this.outcomes.values()).map((f)=>({...f}))}attachOutcomeFragment(f){let $=this.outcomes.get(f.outcomeId);if(!$)throw Error(`Outcome "${f.outcomeId}" was not found`);if(!$.requiredSections.includes(f.section))throw Error(`Section "${f.section}" is not part of outcome "${f.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:f.outcomeId,section:f.section,sourceAgentId:f.sourceAgentId,sourceRunId:f.sourceRunId,content:f.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),$.status==="draft")$.status="in_review";return this.emitEvent({type:E.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment(f){let $=this.outcomeFragments.get(f.fragmentId);if(!$)throw Error(`Fragment "${f.fragmentId}" was not found`);return $.status=f.approved?"reviewed":"rejected",$.reviewedBy=f.reviewedBy,$.reviewedAt=new Date,this.emitEvent({type:E.OutcomeFragmentReviewed,fragment:{...$}}),{...$}}listOutcomeFragments(f){return Array.from(this.outcomeFragments.values()).filter(($)=>$.outcomeId===f).map(($)=>({...$}))}finalizeOutcome(f){let $=this.outcomes.get(f);if(!$)throw Error(`Outcome "${f}" was not found`);let J=this.listOutcomeFragments(f);for(let Q of $.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:E.OutcomeFinalized,outcome:{...$}}),{...$}}cleanup(){for(let f of this.members.values())if(f.role==="teammate"&&f.runningCount>0)throw Error(`Cannot cleanup team while teammate "${f.agentId}" is still running`);if(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let f of this.members.values())if(f.role==="teammate")try{f.agent?.abort()}catch($){if(!s9($))throw $}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($.role==="teammate")this.members.delete(f)}requireTask(f){let $=this.tasks.get(f);if(!$)throw Error(`Task "${f}" was not found`);return $}assertDependenciesResolved(f){let $=this.getUnresolvedDependencies(f);if($.length>0)throw Error(`Task "${f.id}" is blocked by "${$[0]}"`)}getUnresolvedDependencies(f){return f.dependsOn.filter(($)=>{let J=this.tasks.get($);return!J||J.status!=="completed"})}trackMeaningfulEvent(f,$){if(this.recordRunActivityFromAgentEvent(f,$),$.type==="iteration_end"&&$.hadToolCalls){this.recordProgressStep(f,`Completed iteration ${$.iteration} with ${$.toolCallCount} tool call(s)`);return}if($.type==="content_end"&&$.contentType==="tool"&&!$.error){this.recordProgressStep(f,`Finished tool "${$.toolName??"unknown"}"`);return}if($.type==="done"){this.appendMissionLog({agentId:f,kind:"done",summary:`Completed a delegated run (${$.iterations} iterations)`});return}if($.type==="error")this.appendMissionLog({agentId:f,kind:"error",summary:$.error.message})}recordRunActivityFromAgentEvent(f,$){let J;switch($.type){case"iteration_start":J=`iteration_${$.iteration}_started`;break;case"content_start":if($.contentType==="tool")J=`running_tool_${$.toolName??"unknown"}`;break;case"content_end":if($.contentType==="tool")J=$.error?this.formatProgressErrorActivity(`tool_${$.toolName??"unknown"}_error`,$.error):`finished_tool_${$.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",$.error.message);break;default:break}if(!J)return;for(let Q of this.runs.values()){if(Q.agentId!==f||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:E.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${Q}`}recordProgressStep(f,$,J,Q=!1){this.missionStepCounter++;let Z=this.members.get(f);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:f,taskId:J,kind:"progress",summary:$})}buildMailboxNotification(f){if(f.length===0)return"";let $=[`[MAILBOX] You have ${f.length} unread message(s):`];for(let J of f)$.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),$.push(J.body);return $.push("---"),$.join(`
462
+ `)}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function $X(f){return new Promise(($)=>setTimeout($,f))}function L1(f,$){let J=0;for(let Q of f){if(!Q.startsWith($))continue;let Z=Number.parseInt(Q.slice($.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function e9(f,$){switch($.type){case"run_queued":case"run_started":f.activeTeamRunIds.add($.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if($.type==="run_failed")J=$.run.error;else if($.type==="run_cancelled"||$.type==="run_interrupted")J=$.run.error??$.reason;f.activeTeamRunIds.delete($.run.id),f.pendingTeamRunUpdates.push({runId:$.run.id,agentId:$.run.agentId,taskId:$.run.taskId,status:$.type.replace("run_",""),error:J,iterations:$.run.result?.iterations}),aJ(f);break}default:break}}async function fQ(f,$,J){switch($.type){case"run_progress":await J("onTeamTaskProgress",f,$.run.agentId,$.message,{kind:$.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if($.event.type==="content_start"&&$.event.contentType==="text"&&typeof $.event.text==="string"){let Q=$.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,$.message);break;case"task_end":{if($.error)await J("onTeamTaskEnd",f,$.agentId,"failed",`[error] ${$.error.message}`,void 0,$.messages);else if($.result?.finishReason==="aborted")await J("onTeamTaskEnd",f,$.agentId,"cancelled","[done] aborted",$.result,$.result.messages);else await J("onTeamTaskEnd",f,$.agentId,"completed",`[done] ${$.result?.finishReason??"completed"}`,$.result,$.result?.messages);break}default:break}}function $Q(f,$,J,Q){if(!f.runtime.teamRuntime)return;let Z=f.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:$,teamName:Z,lifecycle:nJ({teamName:Z,sessionId:$,event:J}),summary:iJ(Z,f.runtime.teamRuntime.exportState())}})}function x2(f){return f.activeTeamRunIds.size>0||f.pendingTeamRunUpdates.length>0}function JQ(f,$){if(f.aborting)return!1;if(!($==="completed"||$==="max_iterations"))return!1;return f.config.enableAgentTeams===!0&&x2(f)}function aJ(f){let $=f.teamRunWaiters.splice(0);for(let J of $)J()}async function QQ(f){while(!0){if(f.aborting)return[];if(f.pendingTeamRunUpdates.length>0){let $=[...f.pendingTeamRunUpdates];return f.pendingTeamRunUpdates.length=0,$}if(f.activeTeamRunIds.size===0)return[];await new Promise(($)=>{f.teamRunWaiters.push($)})}}function ZQ(f,$){let J=$.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=f.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 g2(`System-delivered teammate async run updates:
463
463
  ${J.join(`
464
464
  `)}
465
465
 
466
- ${Z}`,$.config.mode)}function S2($,f){return jz($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var uW=4;class K${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 hW($,f.messagesArtifactUploader,f.logger),this.teamChildren=new IJ($,this.manifestStore,(J,W,Z)=>this.toPersistedMessages(J,W,Z),K$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?NJ(f.messages,f,J):TJ($)}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(),W=J.length>0?J:`${Date.now()}_${Xz(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),j=F2({metadata:$.metadata,prompt:$.prompt}),H={version:1,session_id:W,source:$.source,pid:$.pid,started_at:f,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:W,source:$.source,pid:$.pid,startedAt:f,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:H.prompt??null,metadata:k$(H.metadata),hookPath:"",messagesPath:Z,updatedAt:n()}),this.manifestStore.initializeMessagesFile(W,Z,f),this.manifestStore.writeSessionManifest(Q,H),{manifestPath:Q,messagesPath:Z,manifest:H}}async updateSessionStatus($,f,J){let W;if((await hj(()=>this.adapter.getSession($),async(Q)=>{return W=$0(f)?void 0:n(),this.adapter.updateSession({sessionId:$,status:f,endedAt:W??null,exitCode:$0(f)?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},uW)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession($){for(let f=0;f<uW;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,Z=$.metadata!==void 0?k$($.metadata)??{}:k$(W)??{},Q=z1(typeof W?.title==="string"?W.title:void 0),j=$.title!==void 0?z1($.title):Q??XW($.prompt);if(j)Z.title=j;else delete Z.title;let H=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:H?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:A,manifest:Y}=this.manifestStore.readManifestFile($.sessionId);if(Y){if($.prompt!==void 0)Y.prompt=$.prompt??void 0;let V=$.metadata!==void 0?k$($.metadata)??{}:k$(Y.metadata)??{};if(j)V.title=j;Y.metadata=Object.keys(V).length>0?V:void 0,this.manifestStore.writeSessionManifest(A,Y)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let W=TJ(f);return this.manifestStore.persistSessionMessages($,W,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,W,Z,Q){return this.teamChildren.onTeamTaskEnd($,f,J,W,Z,Q)}onTeamTaskProgress($,f,J,W){return this.teamChildren.onTeamTaskProgress($,f,J,W)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if($0($.status)===!1||this.isPidAlive($.pid))return $;let f=n(),J=K$.STALE_REASON;for(let W=0;W<uW;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if($0(Z.status)===!1)return Z;let Q={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:K$.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:Q,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let H=Sj(Z,{status:"failed",endedAt:f,exitCode:1,metadata:Q}),{path:X}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(X,H),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,K$.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:Q,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let Q=k$(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),H=z1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),X=H?{...Q??{},title:H}:Q;return{...Z,metadata:X}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),W=0;for(let Z of J){let Q=await this.reconcileDeadRunningSession(Z);if(Q&&Q.status!==Z.status)W++}return W}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(W.map(async(Z)=>{await wW(Z.cwd,Z.sessionId),y2(Z.messagesPath),y2(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await wW(J.cwd,f),y2(J.messagesPath),y2(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)W.add(Hz(Z));for(let Z of W)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function dW(){return new Date().toISOString()}function CH($,f){let J=`${$}.tmp`;Vz(J,`${JSON.stringify(f,null,2)}
467
- `,"utf8"),Yz(J,$)}class EH{sessionsDirPath;constructor($=Bz()){this.sessionsDirPath=$}ensureSessionsDir(){if(!cW(this.sessionsDirPath))Az(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return hH(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return hH(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!cW($))return{version:1,sessions:{}};try{let f=JSON.parse(SH($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){CH(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!cW($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(SH($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){CH(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let W=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:W,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:dW()};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:dW()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),W=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!W)return;return W.consumedAt=dW(),this.writeQueue(J),W.task}}class lW extends K${constructor($,f={}){super(new EH($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as Kz,mkdirSync as Gz}from"node:fs";import{resolveSessionDataDir as Pz}from"@cline/shared/storage";var pW=`
466
+ ${Z}`,f.config.mode)}function g2(f,$){return e_(f,$==="plan"?"plan":$==="yolo"?"yolo":"act")}var WQ=4;class Rf{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=f;this.manifestStore=new p9(f,$.messagesArtifactUploader,$.logger),this.teamChildren=new dJ(f,this.manifestStore,(J,Q,Z)=>this.toPersistedMessages(J,Q,Z),Rf.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages(f,$,J){if(!f)return;return $?EJ($.messages,$,J):SJ(f)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest(f,$){this.manifestStore.writeSessionManifest(f,$)}readSessionManifest(f){return this.manifestStore.readSessionManifest(f)}async createRootSessionWithArtifacts(f){let $=f.startedAt??n(),J=f.sessionId.trim(),Q=J.length>0?J:`${Date.now()}_${$T(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(Q),W=this.manifestStore.artifacts.sessionManifestPath(Q),j=M2({metadata:f.metadata,prompt:f.prompt}),H={version:1,session_id:Q,source:f.source,pid:f.pid,started_at:$,status:"running",interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:Q,source:f.source,pid:f.pid,startedAt:$,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:H.prompt??null,metadata:vf(H.metadata),hookPath:"",messagesPath:Z,updatedAt:n()}),this.manifestStore.initializeMessagesFile(Q,Z,$),this.manifestStore.writeSessionManifest(W,H),{manifestPath:W,messagesPath:Z,manifest:H}}async updateSessionStatus(f,$,J){let Q;if((await oj(()=>this.adapter.getSession(f),async(W)=>{return Q=$0($)?void 0:n(),this.adapter.updateSession({sessionId:f,status:$,endedAt:Q??null,exitCode:$0($)?null:typeof J==="number"?J:null,expectedStatusLock:W.statusLock})},WQ)).updated){if($==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions(f,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession(f){for(let $=0;$<WQ;$++){let J=await this.adapter.getSession(f.sessionId);if(!J)return{updated:!1};let Q=J.metadata??void 0,Z=f.metadata!==void 0?vf(f.metadata)??{}:vf(Q)??{},W=N$(typeof Q?.title==="string"?Q.title:void 0),j=f.title!==void 0?N$(f.title):W??_9(f.prompt);if(j)Z.title=j;else delete Z.title;let H=f.metadata!==void 0||f.prompt!==void 0||f.title!==void 0;if(!(await this.adapter.updateSession({sessionId:f.sessionId,prompt:f.prompt,metadata:H?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:A,manifest:Y}=this.manifestStore.readManifestFile(f.sessionId);if(Y){if(f.prompt!==void 0)Y.prompt=f.prompt??void 0;let V=f.metadata!==void 0?vf(f.metadata)??{}:vf(Y.metadata)??{};if(j)V.title=j;Y.metadata=Object.keys(V).length>0?V:void 0,this.manifestStore.writeSessionManifest(A,Y)}return{updated:!0}}return{updated:!1}}queueSpawnRequest(f){return this.teamChildren.queueSpawnRequest(f)}upsertSubagentSession(f){return this.teamChildren.upsertSubagentSession(f)}upsertSubagentSessionFromHook(f){return this.teamChildren.upsertSubagentSessionFromHook(f)}appendSubagentHookAudit(f,$){return this.teamChildren.appendSubagentHookAudit($),Promise.resolve()}persistSessionMessages(f,$,J){let Q=SJ($);return this.manifestStore.persistSessionMessages(f,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(f){if(!Number.isFinite(f)||f<=0)return!1;try{return process.kill(Math.floor(f),0),!0}catch($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="EPERM"}}async reconcileDeadRunningSession(f){if($0(f.status)===!1||this.isPidAlive(f.pid))return f;let $=n(),J=Rf.STALE_REASON;for(let Q=0;Q<WQ;Q++){let Z=await this.adapter.getSession(f.sessionId);if(!Z)return;if($0(Z.status)===!1)return Z;let W={...Z.metadata??{},terminal_marker:J,terminal_marker_at:$,terminal_marker_pid:Z.pid,terminal_marker_source:Rf.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:$,exitCode:1,metadata:W,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let H=sj(Z,{status:"failed",endedAt:$,exitCode:1,metadata:W}),{path:X}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(X,H),this.manifestStore.appendStaleSessionHookLog($,Z.sessionId,Z.pid,J,Rf.STALE_SOURCE),{...Z,status:"failed",endedAt:$,exitCode:1,metadata:W,statusLock:j.statusLock,updatedAt:$}}return await this.adapter.getSession(f.sessionId)}async listSessions(f=200){let $=Math.max(1,Math.floor(f)),J=Math.min($*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,$).map((Z)=>{let W=vf(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),H=N$(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),X=H?{...W??{},title:H}:W;return{...Z,metadata:X}})}async reconcileDeadSessions(f=2000){let $=Math.max(1,Math.floor(f)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:$,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(f){let $=f.trim();if(!$)throw Error("session id is required");let J=await this.adapter.getSession($);if(!J)return{deleted:!1};if(await this.adapter.deleteSession($,!1),!J.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$});await this.adapter.deleteSession($,!0),await Promise.allSettled(Q.map(async(Z)=>{await d9(Z.cwd,Z.sessionId),k2(Z.messagesPath),k2(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await d9(J.cwd,$),k2(J.messagesPath),k2(this.manifestStore.artifacts.sessionManifestPath($,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty($);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir($)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)Q.add(fT(Z));for(let Z of Q)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function HQ(){return new Date().toISOString()}function ZX(f,$){let J=`${f}.tmp`;ZT(J,`${JSON.stringify($,null,2)}
467
+ `,"utf8"),QT(J,f)}class WX{sessionsDirPath;constructor(f=WT()){this.sessionsDirPath=f}ensureSessionsDir(){if(!jQ(this.sessionsDirPath))JT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return QX(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return QX(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let f=this.indexPath();if(!jQ(f))return{version:1,sessions:{}};try{let $=JSON.parse(JX(f,"utf8"));if($?.version===1&&$.sessions)return $}catch{}return{version:1,sessions:{}}}writeIndex(f){ZX(this.indexPath(),f)}readQueue(){let f=this.spawnQueuePath();if(!jQ(f))return{version:1,nextId:1,requests:[]};try{let $=JSON.parse(JX(f,"utf8"));if($?.version===1&&typeof $.nextId==="number"&&Array.isArray($.requests))return $}catch{}return{version:1,nextId:1,requests:[]}}writeQueue(f){ZX(this.spawnQueuePath(),f)}async upsertSession(f){let $=this.readIndex();$.sessions[f.sessionId]=f,this.writeIndex($)}async getSession(f){return this.readIndex().sessions[f]}async listSessions(f){return Object.values(this.readIndex().sessions).filter(($)=>f.parentSessionId!==void 0?$.parentSessionId===f.parentSessionId:!0).filter(($)=>f.status!==void 0?$.status===f.status:!0).sort(($,J)=>J.startedAt.localeCompare($.startedAt)).slice(0,f.limit)}async updateSession(f){let $=this.readIndex(),J=$.sessions[f.sessionId];if(!J)return{updated:!1,statusLock:0};if(f.expectedStatusLock!==void 0&&J.statusLock!==f.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let Q=f.expectedStatusLock!==void 0?f.expectedStatusLock+1:J.statusLock,Z={...J,status:f.status??J.status,endedAt:f.endedAt!==void 0?f.endedAt:J.endedAt??null,exitCode:f.exitCode!==void 0?f.exitCode:J.exitCode??null,prompt:f.prompt!==void 0?f.prompt:J.prompt??null,metadata:f.metadata!==void 0?f.metadata??null:J.metadata??null,parentSessionId:f.parentSessionId!==void 0?f.parentSessionId??null:J.parentSessionId??null,parentAgentId:f.parentAgentId!==void 0?f.parentAgentId??null:J.parentAgentId??null,agentId:f.agentId!==void 0?f.agentId??null:J.agentId??null,conversationId:f.conversationId!==void 0?f.conversationId??null:J.conversationId??null,statusLock:Q,isSubagent:f.setRunning||f.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:HQ()};if(f.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return $.sessions[f.sessionId]=Z,this.writeIndex($),{updated:!0,statusLock:Z.statusLock}}async deleteSession(f,$){let J=this.readIndex();if(!J.sessions[f])return!1;if(delete J.sessions[f],$){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===f)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest(f){let $=this.readQueue();$.requests.push({id:$.nextId,rootSessionId:f.rootSessionId,parentAgentId:f.parentAgentId,task:f.task,systemPrompt:f.systemPrompt,createdAt:HQ()}),$.nextId+=1,this.writeQueue($)}async claimSpawnRequest(f,$){let J=this.readQueue(),Q=J.requests.find((Z)=>Z.rootSessionId===f&&Z.parentAgentId===$&&!Z.consumedAt);if(!Q)return;return Q.consumedAt=HQ(),this.writeQueue(J),Q.task}}class XQ extends Rf{constructor(f,$={}){super(new WX(f),$)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as jT,mkdirSync as HT}from"node:fs";import{resolveSessionDataDir as XT}from"@cline/shared/storage";var AQ=`
468
468
  session_id AS sessionId,
469
469
  source,
470
470
  pid,
@@ -491,43 +491,43 @@ ${Z}`,$.config.mode)}function S2($,f){return jz($,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 rW($){$.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 iW($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function bH($){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 kH{store;sessionsDirPath;constructor($,f=Pz()){this.store=$;this.sessionsDirPath=f}ensureSessionsDir(){if(!Kz(this.sessionsDirPath))Gz(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
494
+ updated_at AS updatedAt`;function YQ(f){f.interactive=f.interactive===1,f.enableTools=f.enableTools===1,f.enableSpawn=f.enableSpawn===1,f.enableTeams=f.enableTeams===1,f.isSubagent=f.isSubagent===1;let $=f.metadata;if(typeof $==="string"&&$.trim())try{let J=JSON.parse($);f.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{f.metadata=null}else f.metadata=null;return f}function VQ(f){if(!f||Object.keys(f).length===0)return null;return JSON.stringify(f)}function jX(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class HX{store;sessionsDirPath;constructor(f,$=XT()){this.store=f;this.sessionsDirPath=$}ensureSessionsDir(){if(!jT(this.sessionsDirPath))HT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession(f){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,iW($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let f=this.store.queryOne(`SELECT ${pW} FROM sessions WHERE session_id = ?`,[$]);return f?rW(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 W=f.length>0?`WHERE ${f.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${pW}
499
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,f.statusLock,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.isSubagent?1:0,f.prompt??null,VQ(f.metadata),"",f.hookPath??"",f.messagesPath??null,f.updatedAt])}async getSession(f){let $=this.store.queryOne(`SELECT ${AQ} FROM sessions WHERE session_id = ?`,[f]);return $?YQ($):void 0}async listSessions(f){let $=[],J=[];if(f.parentSessionId)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.status)$.push("status = ?"),J.push(f.status);let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${AQ}
500
500
  FROM sessions
501
- ${W}
501
+ ${Q}
502
502
  ORDER BY started_at DESC
503
- LIMIT ?`,[...J,$.limit]).map(rW)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
503
+ LIMIT ?`,[...J,f.limit]).map(YQ)}async updateSession(f){if(f.setRunning){if(f.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(iW($.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 W=0;if($.expectedStatusLock!==void 0)W=$.expectedStatusLock+1,f.push("status_lock = ?"),J.push(W);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)W=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:W}}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
- VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,n()])}async claimSpawnRequest($,f){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
507
+ WHERE session_id = ? AND status_lock = ?`,[n(),f.expectedStatusLock+1,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.prompt??null,f.sessionId,f.expectedStatusLock]).changes??0)>0,statusLock:f.expectedStatusLock+1}}let $=[],J=[];if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt??null);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(VQ(f.metadata));if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId??null);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId??null);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId??null);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId??null);if($.length===0){let j=await this.getSession(f.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let Q=0;if(f.expectedStatusLock!==void 0)Q=f.expectedStatusLock+1,$.push("status_lock = ?"),J.push(Q);$.push("updated_at = ?"),J.push(n());let Z=`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`;if(J.push(f.sessionId),f.expectedStatusLock!==void 0)Z+=" AND status_lock = ?",J.push(f.expectedStatusLock);if((this.store.run(Z,J).changes??0)===0)return{updated:!1,statusLock:0};if(f.expectedStatusLock===void 0)Q=(await this.getSession(f.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession(f,$){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}async enqueueSpawnRequest(f){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
508
+ VALUES (?, ?, ?, ?, ?, NULL)`,[f.rootSessionId,f.parentAgentId,f.task??null,f.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 l$ extends K${store;constructor($,f={}){super(new kH($,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 tf extends Rf{store;constructor(f,$={}){super(new HX(f,$.sessionArtifactsDir),$);this.store=f}createRootSession(f){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 nT}from"node:fs";import{homedir as aT}from"node:os";import{isAbsolute as tT,join as SZ,resolve as hZ}from"node:path";import{captureSdkError as C1,createSessionId as sT,isLikelyAuthError as oT,normalizeUserInput as eT}from"@cline/shared";import{setHomeDirIfUnset as $N}from"@cline/shared/storage";B0();import{createHandlerAsync as Lz}from"@cline/llms";import{estimateTokens as nW}from"@cline/shared";var mH=200000,aW=0.9,gH=16384,tW=20000,IH=1024,xH=2000,vH=2000,uH=8;function p$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
516
- ...[truncated ${$.length-f} chars]`}function Uz($){let f=sW($);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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,null,null,"running",0,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,null,null,null,null,0,f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"","",f.messagesPath,n()])}}import{readdirSync as xM}from"node:fs";import{homedir as gM}from"node:os";import{isAbsolute as mM,join as nQ,resolve as aQ}from"node:path";import{captureSdkError as I$,createSessionId as vM,isLikelyAuthError as cM,normalizeUserInput as uM}from"@cline/shared";import{setHomeDirIfUnset as dM}from"@cline/shared/storage";V0();import{createHandlerAsync as KT}from"@cline/llms";import{estimateTokens as BQ}from"@cline/shared";var YX=200000,KQ=0.9,VX=16384,PQ=20000,XX=1024,AX=2000,BX=2000,KX=8;function sf(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
516
+ ...[truncated ${f.length-$} chars]`}function AT(f){let $=GQ(f);if(typeof $==="string")return $;return $.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 sW($){if(typeof $==="string")return p$($,xH);return $.map((f)=>{switch(f.type){case"text":return{...f,text:p$(f.text,xH)};case"file":return{...f,content:p$(f.content,vH)};case"image":return f;default:return f}})}function Fz($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function cH($){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]: ${p$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${Fz(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${Uz(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${p$(J.content,vH)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
520
- `)}function dH($){return $.map(cH).join(`
519
+ `)}function GQ(f){if(typeof f==="string")return sf(f,AX);return f.map(($)=>{switch($.type){case"text":return{...$,text:sf($.text,AX)};case"file":return{...$,content:sf($.content,BX)};case"image":return $;default:return $}})}function YT(f){return Object.entries(f).map(([$,J])=>`${$}=${JSON.stringify(J)}`).join(", ")}function PX(f){if(typeof f.content==="string")return`[${f.role==="user"?"User":"Bot"}]: ${f.content}`;let $=[];for(let J of f.content)switch(J.type){case"text":$.push(`[${f.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":$.push(`[Bot thinking]: ${sf(J.thinking,2000)}`);break;case"redacted_thinking":$.push("[Bot thinking]: [redacted]");break;case"tool_use":$.push(`[Bot tool calls]: ${J.name}(${YT(J.input)})`);break;case"tool_result":$.push(`[Tool result]: ${AT(J.content)}`);break;case"file":$.push(`[${f.role==="user"?"User":"Bot"} file ${J.path}]: ${sf(J.content,BX)}`);break;case"image":$.push(`[${f.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return $.join(`
520
+ `)}function GX(f){return f.map(PX).join(`
521
521
 
522
- `).trim()}function lH(){let $=new WeakMap;return(f)=>{let J=f,W=$.get(J);if(typeof W==="number")return W;let Z;try{Z=JSON.stringify(f)}catch{Z=cH(f)}let Q=nW(Z.length);return $.set(J,Q),Q}}function E2($){return $.metadata?.kind==="compaction_summary"}function oW($){if(!E2($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function Rz($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function b2($){return $.role==="user"&&!Rz($)&&!E2($)}function pH($){for(let f=0;f<$.length;f+=1)if(b2($[f]))return f;return-1}function vJ($){for(let f=$.length-1;f>=0;f-=1)if(b2($[f]))return f;return 0}function rH($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function iH($){for(let f=$.length-1;f>=0;f-=1)if(E2($[f]))return f;return-1}function nH($,f,J){let W=vJ($);if(W<=0)return 0;let Z=0,Q=$.length;for(let H=$.length-1;H>=0;H-=1)if(Z+=J($[H]),Q=H,Z>=f)break;if(Q<=0)return 0;let j=Math.min(Q,W);while(j>0&&!b2($[j]))j-=1;return j}function C2($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>C2(f));if($&&typeof $==="object"){let f=$,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...C2(f[W]));if(Array.isArray(f.files)){for(let W of f.files)if(W&&typeof W==="object")J.push(...C2(W.path))}if(Array.isArray(f.file_paths))J.push(...C2(f.file_paths));return J}return[]}function h2($,f){let J=new Set($);for(let W of f){let Z=W.trim();if(!Z)continue;J.add(Z)}return[...J].sort((W,Z)=>W.localeCompare(Z))}function aH($){let f=[],J=[];for(let W of $){let Z=oW(W);if(Z){f=h2(f,Z.details.readFiles),J=h2(J,Z.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){f=h2(f,[Q.path]);continue}if(Q.type!=="tool_use")continue;let j=C2(Q.input);if(Q.name==="read_files"){f=h2(f,j);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=h2(J,j)}}return{readFiles:f,modifiedFiles:J}}function Dz($){let f=$.readFiles.length>0?$.readFiles.map((W)=>`- ${W}`).join(`
523
- `):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((W)=>`- ${W}`).join(`
522
+ `).trim()}function FX(){let f=new WeakMap;return($)=>{let J=$,Q=f.get(J);if(typeof Q==="number")return Q;let Z;try{Z=JSON.stringify($)}catch{Z=PX($)}let W=BQ(Z.length);return f.set(J,W),W}}function c2(f){return f.metadata?.kind==="compaction_summary"}function FQ(f){if(!c2(f))return;let $=f.metadata;if(!$)return;let J=$.details;return{kind:"compaction_summary",summary:String($.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($.tokensBefore??0),generatedAt:Number($.generatedAt??0)}}function VT(f){if(f.role!=="user"||!Array.isArray(f.content))return!1;return f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}function u2(f){return f.role==="user"&&!VT(f)&&!c2(f)}function UX(f){for(let $=0;$<f.length;$+=1)if(u2(f[$]))return $;return-1}function tJ(f){for(let $=f.length-1;$>=0;$-=1)if(u2(f[$]))return $;return 0}function RX(f){for(let $=f.length-1;$>=0;$-=1)if(f[$].role==="assistant")return $;return-1}function DX(f){for(let $=f.length-1;$>=0;$-=1)if(c2(f[$]))return $;return-1}function LX(f,$,J){let Q=tJ(f);if(Q<=0)return 0;let Z=0,W=f.length;for(let H=f.length-1;H>=0;H-=1)if(Z+=J(f[H]),W=H,Z>=$)break;if(W<=0)return 0;let j=Math.min(W,Q);while(j>0&&!u2(f[j]))j-=1;return j}function v2(f){if(typeof f==="string"&&f.trim().length>0)return[f];if(Array.isArray(f))return f.flatMap(($)=>v2($));if(f&&typeof f==="object"){let $=f,J=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...v2($[Q]));if(Array.isArray($.files)){for(let Q of $.files)if(Q&&typeof Q==="object")J.push(...v2(Q.path))}if(Array.isArray($.file_paths))J.push(...v2($.file_paths));return J}return[]}function m2(f,$){let J=new Set(f);for(let Q of $){let Z=Q.trim();if(!Z)continue;J.add(Z)}return[...J].sort((Q,Z)=>Q.localeCompare(Z))}function OX(f){let $=[],J=[];for(let Q of f){let Z=FQ(Q);if(Z){$=m2($,Z.details.readFiles),J=m2(J,Z.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let W of Q.content){if(W.type==="file"){$=m2($,[W.path]);continue}if(W.type!=="tool_use")continue;let j=v2(W.input);if(W.name==="read_files"){$=m2($,j);continue}if(W.name==="editor"||W.name==="apply_patch")J=m2(J,j)}}return{readFiles:$,modifiedFiles:J}}function BT(f){let $=f.readFiles.length>0?f.readFiles.map((Q)=>`- ${Q}`).join(`
523
+ `):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((Q)=>`- ${Q}`).join(`
524
524
  `):"- none";return`## Files
525
525
  Read:
526
- ${f}
526
+ ${$}
527
527
  Modified:
528
- ${J}`}function tH($,f){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
528
+ ${J}`}function _X(f,$){if(/^## Files$/im.test(f))return f.trim();return`${f.trim()}
529
529
 
530
- ${Dz(f)}`.trim()}function sH($){let f=[`Summarize this session for continuation. Be concise and factual.
530
+ ${BT($)}`.trim()}function TX(f){let $=[`Summarize this session for continuation. Be concise and factual.
531
531
 
532
532
  ## Goal
533
533
  One sentence: what is being built or fixed.
@@ -544,28 +544,28 @@ Key technical choices or notable findings (omit if none).
544
544
  Immediate next steps.
545
545
 
546
546
  ## Files
547
- Read: ${$.fileOps.readFiles.join(", ")||"none"}
548
- Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.trim())f.push(`Previous summary:
549
- ${$.previousSummary.trim()}`);return f.push(`Conversation:
550
- ${$.conversationText||"(empty)"}`),f.join(`
551
-
552
- `)}function oH($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:Q,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??IH,thinking:!1}};if(!f)return J($.activeProviderConfig);let W=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...W??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.headers??W?.headers,knownModels:f.knownModels??W?.knownModels,maxOutputTokens:f.maxOutputTokens??IH})}function eH($){return{role:"user",content:`Context summary:
553
-
554
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function Oz($){let f=await Lz($.providerConfig),J="";for await(let W of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function zz($){try{return JSON.stringify($).length}catch{return String($).length}}async function $X($){let f=$.context.messages;if(f.length<2)return;let J=nH(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let W=f.slice(0,J),Z=iH(W),Q=Z>=0?oW(W[Z])?.summary:void 0,j=Z>=0?W.slice(Z+1):W;if(j.length===0)return;let H=aH(W),X=dH(j),A=sH({previousSummary:Q,conversationText:X,fileOps:H});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:W.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:Q?.length??0,conversationTextChars:X.length,summaryRequestChars:A.length,summaryRequestEstimatedTokens:nW(A.length),newMessagesJsonChars:zz(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let Y=await Oz({providerConfig:oH({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:A,logger:$.logger});if(!Y.trim())return;let V=tH(Y,H),B=f.reduce((R,P)=>R+$.estimateMessageTokens(P),0),K=[eH({summary:V,fileOps:H,tokensBefore:B}),...f.slice(J)],G=K.reduce((R,P)=>R+$.estimateMessageTokens(P),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function WX($){if(E2($))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:sW(J.content)}:J)}}function k2($,f){return $.reduce((J,W)=>J+f(W),0)}function fX($,f){let J=Math.max(1,f),W=Math.max(16,J*4);if(typeof $.content==="string"){let j=p$($.content,W).trim();return{...$,content:j||"..."}}let Z=W,Q=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let H=p$(j.text,Z).trim();return Z-=H.length,{...j,text:H||"..."}});return{...$,content:Q}}function _z($,f){let J=pH($),W=vJ($),Z=rH($),Q=[];for(let j=0;j<$.length;j+=1){let H=WX($[j]);if(!H)continue;Q.push({index:j,message:H,estimatedTokens:f(H),isFirstUser:j===J,isLastUser:j===W,isLastAssistant:j===Z})}return Q}function JX($,f,J,W){let Z=$[f];Z.message=J,Z.estimatedTokens=W(J)}function Tz($){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 Nz($){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 ZX($){return new Set([...Tz($.message),...Nz($.message)])}function Mz($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let W of ZX($[J])){let Z=f.get(W);if(Z)Z.add(J);else f.set(W,new Set([J]))}return f}function yz($,f){let J=Mz($),W=new Set,Z=[f];while(Z.length>0){let Q=Z.shift();if(Q===void 0||W.has(Q))continue;W.add(Q);for(let j of ZX($[Q]))for(let H of J.get(j)??[])if(!W.has(H))Z.push(H)}return W}function uJ($,f,J,W){let Z=k2($.map((Q)=>Q.message),W);for(let Q=0;Q<$.length&&Z>J;){if(!f($[Q])){Q+=1;continue}let j=yz($,Q);Z-=Array.from(j).reduce((H,X)=>H+$[X].estimatedTokens,0);for(let H of Array.from(j).sort((X,A)=>A-X))$.splice(H,1)}}function qz($,f,J){let W=k2($.map((Q)=>Q.message),J);if(W<=f)return;for(let Q=$.length-1;Q>=0&&W>f;Q-=1){let j=$[Q];if(j.isFirstUser)continue;let H=Math.max(uH,j.estimatedTokens-(W-f));if(H>=j.estimatedTokens)continue;JX($,Q,fX(j.message,H),J),W=k2($.map((X)=>X.message),J)}if(W<=f)return;let Z=$.findIndex((Q)=>Q.isFirstUser);if(Z>=0){let Q=Math.max(1,$[Z].estimatedTokens-(W-f));JX($,Z,fX($[Z].message,Q),J)}}function wz($,f){return JSON.stringify($)!==JSON.stringify(f)}function Sz($){let f=vJ($);if(f<0||f===0&&!b2($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function QX($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:W}=Sz($.context.messages);if(J.length===0)return;let Z=_z(J,$.estimateMessageTokens);if(Z.length===0)return;uJ(Z,(X)=>X.message.role==="assistant"&&!X.isLastAssistant,f,$.estimateMessageTokens),uJ(Z,(X)=>X.message.role==="user"&&!X.isFirstUser&&!X.isLastUser,f,$.estimateMessageTokens),uJ(Z,(X)=>X.message.role==="assistant"&&X.isLastAssistant,f,$.estimateMessageTokens),uJ(Z,(X)=>X.message.role==="user"&&X.isLastUser&&!X.isFirstUser,f,$.estimateMessageTokens),qz(Z,f,$.estimateMessageTokens);let Q=[...Z.map((X)=>X.message),...W];if(!wz($.context.messages,Q))return;let j=k2([...J.map((X)=>WX(X)??X),...W],$.estimateMessageTokens),H=k2(Q,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:Q.length,messagesRemoved:$.context.messages.length-Q.length,tokensBefore:j,tokensAfter:H,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:Q}}function jX($){try{return JSON.stringify($).length}catch{return String($).length}}function hz($){let f=0,J=0,W=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;let j=jX(Q.content);f+=1,J+=j,W=Math.max(W,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:W}}var Cz={basic:({context:$,estimateMessageTokens:f,logger:J})=>QX({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:W,estimateMessageTokens:Z,logger:Q})=>$X({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??tW,$.triggerTokens):J?.preserveRecentTokens??tW,estimateMessageTokens:Z,logger:Q})};function Ez($){if(typeof $.config.reserveTokens==="number"){let W=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-W);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let W=Math.max(0,Math.min($.maxInputTokens-gH,$.maxInputTokens*aW));return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}let f=$.config.thresholdRatio??aW,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function bz($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),W=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}function eW($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let W=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=lH(),Q=J?.strategy??"basic",j=Cz[Q],H=f.mode??"auto",X=J?.compact?"custom":Q;return async(A)=>{let Y=A.apiMessages.reduce((O,T)=>O+Z(T),0),V=J?.maxInputTokens??A.model.info?.maxInputTokens??A.model.info?.contextWindow??mH;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=Ez({inputTokens:Y,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:H,strategy:Q,iteration:A.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:Y,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:A.messages.length,apiMessageCount:A.apiMessages.length,apiMessagesJsonChars:jX(A.apiMessages),...hz(A.apiMessages)}),H==="auto"&&!B.shouldCompact)return;let K=H==="manual"?bz({inputTokens:Y,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,G={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId,iteration:A.iteration,messages:A.messages,model:A.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?Y/V:0},R=H==="manual"?"manual_compaction":"auto_compaction";A.emitStatusNotice?.(H==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:A.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let P=A.messages.length,U=Date.now(),F=J?.compact?await J.compact(G):await j({context:G,providerConfig:{...W,abortSignal:A.abortSignal},compaction:J,mode:H,estimateMessageTokens:Z,logger:$.logger}),z=Date.now()-U,_=$.sessionId??A.conversationId,D={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId??void 0};if(F?.messages){let O=F.messages.reduce((T,M)=>T+Z(M),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:Q,maxInputTokens:V,inputTokens:Y,afterTokens:O,tokensSaved:Y-O,utilizationBefore:`${(Y/V*100).toFixed(1)}%`,utilizationAfter:`${(O/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length}),o4($.telemetry,{ulid:_,strategy:X,mode:H,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length,tokensBefore:Y,tokensAfter:O,tokensSaved:Y-O,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...D})}else e4($.telemetry,{ulid:_,strategy:X,mode:H,reason:"no_result",tokensBefore:Y,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...D});return F}}B0();function G0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function A0($,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 cJ($){let f=G0();for(let J of $)f=A0(f,J);return f}function Kf($){return typeof $==="number"&&Number.isFinite($)?$:0}function dJ($){let f=G0();for(let J of $){let W=J.metrics;if(!W)continue;f=A0(f,{inputTokens:Kf(W.inputTokens),outputTokens:Kf(W.outputTokens),cacheReadTokens:Kf(W.cacheReadTokens),cacheWriteTokens:Kf(W.cacheWriteTokens),totalCost:Kf(W.cost)})}return f}function kz($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let W=Kf(J.metrics?.inputTokens);return W>0?W:void 0}return}function Iz($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function $Z($){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 G$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,W=$.teamRole,Z="root";if(W==="teammate")Z="team_teammate";else if(W==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:W,teamAgentId:$.teamAgentId?.trim()||void 0}}function xz($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function mz($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let W=J?.trim();if(W)return W}return $.isPrimaryAgentEvent?"root":"unknown"}function fZ($,f,J){let{sessionId:W,config:Z,liveSession:Q,emit:j}=$,H=Z.telemetry,X=Q?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,Y=$Z(f),V=G$({agentId:J?.agentId??Y.agentId,conversationId:J?.conversationId??Y.conversationId,parentAgentId:J?.parentAgentId??Y.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??X?.getTeamId(),teamName:J?.teamName??X?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=Iz(f.input);if(B)p4(H,{ulid:W,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",K=!f.error;if(l4(H,{ulid:W,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))r4(H,{ulid:W,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...V})}if(f.type==="notice"&&f.reason==="api_error")t2(H,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...V});if(f.type==="error")t2(H,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...V});if(f.type==="usage"&&Q?.turnUsageBaseline){let B=xz(f);if(A){Q.turnPrimaryUsage=A0(Q.turnPrimaryUsage??G0(),B);let G=A0(Q.turnUsageBaseline,Q.turnPrimaryUsage);$.usageBySession.set(W,G),Nf(H,{ulid:W,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),c4(H,{ulid:W,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...V})}else{let G=mz({isPrimaryAgentEvent:A,overrides:J,eventMetadata:Y}),R=Q.turnUsageByAgent??new Map;Q.turnUsageByAgent=R,R.set(G,A0(R.get(G)??G0(),B))}let K=A0(Q.turnPrimaryUsage??G0(),cJ(Q.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(W,A0(Q.turnAggregateUsageBaseline??Q.turnUsageBaseline,K))}if(f.type==="iteration_end"&&A)$.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:W,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:qj(f),ts:Date.now()}})}function r$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as B_}from"@cline/shared";import{spawn as iz}from"node:child_process";import{appendFileSync as nz,readFileSync as az}from"node:fs";import{join as tz}from"node:path";import{augmentNodeCommandForDebug as YX,withResolvedClineBuildEnv as HZ}from"@cline/shared";import{ensureHookLogDir as XX}from"@cline/shared/storage";function lJ($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as gz,readdirSync as vz}from"node:fs";import{basename as uz,extname as cz,join as dz}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as HX,resolveHooksConfigSearchPaths as lz}from"@cline/shared/storage";function JZ($){return lz($)}var pJ;((Y)=>{Y.TaskStart="TaskStart";Y.TaskResume="TaskResume";Y.TaskCancel="TaskCancel";Y.TaskComplete="TaskComplete";Y.TaskError="TaskError";Y.PreToolUse="PreToolUse";Y.PostToolUse="PostToolUse";Y.UserPromptSubmit="UserPromptSubmit";Y.PreCompact="PreCompact";Y.SessionShutdown="SessionShutdown"})(pJ||={});var WZ={["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"},pz=new Map(Object.values(pJ).map(($)=>[$.toLowerCase(),$])),rz=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function ZZ($){let f=cz($).toLowerCase();if(!rz.has(f))return;let J=uz($,f).trim().toLowerCase();return pz.get(J)}function Gf($){let f=[],J=new Set,W=JZ($).filter((Z)=>gz(Z));for(let Z of W)try{for(let Q of vz(Z,{withFileTypes:!0})){if(!Q.isFile())continue;let j=ZZ(Q.name);if(!j)continue;let H=dz(Z,Q.name);if(J.has(H))continue;J.add(H),f.push({fileName:j,hookEventName:WZ[j],path:H})}}catch{}return f.sort((Z,Q)=>Z.path.localeCompare(Q.path))}function iJ($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))f[J]=typeof W==="string"?W:JSON.stringify(W);return f}function rJ($,f,J){let W=J instanceof Error?`: ${J.message}`:"",Z=`${f}${W}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function sz($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
555
- `),W=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:W.length>0?W:void 0}}function oz($){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 QZ($){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",W={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:W,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function ez($){let f=$.trim();if(!f)return{};let W=f.split(`
556
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function $_($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,Z)=>{let Q=!1,j=()=>{J.off("error",X),J.off("finish",A),$.off("close",Y)},H=(V)=>{if(Q)return;if(Q=!0,j(),V){let B=V.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){W();return}Z(V);return}W()},X=(V)=>H(V),A=()=>H(),Y=()=>H();J.on("error",X),J.once("finish",A),$.once("close",Y);try{J.end(f)}catch(V){H(V)}})}async function VX($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await AX($,f)}catch(J){let W=W_(f.command,process.platform,J);if(!W)throw J;return await AX($,{...f,command:W})}}async function AX($,f){let J=YX(f.command,{env:f.env,debugRole:"hook"}),W=iz(J[0],J.slice(1),{cwd:f.cwd,env:HZ(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached}),Z=new Promise((B)=>{W.once("spawn",()=>B())}),Q=new Promise((B,K)=>{W.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,Q]),await $_(W,j),f.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let H="",X="",A=!1,Y;W.stdout.on("data",(B)=>{H+=B.toString()}),W.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,W.kill("SIGKILL")},f.timeoutMs);W.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:G,parseError:R}=ez(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:G,parseError:R,timedOut:A})})});return await Promise.race([V,Q])}function f_($){try{let J=az($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let Z=W.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function J_($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function W_($,f=process.platform,J){if(f!=="win32"||!J_(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function BX($){if($.length===0)return;let[f,...J]=$,W=f.replace(/\\/g,"/").toLowerCase(),Z=W.split("/").at(-1)??W;if(Z==="env")return BX(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function Z_($){let f=f_($);if(f&&f.length>0)return[...BX(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return YX(["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 Q_($){let f={};for(let J of Gf($)){if(!J.hookEventName)continue;let W=J.hookEventName,Z=f[W]??[];Z.push(Z_(J.path)),f[W]=Z}return f}async function j_($){let f;for(let J of $.commands){let W=J.join(" ");try{let Z=await VX($.payload,{command:J,cwd:$.cwd,env:HZ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){rJ($.logger,`hook command timed out: ${W}`);continue}if(Z?.parseError){rJ($.logger,`hook command returned invalid JSON control output: ${W} (${Z.parseError})`);continue}f=sz(f,oz(Z?.parsedJson))}catch(Z){rJ($.logger,`hook command failed: ${W}`,Z)}}return f}function w1($){for(let f of $.commands){let J=f.join(" ");VX($.payload,{command:f,cwd:$.cwd,env:HZ(process.env),detached:!0}).catch((W)=>{rJ($.logger,`hook command failed: ${J}`,W)})}}function i$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function jZ($,f){return{...i$($.snapshot),userMessage:f}}function KX($){return{...i$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function GX($){return{...i$($.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 PX($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function H_($){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 nJ($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(W)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...W})}
557
- `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??tz(XX(),"hooks.jsonl");XX(j),nz(j,Z,"utf8")};return{beforeRun:async(W)=>{let Z=jZ(W,"");J({...Y0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let Z=KX(W);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:iJ(Z.call.input)}});return},afterTool:async(W)=>{let Z=GX(W);J({...Y0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:iJ(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:W,result:Z})=>{let Q=i$(W);if(Z.status==="completed"){J({...Y0(Q,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||QZ(Z.error?.message)){J({...Y0(Q,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...Y0(Q,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let Z=jZ({snapshot:W.snapshot},PX(W.message.content));J({...Y0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function XZ($){let f=Q_($.workspacePath);if(!Object.values(f).some((V)=>V.length>0))return;let W=async(V,B)=>{let K=f[B]??[];if(K.length===0)return;w1({commands:K,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...Y0(V,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...Y0(V,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=f.prompt_submit??[];if(B.length>0)w1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},Q=async(V)=>{let B=f.tool_call??[];if(B.length===0)return;return j_({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...Y0(V,$),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:iJ(V.call.input)}}})},j=async(V)=>{let B=f.tool_result??[];if(B.length===0)return;w1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(V,$),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:iJ(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},H=async(V)=>{let B=f.agent_end??[];if(B.length===0)return;w1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(V,$),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},X=async(V)=>{let B=f.agent_error??[];if(B.length===0)return;w1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(V,$),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},A=async(V)=>{if(QZ(V.reason)){let K=f.agent_abort??[];if(K.length>0)w1({commands:K,cwd:$.cwd,logger:$.logger,payload:{...Y0(V,$),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;w1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(V,$),hookName:"session_shutdown",reason:V.reason}})},Y={};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)Y.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(i$(V.snapshot),B);return};if((f.prompt_submit?.length??0)>0)Y.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(jZ({snapshot:V.snapshot},PX(V.message.content)))}}if((f.tool_call?.length??0)>0)Y.beforeTool=async(V)=>{let B=await Q(KX(V));return H_(B)};if((f.tool_result?.length??0)>0)Y.afterTool=async(V)=>{await j(GX(V));return};if((f.agent_end?.length??0)>0)Y.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await H({...i$(V),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let V=Y.afterRun;Y.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:G}=B;if(G.status==="aborted"||QZ(G.error?.message)){await A({...i$(K),reason:G.error?.message});return}if(G.error)await X({...i$(K),iteration:G.iterations,error:G.error})}}return Y}function aJ($){return lJ("core.hook_config_files",XZ($))}function S1($,f){let J=$.map((W)=>W[f]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let Z;for(let Q of J){let j=await Q(W);if(!j||typeof j!=="object")continue;let H=j;Z={...Z??{},...H,stop:Z?.stop===!0||H.stop===!0?!0:H.stop,options:Z?.options||H.options?{...Z?.options??{},...H.options??{}}:void 0}}return Z}}function I2($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:S1(f,"beforeRun"),afterRun:S1(f,"afterRun"),beforeModel:S1(f,"beforeModel"),afterModel:S1(f,"afterModel"),beforeTool:S1(f,"beforeTool"),afterTool:S1(f,"afterTool"),onEvent:S1(f,"onEvent")}}import{z as n$}from"zod";var tJ=l1;var UX=n$.object({settings:l1,updatedAt:n$.string().datetime(),tokenSource:n$.enum(["manual","oauth","migration"]).default("manual")}),sJ=n$.object({version:n$.literal(1),lastUsedProvider:n$.string().min(1).optional(),providers:n$.record(n$.string(),UX)});function Pf(){return{version:1,providers:{}}}n0();import{upsertWorkspaceInfo as X_,WorkspaceManifestSchema as AZ}from"@cline/shared";class oJ{manifest;listeners=new Set;constructor($){this.manifest=AZ.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await LJ($);return this.manifest=X_(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=R1($),J=this.manifest.workspaces[f];if(J)return this.manifest=AZ.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath(f);return this.manifest=AZ.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=R1($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}B0();import{createHash as A_}from"node:crypto";var FX=new Set,RX=new Set;function Y_($){return A_("sha256").update($).digest("hex")}function V_($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function DX($){if(!$.telemetry)return;let f=Y_($.rootPath),J=$.rootCount??1;if(!FX.has(f))FX.add(f),m4($.telemetry,{root_count:J,vcs_types:V_($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!RX.has(f)){RX.add(f);let W=Error($.initError.message);W.name=$.initError.errorType||"Error",g4($.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function K_($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function G_($,f,J){if(f.length>0)for(let Q of f)J?.log(Q.message,{severity:"warn"});if($.length===0)return;let W=$.slice(0,3).map(K_).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let Q of $)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function P_($,f){let J=typeof $.thinking==="boolean",W=typeof $.reasoningEffort==="string";if(!J&&!W)return f;return{...f??{},...J?{enabled:$.thinking}:{},...W?{effort:$.reasoningEffort}:{}}}function LX($,f){return B_($,f)}function U_($){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 F_($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||R_($.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 R_($){let f=$?.trim();if(!f)return;let J=P0(f),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function D_($,f,J,W,Z){let Q=J.getProviderSettings($.providerId),j=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,H={...Q??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Q?.apiKey,baseUrl:$.baseUrl??Q?.baseUrl,headers:$.providerId==="openai-codex"?F_({sessionId:f,configHeaders:$.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:$.apiKey??Q?.auth?.accessToken??Q?.apiKey}):$.headers??Q?.headers,reasoning:P_($,Q?.reasoning),modelCatalog:j},X=Z$(H);if($.knownModels)X.knownModels=$.knownModels;if($.extensionContext)X.extensionContext=$.extensionContext;let Y=$.fetch??X.fetch??Z;if(Y)X.fetch=Y;return X}async function OX($){let{input:f,sessionId:J,providerSettingsManager:W,defaultTelemetry:Z,defaultCapabilities:Q,defaultToolPolicies:j,defaultFetch:H,onPluginEvent:X,onTeamEvent:A,createSpawnTool:Y,localRuntime:V,readSessionMetadata:B,writeSessionMetadata:K}=$,G=r$(f.config),{modelCatalogDefaults:R,userInstructionService:P,configExtensions:U,onTeamRestored:F,...z}=V??{},_=Object.keys(z).length>0?z:void 0,{workspaceInfo:D,workspaceMetadata:O,durationMs:T,vcsType:M,initError:s}=await Yj(G),Z0=_?.extensionContext,a={...Z0??{},workspace:{...D,...Z0?.workspace??{}},session:{...Z0?.session??{},sessionId:J},logger:Z0?.logger??_?.logger,telemetry:Z0?.telemetry??_?.telemetry??Z};DX({telemetry:a.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:M,durationMs:T,initError:s,featureFlagEnabled:!0});let Q0=aJ({cwd:f.config.cwd,workspacePath:G,rootSessionId:J,logger:_?.logger,workspaceInfo:D}),l=yj(_?.hooks)?void 0:nJ({rootSessionId:J,workspacePath:G,workspaceInfo:D}),i0=I2([_?.hooks,l]),c;if(LX(U,"plugins"))try{c=await q8({pluginPaths:_?.pluginPaths,workspacePath:G,cwd:f.config.cwd,onEvent:X,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:D,session:a.session,client:a.client,user:a.user,logger:a.logger,telemetry:a.telemetry,automation:a.automation}),G_(c.failures,c.warnings,_?.logger)}catch(Tf){let d=Tf instanceof Error?Tf.message:String(Tf);_?.logger?.log?.(`plugin loading failed; continuing without plugins (${d})`)}let C=HW(Q0?[Q0]:void 0,HW(_?.extensions,q6(c?.extensions))),V0=LX(U,"plugins")?bf(c?.pluginPaths??[]):void 0,p={...f.config,..._??{},sessionId:J,hooks:i0,extensions:C,extensionContext:a,telemetry:a.telemetry},c0=D_(p,J,W,R,H),e$=I2([p.hooks,p.checkpoint?.enabled===!0?LH({cwd:p.cwd,sessionId:J,logger:p.logger,createCheckpoint:p.checkpoint?.createCheckpoint,initialRunCount:U_(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:K}):void 0]),$1={...p,providerConfig:c0,workspaceMetadata:O,hooks:e$},m1=f.toolPolicies??p.toolPolicies??j,_f=F0(Q,f.capabilities),i2=_f?.requestToolApproval,C4=_f?.toolExecutors,g1=new oJ({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:f,config:$1,providerConfig:c0,workspaceMetadata:O,workspaceInfo:D,extensions:C,hooks:e$,toolPolicies:m1,requestToolApproval:i2,pluginSandboxShutdown:c?.shutdown,runtimeBuilderInput:{config:$1,hooks:e$,extensions:C,onTeamEvent:A,createSpawnTool:Y,onTeamRestored:F,userInstructionService:P,pluginSkillDirectories:V0,configExtensions:U,toolExecutors:C4,workspaceManager:g1,logger:$1.logger,telemetry:$1.telemetry}}}import{resolveDocumentsExtensionPath as L_}from"@cline/shared/storage";B0();function zX($,f,J,W,Z){if(J)u4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else v4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});O_($.telemetry,{workspacePath:W})}function O_($,f){let J=L_("Hooks"),W=Gf(f.workspacePath),Z=new Map;for(let Q of W){let j=Q.hookEventName??"unknown",H=Z.get(j)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))H.global+=1;else H.workspace+=1;Z.set(j,H)}for(let[Q,j]of Z.entries())s4($,Q,j.global,j.workspace)}function _X($,f){for(let J of f.mentions)a4($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)i4($,"file",J.length);for(let J of f.ignoredMentions)n4($,"file","not_found",J)}import{chmodSync as uX,existsSync as PZ,mkdirSync as $T,readFileSync as fT,writeFileSync as JT}from"node:fs";import{basename as cX,dirname as UZ}from"node:path";import{resolveProviderSettingsPath as WT}from"@cline/shared/storage";import{existsSync as z_,mkdirSync as __,readFileSync as T_,writeFileSync as N_}from"node:fs";import{mkdir as M_,readFile as y_,writeFile as q_}from"node:fs/promises";import{dirname as YZ,join as w_}from"node:path";import*as T0 from"@cline/llms";import{ModelCapabilitySchema as S_,ProviderCapabilitySchema as h_,ProviderClientSchema as C_,ProviderProtocolSchema as E_}from"@cline/shared";import{z as u}from"zod";var b_=u.object({id:u.string().optional(),name:u.string().optional(),maxTokens:u.number().optional(),contextWindow:u.number().optional(),maxInputTokens:u.number().optional(),capabilities:u.array(S_).optional(),supportsVision:u.boolean().optional(),supportsAttachments:u.boolean().optional(),supportsReasoning:u.boolean().optional()}).passthrough(),k_=u.object({name:u.string(),baseUrl:u.string(),defaultModelId:u.string().optional(),protocol:E_.optional(),client:C_.optional(),capabilities:u.array(h_).optional(),modelsSourceUrl:u.string().optional()}).passthrough(),TX=u.object({provider:k_.optional(),models:u.record(u.string(),b_).optional()}).passthrough(),NX=u.object({version:u.literal(1),providers:u.record(u.string(),TX)}),I_=u.object({version:u.literal(1),providers:u.record(u.string(),u.unknown())}),eJ=new Set;function MX($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function h1($){return w_(YZ($.getFilePath()),"models.json")}function $4(){return{version:1,providers:{}}}function yX($){let f=I_.safeParse($);if(!f.success)return $4();let J={};for(let[W,Z]of Object.entries(f.data.providers)){let Q=TX.safeParse(Z);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function VZ($){if(!z_($))return $4();try{let f=T_($,"utf8");return yX(JSON.parse(f))}catch{}return $4()}async function Uf($){try{let f=await y_($,"utf8");return yX(JSON.parse(f))}catch{}return $4()}function qX($,f){__(YZ($),{recursive:!0});let J=NX.parse(f);N_($,`${JSON.stringify(J,null,2)}
558
- `,"utf8")}async function f4($,f){await M_(YZ($),{recursive:!0});let J=NX.parse(f);await q_($,`${JSON.stringify(J,null,2)}
559
- `,"utf8")}function wX($,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 SX($){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 hX($){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 x_($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function CX($,f){return $??f??"openai-chat"}function EX($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function bX($,f,J){let W=new Set(f?.capabilities??J??[]);if(f?.supportsVision)W.add("images");if(f?.supportsAttachments)W.add("files");if(f?.supportsReasoning)W.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:W.size>0?[...W]:void 0}}function m_($,f){for(let[J,W]of Object.entries(f??{})){let Z=W.id?.trim()||J.trim();if(!Z)continue;T0.registerModel($,Z,bX(Z,W))}}function g_($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function v_($){return Object.assign({},...T0.resolveProviderModelCatalogKeys($).map((J)=>T0.getGeneratedModelsForProvider(J)))}function u_($){let f=$.provider.trim();if(!f||T0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let W=T0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=v_(f),Q=hX($.capabilities),j=Q.length>0?Q:void 0,H=$.model?.trim(),X={...Z,...W?.models??{}};if(H)X[H]=g_(H,X[H],j);let A=Object.keys(X).filter(Boolean),Y=H||A[0];if(!Y)return;let V=CX($.protocol,W?.provider.protocol),B=EX($.client,V,W?.provider.client);T0.registerProvider({provider:{id:f,name:W?.provider.name??MX(f),description:W?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:Y,capabilities:SX($.capabilities)??W?.provider.capabilities,source:"file"},models:X})}function J4($){for(let f of Object.values($.providers))u_(f.settings)}function x2($,f){let J=f.models??{};if(!x_(f.provider)){m_($,J);return}let W=hX(f.provider.capabilities),Z=Object.entries(J).map(([A,Y])=>({id:Y.id?.trim()||A.trim(),model:Y})).filter(({id:A})=>A.length>0),Q=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=CX(f.provider.protocol,void 0),H=EX(f.provider.client,j,void 0),X=Object.fromEntries(Z.map(({id:A,model:Y})=>[A,{...bX(A,Y,W.length>0?W:void 0),status:"active"}]));T0.registerProvider({provider:{id:$,name:f.provider.name.trim()||MX($),protocol:j,client:H,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:Q,capabilities:SX(f.provider.capabilities),source:"file"},models:X})}function kX($){let f=h1($);if(eJ.has(f))return;let J=VZ(f);for(let[W,Z]of Object.entries(J.providers))x2(W,Z);eJ.add(f)}async function IX($){let f=h1($);if(eJ.has(f))return;let J=await Uf(f);for(let[W,Z]of Object.entries(J.providers))x2(W,Z);eJ.add(f)}import{existsSync as c_,readFileSync as d_}from"node:fs";import{dirname as l_,join as BZ}from"node:path";import*as Z4 from"@cline/llms";import{resolveClineDataDir as p_}from"@cline/shared/storage";var W4="openai",gX=Z4.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,xX=128000;function vX($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;let W=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:W,accountId:J.userInfo?.id}}catch{return}}function q($){let f=$?.trim();return f?f:void 0}function mX($){if(!c_($))return;try{let f=d_($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function r_($){let f=$.dataDir??p_(),J=$.globalStatePath??BZ(f,"globalState.json"),W=$.secretsPath??BZ(f,"secrets.json"),Z=mX(J),Q=mX(W);if(!Z&&!Q)return;return{globalState:Z??{},secrets:Q??{}}}function KZ($){if($===W4)return gX;return $}function i_($,f,J,W){let Z=J==="plan"?"planMode":"actMode",Q=f===W?q(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,H={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(H?q(typeof $[H]==="string"?$[H]:void 0):void 0)??Q}function n_($,f,J){let W=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,Q=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??W,H=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!H&&X===void 0)return;return{...H?{effort:H}:{},...X!==void 0?{budgetTokens:X}:{}}}function a_($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),W=q(J.access_token),Z=q(J.refresh_token),Q=q(J.accountId);if(!W&&!Z&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...Z?{refreshToken:Z}:{},...Q?{accountId:Q}:{}}}}catch{return}}function t_($){let f=Z4.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function s_($,f,J,W){let Z=KZ($),Q=q(W==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=i_(f,$,W,Q)??t_(Z),H=n_(f,Z,W),X=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,A={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},Y={};if($==="openai-codex")Object.assign(Y,a_(J));if($==="cline")try{let U=q(J["cline:clineAccountId"]);if(U)Y.auth={...Y.auth??{},...vX(U)}}catch{}if($===W4&&f.openAiHeaders)Y.headers=f.openAiHeaders;if($==="bedrock"){let U=f.awsAuthentication==="profile"||f.awsUseProfile===!0;Y.aws={accessKey:q(J.awsAccessKey),secretKey:q(J.awsSecretKey),sessionToken:q(J.awsSessionToken),region:q(f.awsRegion),authentication:f.awsAuthentication,profile:U?q(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:q(f.awsBedrockEndpoint),customModelBaseId:q(W==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")Y.gcp={projectId:q(f.vertexProjectId),region:q(f.vertexRegion)};if($===W4&&(f.azureApiVersion||f.azureIdentity!==void 0))Y.azure={apiVersion:q(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")Y.sap={clientId:q(J.sapAiCoreClientId),clientSecret:q(J.sapAiCoreClientSecret),tokenUrl:q(f.sapAiCoreTokenUrl),resourceGroup:q(f.sapAiResourceGroup),deploymentId:q(W==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){Y.oca={mode:f.ocaMode};let U=q(J.ocaRefreshToken);if(U)Y.auth={...Y.auth??{},refreshToken:U}}if($==="qwen")Y.apiLine=f.qwenApiLine;if($==="moonshot")Y.apiLine=f.moonshotApiLine;if($==="zai")Y.apiLine=f.zaiApiLine;if($==="minimax")Y.apiLine=f.minimaxApiLine;let V={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=q(A[$]),K=q(V[$]),G={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...H?{reasoning:H}:{},...X?{timeout:X}:{},...Y},R=tJ.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function o_($,f){if($!==gX)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:xX,maxInputTokens:xX,capabilities:["streaming","tools","images"]}}}}function e_($,f){let J=new Set;for(let Z of[$.actModeApiProvider,$.planModeApiProvider]){let Q=q(Z);if(Q)J.add(Q)}if(q(f.apiKey))J.add("anthropic");if(q(f.openRouterApiKey))J.add("openrouter");if(q(f.openAiApiKey))J.add(W4);if(q(f.openAiNativeApiKey))J.add("openai-native");if(q(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(q(f.geminiApiKey))J.add("gemini");if(q(f.ollamaApiKey))J.add("ollama");if(q(f.awsAccessKey)||q(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||q($.awsProfile))J.add("bedrock");if(q($.vertexProjectId)||q($.vertexRegion))J.add("vertex");if(q(f.clineApiKey))J.add("cline");let W=vX(q(f["cline:clineAccountId"]));if(W?.accessToken||W?.refreshToken||W?.accountId)J.add("cline");if(q(f.ocaApiKey))J.add("oca");if(q(f.sapAiCoreClientId)||q(f.sapAiCoreClientSecret)||q($.sapAiCoreTokenUrl)||q($.sapAiCoreBaseUrl)||q($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function GZ($){let f=$.providerSettingsManager.read(),J=r_($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:W,secrets:Z}=J,Q=W.mode==="plan"?"plan":"act",j=e_(W,Z),H=Pf();H.providers={...f.providers},H.lastUsedProvider=f.lastUsedProvider;let X=new Date().toISOString(),A=0,Y=BZ(l_($.providerSettingsManager.getFilePath()),"models.json"),V=VZ(Y),B=0;for(let R of j){let P=KZ(R);if(H.providers[P])continue;let U=s_(R,W,Z,Q);if(!U)continue;H.providers[P]={settings:U,updatedAt:X,tokenSource:"migration"},A+=1;let F=o_(P,U);if(F&&!V.providers[P])V.providers[P]=F,B+=1}if(A===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=q(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),G=K?KZ(K):void 0;if(H.lastUsedProvider=f.lastUsedProvider??(G&&H.providers[G]?G:Object.keys(H.providers)[0]),$.providerSettingsManager.write(H),B>0)qX(Y,V);return{migrated:A>0||B>0,providerCount:Object.keys(H.providers).length,lastUsedProvider:H.lastUsedProvider}}function ZT(){return new Date().toISOString()}function QT($){if(cX($)!=="providers.json")return;let f=UZ($);if(cX(f)!=="settings")return;return UZ(f)}class a${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??WT(),this.dataDir=$.dataDir??QT(this.filePath),this.dataDir||!$.filePath)GZ({providerSettingsManager:this,dataDir:this.dataDir});if(kX(this),J4(this.read()),PZ(this.filePath))try{uX(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!PZ(this.filePath))return Pf();try{let $=fT(this.filePath,"utf8"),f=JSON.parse($),J=sJ.safeParse(f);if(J.success)return J4(J.data),J.data}catch{}return Pf()}write($){let f=sJ.parse($),J=UZ(this.filePath);if(!PZ(J))$T(J,{recursive:!0,mode:448});JT(this.filePath,`${JSON.stringify(f,null,2)}
560
- `,"utf8");try{uX(this.filePath,384)}catch{}J4(f)}saveProviderSettings($,f={}){let J=tJ.parse($),W=this.read(),Z=J.provider,Q=f.setLastUsed!==!1,j=W.providers[Z],H=f.tokenSource??j?.tokenSource??"manual",X={...W,providers:{...W.providers,[Z]:{settings:J,updatedAt:ZT(),tokenSource:H}},lastUsedProvider:Q?Z:W.lastUsedProvider};return this.write(X),X}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 Z$(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return Z$(f,$)}async refreshCatalog(){try{await K8({})}catch{}}}B0();EJ();import{execFile as jT}from"node:child_process";import{promisify as HT}from"node:util";var Ff=HT(jT);function FZ($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let Z=String(W.ref??"").trim(),Q=Number(W.createdAt??0),j=Number(W.runCount??0);if(Z.length===0||!Number.isFinite(Q)||!Number.isInteger(j)||j<1)return[];let H=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:Z,createdAt:Q,runCount:j,...H?{kind:H}:{}}]})}function dX($,f){let J=FZ($).filter((Z)=>Z.runCount<=f),W=J.at(-1);return W?{latest:W,history:J}:void 0}function XT($,f){return $.reduce((J,W)=>{if(W.runCount>f)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function lX($,f){let J=0;for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return W}throw Error(`Could not find user message for checkpoint run ${f}`)}function AT($,f){let J=lX($,f);return $.slice(0,J+1)}function pX($,f){let J=lX($,f);return $.slice(0,J)}function rX($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=XT(FZ($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let W=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:W,...$.restoreMessages!==!1?{messages:AT($.messages??[],f)}:{}}}async function iX($,f){if((await Ff("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await Ff("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await Ff("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await Ff("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await Ff("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await Ff("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}class p0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function YT($){let f=$.sessionId.trim();if(!f)throw new p0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new p0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new p0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new p0("invalid_restore","checkpointRunCount must be a positive integer");return f}class Rf{async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,W=YT({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(W);if(!Z)throw new p0("session_not_found",`Session ${W} not found`);let Q=f?await $.readMessages(W):void 0;if(f&&Q?.length===0)throw new p0("session_messages_not_found",`No messages found for session ${W}`);let j=rX({session:Z,messages:Q,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??iX)(j.cwd,j.checkpoint);let H=v$({session:Z,messages:Q});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:H};let X=dX(Z,$.checkpointRunCount),A=$.restore?.omitCheckpointMessageFromSession?pX(Q??[],$.checkpointRunCount):j.messages??[],Y={sourceSession:Z,sourceMessages:Q,sourceSnapshot:H,plan:j,restoredCheckpointMetadata:X,initialMessages:A,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new p0("invalid_restore","start is required when restore.messages is true");let V=$.buildStartInput?await $.buildStartInput(Y,$.start):$.start,B=await $.startSession(V),K=$.getStartedSessionId?.(B);if(K)await($.retainCheckpointRefs??DH)(j.cwd,K,X?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:H,...G?{restoredSnapshot:v$({session:G,messages:A})}:{}}}}import{hasRuntimeConfigExtension as TT}from"@cline/shared";import{nanoid as NT}from"nanoid";n0();import{appendFileSync as VT,existsSync as Df,mkdirSync as nX,readdirSync as BT,readFileSync as aX,renameSync as KT,writeFileSync as GT}from"node:fs";import{join as RZ}from"node:path";import{resolveTeamDataDir as PT}from"@cline/shared/storage";function tX(){return new Date().toISOString()}function DZ($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function sX($){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 Q4{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??PT()}init(){this.ensureTeamDir()}listTeamNames(){if(!Df(this.teamDirPath))return[];return BT(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>Df(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?sX(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!Df(J))return[];return aX(J,"utf8").split(`
561
- `).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,f)}loadRuntime($){let f=this.readEnvelope($);return{state:f?.teamState?sX(f.teamState):void 0,teammates:f?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,f){this.ensureTeamSubdir($),VT(this.historyPath($),`${JSON.stringify({ts:tX(),eventType:f.type,payload:f})}
562
- `,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let W={version:1,updatedAt:tX(),teamState:f,teammates:J},Z=this.statePath($),Q=`${Z}.tmp`;GT(Q,`${JSON.stringify(W,null,2)}
563
- `,"utf8"),KT(Q,Z)}markInProgressRunsInterrupted($,f){let J=this.readEnvelope($);if(!J?.teamState?.runs?.length)return[];let W=J.teamState.runs.filter((Q)=>Q.status==="queued"||Q.status==="running").map((Q)=>Q.id);if(W.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((Q)=>Q.status==="queued"||Q.status==="running"?{...Q,status:"interrupted",error:f,endedAt:Z}:Q)},this.persistRuntime($,J.teamState,J.teammates),W}ensureTeamDir(){if(!Df(this.teamDirPath))nX(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let f=RZ(this.ensureTeamDir(),DZ($));if(!Df(f))nX(f,{recursive:!0});return f}statePath($){return RZ(this.ensureTeamDir(),DZ($),"state.json")}historyPath($){return RZ(this.ensureTeamDir(),DZ($),"task-history.jsonl")}readEnvelope($){let f=this.statePath($);if(!Df(f))return;try{let J=JSON.parse(aX(f,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as UT,mkdirSync as FT}from"node:fs";import{join as RT}from"node:path";import{safeJsonParse as oX}from"@cline/shared";import{loadSqliteDb as DT,nowIso as LZ}from"@cline/shared/db";import{resolveDbDataDir as LT}from"@cline/shared/storage";function OT(){return LT()}function Lf($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function zT($){let f=oX($);if(!Array.isArray(f))return[];let J=[];for(let W of f){if(!W||typeof W!=="object")continue;let Z=W,Q=Z.agentId,j=Z.rolePrompt;if(typeof Q!=="string"||!Q.trim())continue;if(typeof j!=="string"||!j.trim())continue;let H={agentId:Q.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())H.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))H.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(H)}return J}function _T($){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 m2{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??OT()}init(){this.getRawDb()}ensureTeamDir(){if(!UT(this.teamDirPath))FT(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return RT(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=DT(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
547
+ Read: ${f.fileOps.readFiles.join(", ")||"none"}
548
+ Edited: ${f.fileOps.modifiedFiles.join(", ")||"none"}`];if(f.previousSummary?.trim())$.push(`Previous summary:
549
+ ${f.previousSummary.trim()}`);return $.push(`Conversation:
550
+ ${f.conversationText||"(empty)"}`),$.join(`
551
+
552
+ `)}function zX(f){let $=f.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:W,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??XX,thinking:!1}};if(!$)return J(f.activeProviderConfig);let Q=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0;return J({...Q??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Q?.apiKey,baseUrl:$.baseUrl??Q?.baseUrl,headers:$.headers??Q?.headers,knownModels:$.knownModels??Q?.knownModels,maxOutputTokens:$.maxOutputTokens??XX})}function MX(f){return{role:"user",content:`Context summary:
553
+
554
+ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function PT(f){let $=await KT(f.providerConfig),J="";for await(let Q of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}function GT(f){try{return JSON.stringify(f).length}catch{return String(f).length}}async function NX(f){let $=f.context.messages;if($.length<2)return;let J=LX($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let Q=$.slice(0,J),Z=DX(Q),W=Z>=0?FQ(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let H=OX(Q),X=GX(j),A=TX({previousSummary:W,conversationText:X,fileOps:H});f.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:$.length-J,previousSummaryChars:W?.length??0,conversationTextChars:X.length,summaryRequestChars:A.length,summaryRequestEstimatedTokens:BQ(A.length),newMessagesJsonChars:GT(j),maxInputTokens:f.context.maxInputTokens,triggerTokens:f.context.triggerTokens});let Y=await PT({providerConfig:zX({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:A,logger:f.logger});if(!Y.trim())return;let V=_X(Y,H),B=$.reduce((R,G)=>R+f.estimateMessageTokens(G),0),K=[MX({summary:V,fileOps:H,tokensBefore:B}),...$.slice(J)],P=K.reduce((R,G)=>R+f.estimateMessageTokens(G),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:B,tokensAfter:P,maxInputTokens:f.context.maxInputTokens}),{messages:K}}function wX(f){if(c2(f))return;if(typeof f.content==="string"){let J=f.content.trim();return J?{...f,content:J}:void 0}let $=f.content.filter((J)=>J.type!=="text"||J.text.trim());if($.length===0)return;return{...f,content:$.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:GQ(J.content)}:J)}}function d2(f,$){return f.reduce((J,Q)=>J+$(Q),0)}function qX(f,$){let J=Math.max(1,$),Q=Math.max(16,J*4);if(typeof f.content==="string"){let j=sf(f.content,Q).trim();return{...f,content:j||"..."}}let Z=Q,W=f.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let H=sf(j.text,Z).trim();return Z-=H.length,{...j,text:H||"..."}});return{...f,content:W}}function FT(f,$){let J=UX(f),Q=tJ(f),Z=RX(f),W=[];for(let j=0;j<f.length;j+=1){let H=wX(f[j]);if(!H)continue;W.push({index:j,message:H,estimatedTokens:$(H),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function yX(f,$,J,Q){let Z=f[$];Z.message=J,Z.estimatedTokens=Q(J)}function UT(f){let $=new Set;if(!Array.isArray(f.content))return $;for(let J of f.content)if(J.type==="tool_use")$.add(J.id);return $}function RT(f){let $=new Set;if(!Array.isArray(f.content))return $;for(let J of f.content)if(J.type==="tool_result")$.add(J.tool_use_id);return $}function CX(f){return new Set([...UT(f.message),...RT(f.message)])}function DT(f){let $=new Map;for(let J=0;J<f.length;J+=1)for(let Q of CX(f[J])){let Z=$.get(Q);if(Z)Z.add(J);else $.set(Q,new Set([J]))}return $}function LT(f,$){let J=DT(f),Q=new Set,Z=[$];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of CX(f[W]))for(let H of J.get(j)??[])if(!Q.has(H))Z.push(H)}return Q}function sJ(f,$,J,Q){let Z=d2(f.map((W)=>W.message),Q);for(let W=0;W<f.length&&Z>J;){if(!$(f[W])){W+=1;continue}let j=LT(f,W);Z-=Array.from(j).reduce((H,X)=>H+f[X].estimatedTokens,0);for(let H of Array.from(j).sort((X,A)=>A-X))f.splice(H,1)}}function OT(f,$,J){let Q=d2(f.map((W)=>W.message),J);if(Q<=$)return;for(let W=f.length-1;W>=0&&Q>$;W-=1){let j=f[W];if(j.isFirstUser)continue;let H=Math.max(KX,j.estimatedTokens-(Q-$));if(H>=j.estimatedTokens)continue;yX(f,W,qX(j.message,H),J),Q=d2(f.map((X)=>X.message),J)}if(Q<=$)return;let Z=f.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,f[Z].estimatedTokens-(Q-$));yX(f,Z,qX(f[Z].message,W),J)}}function _T(f,$){return JSON.stringify(f)!==JSON.stringify($)}function TT(f){let $=tJ(f);if($<0||$===0&&!u2(f[0]))return{compactable:f,protectedTail:[]};return{compactable:f.slice(0,$),protectedTail:f.slice($)}}function SX(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.maxInputTokens)),{compactable:J,protectedTail:Q}=TT(f.context.messages);if(J.length===0)return;let Z=FT(J,f.estimateMessageTokens);if(Z.length===0)return;sJ(Z,(X)=>X.message.role==="assistant"&&!X.isLastAssistant,$,f.estimateMessageTokens),sJ(Z,(X)=>X.message.role==="user"&&!X.isFirstUser&&!X.isLastUser,$,f.estimateMessageTokens),sJ(Z,(X)=>X.message.role==="assistant"&&X.isLastAssistant,$,f.estimateMessageTokens),sJ(Z,(X)=>X.message.role==="user"&&X.isLastUser&&!X.isFirstUser,$,f.estimateMessageTokens),OT(Z,$,f.estimateMessageTokens);let W=[...Z.map((X)=>X.message),...Q];if(!_T(f.context.messages,W))return;let j=d2([...J.map((X)=>wX(X)??X),...Q],f.estimateMessageTokens),H=d2(W,f.estimateMessageTokens);return f.logger?.debug("Performed basic compaction",{messagesBefore:f.context.messages.length,messagesAfter:W.length,messagesRemoved:f.context.messages.length-W.length,tokensBefore:j,tokensAfter:H,targetTokens:$,maxInputTokens:f.context.maxInputTokens}),{messages:W}}function EX(f){try{return JSON.stringify(f).length}catch{return String(f).length}}function zT(f){let $=0,J=0,Q=0;for(let Z of f){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=EX(W.content);$+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:$,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var MT={basic:({context:f,estimateMessageTokens:$,logger:J})=>SX({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>NX({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??PQ,f.triggerTokens):J?.preserveRecentTokens??PQ,estimateMessageTokens:Z,logger:W})};function NT(f){if(typeof f.config.reserveTokens==="number"){let Q=Math.max(0,f.config.reserveTokens),Z=Math.max(0,f.maxInputTokens-Q);return{shouldCompact:f.inputTokens>Z,triggerTokens:Z,thresholdRatio:f.maxInputTokens>0?Z/f.maxInputTokens:0}}if(typeof f.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min(f.maxInputTokens-VX,f.maxInputTokens*KQ));return{shouldCompact:f.inputTokens>Q,triggerTokens:Q,thresholdRatio:f.maxInputTokens>0?Q/f.maxInputTokens:0}}let $=f.config.thresholdRatio??KQ,J=f.maxInputTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function qT(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),Q=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:f.maxInputTokens>0?Q/f.maxInputTokens:0}}function UQ(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let Q=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},Z=FX(),W=J?.strategy??"basic",j=MT[W],H=$.mode??"auto",X=J?.compact?"custom":W;return async(A)=>{let Y=A.apiMessages.reduce((D,M)=>D+Z(M),0),V=J?.maxInputTokens??A.model.info?.maxInputTokens??A.model.info?.contextWindow??YX;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=NT({inputTokens:Y,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(f.logger?.debug("Context compaction diagnostics",{mode:H,strategy:W,iteration:A.iteration,providerId:f.providerId,modelId:f.modelId,inputTokens:Y,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:A.messages.length,apiMessageCount:A.apiMessages.length,apiMessagesJsonChars:EX(A.apiMessages),...zT(A.apiMessages)}),H==="auto"&&!B.shouldCompact)return;let K=H==="manual"?qT({inputTokens:Y,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:$.manualTargetRatio}):B,P={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId,iteration:A.iteration,messages:A.messages,model:A.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?Y/V:0},R=H==="manual"?"manual_compaction":"auto_compaction";A.emitStatusNotice?.(H==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:A.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let G=A.messages.length,F=Date.now(),U=J?.compact?await J.compact(P):await j({context:P,providerConfig:{...Q,abortSignal:A.abortSignal},compaction:J,mode:H,estimateMessageTokens:Z,logger:f.logger}),_=Date.now()-F,T=f.sessionId??A.conversationId,L={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId??void 0};if(U?.messages){let D=U.messages.reduce((M,S)=>M+Z(S),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:V,inputTokens:Y,afterTokens:D,tokensSaved:Y-D,utilizationBefore:`${(Y/V*100).toFixed(1)}%`,utilizationAfter:`${(D/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:G,messagesAfter:U.messages.length,messagesRemoved:G-U.messages.length}),X6(f.telemetry,{ulid:T,strategy:X,mode:H,messagesBefore:G,messagesAfter:U.messages.length,messagesRemoved:G-U.messages.length,tokensBefore:Y,tokensAfter:D,tokensSaved:Y-D,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:_,provider:f.providerId,modelId:f.modelId,...L})}else A6(f.telemetry,{ulid:T,strategy:X,mode:H,reason:"no_result",tokensBefore:Y,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:_,provider:f.providerId,modelId:f.modelId,...L});return U}}V0();function G0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function A0(f,$){return{inputTokens:f.inputTokens+Math.max(0,$.inputTokens??0),outputTokens:f.outputTokens+Math.max(0,$.outputTokens??0),cacheReadTokens:f.cacheReadTokens+Math.max(0,$.cacheReadTokens??0),cacheWriteTokens:f.cacheWriteTokens+Math.max(0,$.cacheWriteTokens??0),totalCost:f.totalCost+Math.max(0,$.totalCost??0)}}function oJ(f){let $=G0();for(let J of f)$=A0($,J);return $}function O1(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function eJ(f){let $=G0();for(let J of f){let Q=J.metrics;if(!Q)continue;$=A0($,{inputTokens:O1(Q.inputTokens),outputTokens:O1(Q.outputTokens),cacheReadTokens:O1(Q.cacheReadTokens),cacheWriteTokens:O1(Q.cacheWriteTokens),totalCost:O1(Q.cost)})}return $}function yT(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let Q=O1(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function wT(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function RQ(f){if(!f||typeof f!=="object")return{};let $=f;return{agentId:typeof $.agentId==="string"?$.agentId:void 0,conversationId:typeof $.conversationId==="string"?$.conversationId:void 0,parentAgentId:typeof $.parentAgentId==="string"?$.parentAgentId:void 0}}function Df(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,Q=f.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:$,agentKind:Z,conversationId:f.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:f.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:f.teamId?.trim()||void 0,teamName:f.teamName?.trim()||void 0,teamRole:Q,teamAgentId:f.teamAgentId?.trim()||void 0}}function CT(f){return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost}}function ST(f){let $=f.isPrimaryAgentEvent?[f.overrides?.agentId,f.eventMetadata.agentId,f.overrides?.teamAgentId]:[f.overrides?.teamAgentId,f.overrides?.agentId,f.eventMetadata.agentId,f.eventMetadata.conversationId];for(let J of $){let Q=J?.trim();if(Q)return Q}return f.isPrimaryAgentEvent?"root":"unknown"}function DQ(f,$,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=f,H=Z.telemetry,X=W?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,Y=RQ($),V=Df({agentId:J?.agentId??Y.agentId,conversationId:J?.conversationId??Y.conversationId,parentAgentId:J?.parentAgentId??Y.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??X?.getTeamId(),teamName:J?.teamName??X?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if($.type==="content_start"&&$.contentType==="tool"&&$.toolName==="skills"){let B=wT($.input);if(B)$6(H,{ulid:Q,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if($.type==="content_end"&&$.contentType==="tool"){let B=$.toolName??"unknown",K=!$.error;if(f6(H,{ulid:Q,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))J6(H,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:$.error,...V})}if($.type==="notice"&&$.reason==="api_error")H8(H,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:$.message,...V});if($.type==="error")H8(H,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:$.error?.message??"unknown error",...V});if($.type==="usage"&&W?.turnUsageBaseline){let B=CT($);if(A){W.turnPrimaryUsage=A0(W.turnPrimaryUsage??G0(),B);let P=A0(W.turnUsageBaseline,W.turnPrimaryUsage);f.usageBySession.set(Q,P),E1(H,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),o4(H,{ulid:Q,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:Z.modelId,...V})}else{let P=ST({isPrimaryAgentEvent:A,overrides:J,eventMetadata:Y}),R=W.turnUsageByAgent??new Map;W.turnUsageByAgent=R,R.set(P,A0(R.get(P)??G0(),B))}let K=A0(W.turnPrimaryUsage??G0(),oJ(W.turnUsageByAgent?.values()??[]));f.aggregateUsageBySession.set(Q,A0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,K))}if($.type==="iteration_end"&&A)f.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:aj($),ts:Date.now()}})}function of(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as Wz}from"@cline/shared";import{spawn as vT}from"node:child_process";import{appendFileSync as cT,readFileSync as uT}from"node:fs";import{join as dT}from"node:path";import{augmentNodeCommandForDebug as IX,withResolvedClineBuildEnv as MQ}from"@cline/shared";import{ensureHookLogDir as bX}from"@cline/shared/storage";function f4(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as ET,readdirSync as hT}from"node:fs";import{basename as bT,extname as kT,join as IT}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as hX,resolveHooksConfigSearchPaths as xT}from"@cline/shared/storage";function LQ(f){return xT(f)}var $4;((Y)=>{Y.TaskStart="TaskStart";Y.TaskResume="TaskResume";Y.TaskCancel="TaskCancel";Y.TaskComplete="TaskComplete";Y.TaskError="TaskError";Y.PreToolUse="PreToolUse";Y.PostToolUse="PostToolUse";Y.UserPromptSubmit="UserPromptSubmit";Y.PreCompact="PreCompact";Y.SessionShutdown="SessionShutdown"})($4||={});var OQ={["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"},gT=new Map(Object.values($4).map((f)=>[f.toLowerCase(),f])),mT=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function _Q(f){let $=kT(f).toLowerCase();if(!mT.has($))return;let J=bT(f,$).trim().toLowerCase();return gT.get(J)}function _1(f){let $=[],J=new Set,Q=LQ(f).filter((Z)=>ET(Z));for(let Z of Q)try{for(let W of hT(Z,{withFileTypes:!0})){if(!W.isFile())continue;let j=_Q(W.name);if(!j)continue;let H=IT(Z,W.name);if(J.has(H))continue;J.add(H),$.push({fileName:j,hookEventName:OQ[j],path:H})}}catch{}return $.sort((Z,W)=>Z.path.localeCompare(W.path))}function Q4(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,Q]of Object.entries(f))$[J]=typeof Q==="string"?Q:JSON.stringify(Q);return $}function J4(f,$,J){let Q=J instanceof Error?`: ${J.message}`:"",Z=`${$}${Q}`;if(f){try{f.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function lT(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
555
+ `),Q=[...f.appendMessages??[],...$.appendMessages??[]];return{cancel:f.cancel===!0||$.cancel===!0?!0:void 0,review:f.review===!0||$.review===!0?!0:void 0,context:J||void 0,overrideInput:$.overrideInput!==void 0?$.overrideInput:f.overrideInput,systemPrompt:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function pT(f){if(!f||typeof f!=="object")return;let $=f,J=typeof $.context==="string"?$.context:typeof $.contextModification==="string"?$.contextModification:typeof $.errorMessage==="string"?$.errorMessage:void 0;return{cancel:typeof $.cancel==="boolean"?$.cancel:void 0,review:typeof $.review==="boolean"?$.review:void 0,context:J,overrideInput:Object.hasOwn($,"overrideInput")?$.overrideInput:void 0}}function TQ(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function Y0(f,$){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:$.rootSessionId||f.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:Q,workspaceRoots:$.workspacePath?[$.workspacePath]:[],workspaceInfo:$.workspaceInfo,userId:J,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function rT(f){let $=f.trim();if(!$)return{};let Q=$.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]:$;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse hook stdout JSON"}}}async function iT(f,$){let J=f.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((Q,Z)=>{let W=!1,j=()=>{J.off("error",X),J.off("finish",A),f.off("close",Y)},H=(V)=>{if(W)return;if(W=!0,j(),V){let B=V.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){Q();return}Z(V);return}Q()},X=(V)=>H(V),A=()=>H(),Y=()=>H();J.on("error",X),J.once("finish",A),f.once("close",Y);try{J.end($)}catch(V){H(V)}})}async function xX(f,$){if($.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await kX(f,$)}catch(J){let Q=tT($.command,process.platform,J);if(!Q)throw J;return await kX(f,{...$,command:Q})}}async function kX(f,$){let J=IX($.command,{env:$.env,debugRole:"hook"}),Q=vT(J[0],J.slice(1),{cwd:$.cwd,env:MQ($.env),stdio:$.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:$.detached}),Z=new Promise((B)=>{Q.once("spawn",()=>B())}),W=new Promise((B,K)=>{Q.once("error",(P)=>K(P))}),j=JSON.stringify(f);if(await Promise.race([Z,W]),await iT(Q,j),$.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let H="",X="",A=!1,Y;Q.stdout.on("data",(B)=>{H+=B.toString()}),Q.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if(($.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,Q.kill("SIGKILL")},$.timeoutMs);Q.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:P,parseError:R}=rT(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:P,parseError:R,timedOut:A})})});return await Promise.race([V,W])}function nT(f){try{let J=uT(f,"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 aT(f){return!!(f&&typeof f==="object"&&("code"in f)&&f.code==="ENOENT")}function tT(f,$=process.platform,J){if($!=="win32"||!aT(J))return;if(f[0]!=="py"||f[1]!=="-3")return;return["python",...f.slice(2)]}function gX(f){if(f.length===0)return;let[$,...J]=f,Q=$.replace(/\\/g,"/").toLowerCase(),Z=Q.split("/").at(-1)??Q;if(Z==="env")return gX(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 f}function sT(f){let $=nT(f);if($&&$.length>0)return[...gX($)??$,f];let J=f.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",f];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return IX(["node",f],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",f];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",f]:["python3",f];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",f];return["bash",f]}function oT(f){let $={};for(let J of _1(f)){if(!J.hookEventName)continue;let Q=J.hookEventName,Z=$[Q]??[];Z.push(sT(J.path)),$[Q]=Z}return $}async function eT(f){let $;for(let J of f.commands){let Q=J.join(" ");try{let Z=await xX(f.payload,{command:J,cwd:f.cwd,env:MQ(process.env),detached:!1,timeoutMs:f.timeoutMs});if(Z?.timedOut){J4(f.logger,`hook command timed out: ${Q}`);continue}if(Z?.parseError){J4(f.logger,`hook command returned invalid JSON control output: ${Q} (${Z.parseError})`);continue}$=lT($,pT(Z?.parsedJson))}catch(Z){J4(f.logger,`hook command failed: ${Q}`,Z)}}return $}function h$(f){for(let $ of f.commands){let J=$.join(" ");xX(f.payload,{command:$,cwd:f.cwd,env:MQ(process.env),detached:!0}).catch((Q)=>{J4(f.logger,`hook command failed: ${J}`,Q)})}}function ef(f){return{agentId:f.agentId,conversationId:f.conversationId??f.runId??f.agentId,parentAgentId:f.parentAgentId??null}}function zQ(f,$){return{...ef(f.snapshot),userMessage:$}}function mX(f){return{...ef(f.snapshot),iteration:f.snapshot.iteration,call:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input}}}function vX(f){return{...ef(f.snapshot),iteration:f.snapshot.iteration,record:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}}function cX(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function fz(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}function Z4(f){let $={cwd:f.workspacePath,workspacePath:f.workspacePath,rootSessionId:f.rootSessionId,workspaceInfo:f.workspaceInfo},J=(Q)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
557
+ `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??dT(bX(),"hooks.jsonl");bX(j),cT(j,Z,"utf8")};return{beforeRun:async(Q)=>{let Z=zQ(Q,"");J({...Y0(Z,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let Z=mX(Q);J({...Y0(Z,$),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:Q4(Z.call.input)}});return},afterTool:async(Q)=>{let Z=vX(Q);J({...Y0(Z,$),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:Q4(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=ef(Q);if(Z.status==="completed"){J({...Y0(W,$),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||TQ(Z.error?.message)){J({...Y0(W,$),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...Y0(W,$),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=zQ({snapshot:Q.snapshot},cX(Q.message.content));J({...Y0(Z,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function NQ(f){let $=oT(f.workspacePath);if(!Object.values($).some((V)=>V.length>0))return;let Q=async(V,B)=>{let K=$[B]??[];if(K.length===0)return;h$({commands:K,cwd:f.cwd,logger:f.logger,payload:B==="agent_resume"?{...Y0(V,f),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...Y0(V,f),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=$.prompt_submit??[];if(B.length>0)h$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Y0(V,f),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},W=async(V)=>{let B=$.tool_call??[];if(B.length===0)return;return eT({commands:B,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...Y0(V,f),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:Q4(V.call.input)}}})},j=async(V)=>{let B=$.tool_result??[];if(B.length===0)return;h$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Y0(V,f),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:Q4(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},H=async(V)=>{let B=$.agent_end??[];if(B.length===0)return;h$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Y0(V,f),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},X=async(V)=>{let B=$.agent_error??[];if(B.length===0)return;h$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Y0(V,f),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},A=async(V)=>{if(TQ(V.reason)){let K=$.agent_abort??[];if(K.length>0)h$({commands:K,cwd:f.cwd,logger:f.logger,payload:{...Y0(V,f),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=$.session_shutdown??[];if(B.length===0)return;h$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Y0(V,f),hookName:"session_shutdown",reason:V.reason}})},Y={};if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0||($.prompt_submit?.length??0)>0){if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0)Y.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(ef(V.snapshot),B);return};if(($.prompt_submit?.length??0)>0)Y.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(zQ({snapshot:V.snapshot},cX(V.message.content)))}}if(($.tool_call?.length??0)>0)Y.beforeTool=async(V)=>{let B=await W(mX(V));return fz(B)};if(($.tool_result?.length??0)>0)Y.afterTool=async(V)=>{await j(vX(V));return};if(($.agent_end?.length??0)>0)Y.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await H({...ef(V),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if(($.agent_error?.length??0)>0||($.agent_abort?.length??0)>0||($.session_shutdown?.length??0)>0){let V=Y.afterRun;Y.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:P}=B;if(P.status==="aborted"||TQ(P.error?.message)){await A({...ef(K),reason:P.error?.message});return}if(P.error)await X({...ef(K),iteration:P.iterations,error:P.error})}}return Y}function W4(f){return f4("core.hook_config_files",NQ(f))}function b$(f,$){let J=f.map((Q)=>Q[$]).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 H=j;Z={...Z??{},...H,stop:Z?.stop===!0||H.stop===!0?!0:H.stop,options:Z?.options||H.options?{...Z?.options??{},...H.options??{}}:void 0}}return Z}}function l2(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:b$($,"beforeRun"),afterRun:b$($,"afterRun"),beforeModel:b$($,"beforeModel"),afterModel:b$($,"afterModel"),beforeTool:b$($,"beforeTool"),afterTool:b$($,"afterTool"),onEvent:b$($,"onEvent")}}import{z as f$}from"zod";var j4=t$;var uX=f$.object({settings:t$,updatedAt:f$.string().datetime(),tokenSource:f$.enum(["manual","oauth","migration"]).default("manual")}),H4=f$.object({version:f$.literal(1),lastUsedProvider:f$.string().min(1).optional(),providers:f$.record(f$.string(),uX)});function T1(){return{version:1,providers:{}}}t0();import{upsertWorkspaceInfo as $z,WorkspaceManifestSchema as qQ}from"@cline/shared";class X4{manifest;listeners=new Set;constructor(f){this.manifest=qQ.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await qJ(f);return this.manifest=$z(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=_$(f),J=this.manifest.workspaces[$];if(J)return this.manifest=qQ.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath($);return this.manifest=qQ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}getCurrentWorkspace(){let f=this.manifest.currentWorkspacePath;if(!f)return;return this.manifest.workspaces[f]}getWorkspace(f){let $=_$(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}V0();import{createHash as Jz}from"node:crypto";var dX=new Set,lX=new Set;function Qz(f){return Jz("sha256").update(f).digest("hex")}function Zz(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function pX(f){if(!f.telemetry)return;let $=Qz(f.rootPath),J=f.rootCount??1;if(!dX.has($))dX.add($),n4(f.telemetry,{root_count:J,vcs_types:Zz(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!lX.has($)){lX.add($);let Q=Error(f.initError.message);Q.name=f.initError.errorType||"Error",a4(f.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function jz(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function Hz(f,$,J){if($.length>0)for(let W of $)J?.log(W.message,{severity:"warn"});if(f.length===0)return;let Q=f.slice(0,3).map(jz).join("; "),Z=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of f)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function Xz(f,$){let J=typeof f.thinking==="boolean",Q=typeof f.reasoningEffort==="string";if(!J&&!Q)return $;return{...$??{},...J?{enabled:f.thinking}:{},...Q?{effort:f.reasoningEffort}:{}}}function rX(f,$){return Wz(f,$)}function Az(f){let $=0;for(let J of f??[]){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;$+=1}return $}function Yz(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||Vz(f.accessToken);if($.originator="cline",$.session_id=f.sessionId,$["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)$["ChatGPT-Account-Id"]=J;return $}function Vz(f){let $=f?.trim();if(!$)return;let J=F0($),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 Bz(f,$,J,Q,Z){let W=J.getProviderSettings(f.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,H=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0,X={...W??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.providerId==="openai-codex"?Yz({sessionId:$,configHeaders:f.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:f.apiKey??W?.auth?.accessToken??W?.apiKey}):f.headers??W?.headers,reasoning:Xz(f,W?.reasoning),modelCatalog:j},A={...Af(X),...H??{}};if(f.knownModels)A.knownModels=f.knownModels;if(f.extensionContext)A.extensionContext=f.extensionContext;let V=f.fetch??A.fetch??Z;if(V)A.fetch=V;return A}async function iX(f){let{input:$,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:H,onPluginEvent:X,onTeamEvent:A,createSubAgentLifecycleCallbacks:Y,createSpawnTool:V,localRuntime:B,readSessionMetadata:K,writeSessionMetadata:P}=f,R=of($.config),{modelCatalogDefaults:G,userInstructionService:F,configExtensions:U,onTeamRestored:_,...T}=B??{},L=Object.keys(T).length>0?T:void 0,{workspaceInfo:D,workspaceMetadata:M,durationMs:S,vcsType:h,initError:a}=await Sj(R),W0=L?.extensionContext,t={...W0??{},workspace:{...D,...W0?.workspace??{}},session:{...W0?.session??{},sessionId:J},logger:W0?.logger??L?.logger,telemetry:W0?.telemetry??L?.telemetry??Z};pX({telemetry:t.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:h,durationMs:S,initError:a,featureFlagEnabled:!0});let i=W4({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:L?.logger,workspaceInfo:D}),l0=nj(L?.hooks)?void 0:Z4({rootSessionId:J,workspacePath:R,workspaceInfo:D}),W$=l2([L?.hooks,l0]),l;if(rX(U,"plugins"))try{l=await x8({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:X,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:D,session:t.session,client:t.client,user:t.user,logger:t.logger,telemetry:t.telemetry,automation:t.automation}),Hz(l.failures,l.warnings,L?.logger)}catch(l$){let d4=l$ instanceof Error?l$.message:String(l$);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${d4})`)}let N=O9(i?[i]:void 0,O9(L?.extensions,c6(l?.extensions))),j0=rX(U,"plugins")?d1(l?.pluginPaths??[]):void 0,e={...$.config,...L??{},sessionId:J,hooks:W$,extensions:N,extensionContext:t,telemetry:t.telemetry},_0=Bz(e,J,Q,G,H),u$=l2([e.hooks,e.checkpoint?.enabled===!0?cH({cwd:e.cwd,sessionId:J,logger:e.logger,createCheckpoint:e.checkpoint?.createCheckpoint,initialRunCount:Az($.initialMessages),readSessionMetadata:K,writeSessionMetadata:P}):void 0]),Wf={...e,providerConfig:_0,workspaceMetadata:M,hooks:u$},a0=$.toolPolicies??e.toolPolicies??j,S1=R0(W,$.capabilities),d$=S1?.requestToolApproval,$8=S1?.toolExecutors,jf=Y?.(Wf),J8=new X4({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:$,config:Wf,providerConfig:_0,workspaceMetadata:M,workspaceInfo:D,extensions:N,hooks:u$,toolPolicies:a0,requestToolApproval:d$,pluginSandboxShutdown:l?.shutdown,runtimeBuilderInput:{config:Wf,hooks:u$,extensions:N,onTeamEvent:A,createSpawnTool:V,onTeamRestored:_,onSubAgentEvent:jf?.onSubAgentEvent,onSubAgentStart:jf?.onSubAgentStart,onSubAgentEnd:jf?.onSubAgentEnd,userInstructionService:F,pluginSkillDirectories:j0,configExtensions:U,toolExecutors:$8,toolPolicies:a0,workspaceManager:J8,logger:Wf.logger,telemetry:Wf.telemetry,requestToolApproval:d$}}}import{resolveDocumentsExtensionPath as Kz}from"@cline/shared/storage";V0();function nX(f,$,J,Q,Z){if(J)s4(f.telemetry,{ulid:$,apiProvider:f.providerId,...Z});else t4(f.telemetry,{ulid:$,apiProvider:f.providerId,...Z});Pz(f.telemetry,{workspacePath:Q})}function Pz(f,$){let J=Kz("Hooks"),Q=_1($.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",H=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))H.global+=1;else H.workspace+=1;Z.set(j,H)}for(let[W,j]of Z.entries())H6(f,W,j.global,j.workspace)}function aX(f,$){for(let J of $.mentions)W6(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)Q6(f,"file",J.length);for(let J of $.ignoredMentions)Z6(f,"file","not_found",J)}import{chmodSync as KA,existsSync as hQ,mkdirSync as iz,readFileSync as nz,writeFileSync as az}from"node:fs";import{basename as PA,dirname as bQ}from"node:path";import{resolveProviderSettingsPath as tz}from"@cline/shared/storage";import{existsSync as Gz,mkdirSync as Fz,readFileSync as Uz,writeFileSync as Rz}from"node:fs";import{mkdir as Dz,readFile as Lz,writeFile as Oz}from"node:fs/promises";import{dirname as yQ,join as _z}from"node:path";import*as q0 from"@cline/llms";import{ModelCapabilitySchema as Tz,ProviderCapabilitySchema as zz,ProviderClientSchema as Mz,ProviderProtocolSchema as Nz}from"@cline/shared";import{z as d}from"zod";var qz=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(Tz).optional(),supportsVision:d.boolean().optional(),supportsAttachments:d.boolean().optional(),supportsReasoning:d.boolean().optional()}).passthrough(),yz=d.object({name:d.string(),baseUrl:d.string(),defaultModelId:d.string().optional(),protocol:Nz.optional(),client:Mz.optional(),capabilities:d.array(zz).optional(),modelsSourceUrl:d.string().optional()}).passthrough(),tX=d.object({provider:yz.optional(),models:d.record(d.string(),qz).optional()}).passthrough(),sX=d.object({version:d.literal(1),providers:d.record(d.string(),tX)}),wz=d.object({version:d.literal(1),providers:d.record(d.string(),d.unknown())}),A4=new Set;function oX(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function k$(f){return _z(yQ(f.getFilePath()),"models.json")}function Y4(){return{version:1,providers:{}}}function eX(f){let $=wz.safeParse(f);if(!$.success)return Y4();let J={};for(let[Q,Z]of Object.entries($.data.providers)){let W=tX.safeParse(Z);if(W.success)J[Q]=W.data}return{version:1,providers:J}}function wQ(f){if(!Gz(f))return Y4();try{let $=Uz(f,"utf8");return eX(JSON.parse($))}catch{}return Y4()}async function z1(f){try{let $=await Lz(f,"utf8");return eX(JSON.parse($))}catch{}return Y4()}function fA(f,$){Fz(yQ(f),{recursive:!0});let J=sX.parse($);Rz(f,`${JSON.stringify(J,null,2)}
558
+ `,"utf8")}async function V4(f,$){await Dz(yQ(f),{recursive:!0});let J=sX.parse($);await Oz(f,`${JSON.stringify(J,null,2)}
559
+ `,"utf8")}function $A(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function JA(f){if(!f||f.length===0)return;let $=new Set;if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("tools"))$.add("tools");return $.size>0?[...$]:void 0}function QA(f){let $=new Set;if(!f||f.length===0)return[...$];if(f.includes("streaming"))$.add("streaming");if(f.includes("tools"))$.add("tools");if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("vision"))$.add("images"),$.add("files");return[...$]}function Cz(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function ZA(f,$){return f??$??"openai-chat"}function WA(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function jA(f,$,J){let Q=new Set($?.capabilities??J??[]);if($?.supportsVision)Q.add("images");if($?.supportsAttachments)Q.add("files");if($?.supportsReasoning)Q.add("reasoning");return{id:f,name:$?.name??f,maxTokens:$?.maxTokens,contextWindow:$?.contextWindow,maxInputTokens:$?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function Sz(f,$){for(let[J,Q]of Object.entries($??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;q0.registerModel(f,Z,jA(Z,Q))}}function Ez(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function hz(f){return Object.assign({},...q0.resolveProviderModelCatalogKeys(f).map((J)=>q0.getGeneratedModelsForProvider(J)))}function bz(f){let $=f.provider.trim();if(!$||q0.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let Q=q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=hz($),W=QA(f.capabilities),j=W.length>0?W:void 0,H=f.model?.trim(),X={...Z,...Q?.models??{}};if(H)X[H]=Ez(H,X[H],j);let A=Object.keys(X).filter(Boolean),Y=H||A[0];if(!Y)return;let V=ZA(f.protocol,Q?.provider.protocol),B=WA(f.client,V,Q?.provider.client);q0.registerProvider({provider:{id:$,name:Q?.provider.name??oX($),description:Q?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:Y,capabilities:JA(f.capabilities)??Q?.provider.capabilities,source:"file"},models:X})}function B4(f){for(let $ of Object.values(f.providers))bz($.settings)}function p2(f,$){let J=$.models??{};if(!Cz($.provider)){Sz(f,J);return}let Q=QA($.provider.capabilities),Z=Object.entries(J).map(([A,Y])=>({id:Y.id?.trim()||A.trim(),model:Y})).filter(({id:A})=>A.length>0),W=$.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=ZA($.provider.protocol,void 0),H=WA($.provider.client,j,void 0),X=Object.fromEntries(Z.map(({id:A,model:Y})=>[A,{...jA(A,Y,Q.length>0?Q:void 0),status:"active"}]));q0.registerProvider({provider:{id:f,name:$.provider.name.trim()||oX(f),protocol:j,client:H,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:W,capabilities:JA($.provider.capabilities),source:"file"},models:X})}function HA(f){let $=k$(f);if(A4.has($))return;let J=wQ($);for(let[Q,Z]of Object.entries(J.providers))p2(Q,Z);A4.add($)}async function XA(f){let $=k$(f);if(A4.has($))return;let J=await z1($);for(let[Q,Z]of Object.entries(J.providers))p2(Q,Z);A4.add($)}import{existsSync as kz,readFileSync as Iz}from"node:fs";import{dirname as xz,join as CQ}from"node:path";import*as P4 from"@cline/llms";import{resolveClineDataDir as gz}from"@cline/shared/storage";var K4="openai",VA=P4.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,AA=128000;function BA(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;let Q=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:Q,accountId:J.userInfo?.id}}catch{return}}function y(f){let $=f?.trim();return $?$:void 0}function YA(f){if(!kz(f))return;try{let $=Iz(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function mz(f){let $=f.dataDir??gz(),J=f.globalStatePath??CQ($,"globalState.json"),Q=f.secretsPath??CQ($,"secrets.json"),Z=YA(J),W=YA(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function SQ(f){if(f===K4)return VA;return f}function vz(f,$,J,Q){let Z=J==="plan"?"planMode":"actMode",W=$===Q?y(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,H={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`}[$];return(H?y(typeof f[H]==="string"?f[H]:void 0):void 0)??W}function cz(f,$,J){let Q=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,Z=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,W=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,j=($==="gemini"?Z:void 0)??Q,H=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,X=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!H&&X===void 0)return;return{...H?{effort:H}:{},...X!==void 0?{budgetTokens:X}:{}}}function uz(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),Q=y(J.access_token),Z=y(J.refresh_token),W=y(J.accountId);if(!Q&&!Z&&!W)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...Z?{refreshToken:Z}:{},...W?{accountId:W}:{}}}}catch{return}}function dz(f){let $=P4.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function lz(f,$,J,Q){let Z=SQ(f),W=y(Q==="plan"?$.planModeApiProvider:$.actModeApiProvider),j=vz($,f,Q,W)??dz(Z),H=cz($,Z,Q),X=typeof $.requestTimeoutMs==="number"&&Number.isInteger($.requestTimeoutMs)&&$.requestTimeoutMs>0?$.requestTimeoutMs:void 0,A={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},Y={};if(f==="openai-codex")Object.assign(Y,uz(J));if(f==="cline")try{let F=y(J["cline:clineAccountId"]);if(F)Y.auth={...Y.auth??{},...BA(F)}}catch{}if(f===K4&&$.openAiHeaders)Y.headers=$.openAiHeaders;if(f==="bedrock"){let F=$.awsAuthentication==="profile"||$.awsUseProfile===!0;Y.aws={accessKey:y(J.awsAccessKey),secretKey:y(J.awsSecretKey),sessionToken:y(J.awsSessionToken),region:y($.awsRegion),authentication:$.awsAuthentication,profile:F?y($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:y($.awsBedrockEndpoint),customModelBaseId:y(Q==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)}}if(f==="vertex")Y.gcp={projectId:y($.vertexProjectId),region:y($.vertexRegion)};if(f===K4&&($.azureApiVersion||$.azureIdentity!==void 0))Y.azure={apiVersion:y($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")Y.sap={clientId:y(J.sapAiCoreClientId),clientSecret:y(J.sapAiCoreClientSecret),tokenUrl:y($.sapAiCoreTokenUrl),resourceGroup:y($.sapAiResourceGroup),deploymentId:y(Q==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){Y.oca={mode:$.ocaMode};let F=y(J.ocaRefreshToken);if(F)Y.auth={...Y.auth??{},refreshToken:F}}if(f==="qwen")Y.apiLine=$.qwenApiLine;if(f==="moonshot")Y.apiLine=$.moonshotApiLine;if(f==="zai")Y.apiLine=$.zaiApiLine;if(f==="minimax")Y.apiLine=$.minimaxApiLine;let V={anthropic:$.anthropicBaseUrl,openai:$.openAiBaseUrl,ollama:$.ollamaBaseUrl,lmstudio:$.lmStudioBaseUrl,litellm:$.liteLlmBaseUrl,gemini:$.geminiBaseUrl,requesty:$.requestyBaseUrl,asksage:$.asksageApiUrl,dify:$.difyBaseUrl,oca:$.ocaBaseUrl,aihubmix:$.aihubmixBaseUrl,sapaicore:$.sapAiCoreBaseUrl},B=y(A[f]),K=y(V[f]),P={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...H?{reasoning:H}:{},...X?{timeout:X}:{},...Y},R=j4.safeParse(P);if(!R.success)return;return Object.keys(P).filter((F)=>F!=="provider").length>0?R.data:void 0}function pz(f,$){if(f!==VA)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model,contextWindow:AA,maxInputTokens:AA,capabilities:["streaming","tools","images"]}}}}function rz(f,$){let J=new Set;for(let Z of[f.actModeApiProvider,f.planModeApiProvider]){let W=y(Z);if(W)J.add(W)}if(y($.apiKey))J.add("anthropic");if(y($.openRouterApiKey))J.add("openrouter");if(y($.openAiApiKey))J.add(K4);if(y($.openAiNativeApiKey))J.add("openai-native");if(y($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(y($.geminiApiKey))J.add("gemini");if(y($.ollamaApiKey))J.add("ollama");if(y($.awsAccessKey)||y($.awsBedrockApiKey)||f.awsAuthentication!==void 0||f.awsUseProfile===!0||y(f.awsProfile))J.add("bedrock");if(y(f.vertexProjectId)||y(f.vertexRegion))J.add("vertex");if(y($.clineApiKey))J.add("cline");let Q=BA(y($["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)J.add("cline");if(y($.ocaApiKey))J.add("oca");if(y($.sapAiCoreClientId)||y($.sapAiCoreClientSecret)||y(f.sapAiCoreTokenUrl)||y(f.sapAiCoreBaseUrl)||y(f.sapAiResourceGroup)||f.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function EQ(f){let $=f.providerSettingsManager.read(),J=mz(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=rz(Q,Z),H=T1();H.providers={...$.providers},H.lastUsedProvider=$.lastUsedProvider;let X=new Date().toISOString(),A=0,Y=CQ(xz(f.providerSettingsManager.getFilePath()),"models.json"),V=wQ(Y),B=0;for(let R of j){let G=SQ(R);if(H.providers[G])continue;let F=lz(R,Q,Z,W);if(!F)continue;H.providers[G]={settings:F,updatedAt:X,tokenSource:"migration"},A+=1;let U=pz(G,F);if(U&&!V.providers[G])V.providers[G]=U,B+=1}if(A===0&&B===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let K=y(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),P=K?SQ(K):void 0;if(H.lastUsedProvider=$.lastUsedProvider??(P&&H.providers[P]?P:Object.keys(H.providers)[0]),f.providerSettingsManager.write(H),B>0)fA(Y,V);return{migrated:A>0||B>0,providerCount:Object.keys(H.providers).length,lastUsedProvider:H.lastUsedProvider}}function sz(){return new Date().toISOString()}function oz(f){if(PA(f)!=="providers.json")return;let $=bQ(f);if(PA($)!=="settings")return;return bQ($)}class $${filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??tz(),this.dataDir=f.dataDir??oz(this.filePath),this.dataDir||!f.filePath)EQ({providerSettingsManager:this,dataDir:this.dataDir});if(HA(this),B4(this.read()),hQ(this.filePath))try{KA(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!hQ(this.filePath))return T1();try{let f=nz(this.filePath,"utf8"),$=JSON.parse(f),J=H4.safeParse($);if(J.success)return B4(J.data),J.data}catch{}return T1()}write(f){let $=H4.parse(f),J=bQ(this.filePath);if(!hQ(J))iz(J,{recursive:!0,mode:448});az(this.filePath,`${JSON.stringify($,null,2)}
560
+ `,"utf8");try{KA(this.filePath,384)}catch{}B4($)}saveProviderSettings(f,$={}){let J=j4.parse(f),Q=this.read(),Z=J.provider,W=$.setLastUsed!==!1,j=Q.providers[Z],H=$.tokenSource??j?.tokenSource??"manual",X={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:sz(),tokenSource:H}},lastUsedProvider:W?Z:Q.lastUsedProvider};return this.write(X),X}getProviderSettings(f){return this.read().providers[f]?.settings}getLastUsedProviderSettings(){let f=this.read(),$=f.lastUsedProvider;if(!$)return;return f.providers[$]?.settings}getProviderConfig(f,$){let J=this.getProviderSettings(f);if(!J)return;return Af(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return Af($,f)}async refreshCatalog(){try{await _8({})}catch{}}}V0();vJ();import{execFile as ez}from"node:child_process";import{promisify as fM}from"node:util";var M1=fM(ez);function kQ(f){let $=f?.metadata?.checkpoint&&typeof f.metadata.checkpoint==="object"&&!Array.isArray(f.metadata.checkpoint)?f.metadata.checkpoint:void 0;return(Array.isArray($?.history)?$.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 H=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...H?{kind:H}:{}}]})}function GA(f,$){let J=kQ(f).filter((Z)=>Z.runCount<=$),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function $M(f,$){return f.reduce((J,Q)=>{if(Q.runCount>$)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function FA(f,$){let J=0;for(let Q=0;Q<f.length;Q+=1){let Z=f[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===$)return Q}throw Error(`Could not find user message for checkpoint run ${$}`)}function JM(f,$){let J=FA(f,$);return f.slice(0,J+1)}function UA(f,$){let J=FA(f,$);return f.slice(0,J)}function RA(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=$M(kQ(f.session),$);if(!J)throw Error(`No checkpoint found at or before run ${$} in session ${f.session.sessionId}`);let Q=(f.cwd?.trim()||f.session.cwd||f.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...f.restoreMessages!==!1?{messages:JM(f.messages??[],$)}:{}}}async function DA(f,$){if((await M1("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await M1("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await M1("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await M1("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await M1("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await M1("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}class i0 extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function QM(f){let $=f.sessionId.trim();if(!$)throw new i0("invalid_restore","sessionId is required");if(!f.restoreMessages&&!f.restoreWorkspace)throw new i0("invalid_restore","restore.messages or restore.workspace must be true");if(f.restoreMessages&&f.requiresStart)throw new i0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(f.checkpointRunCount)||f.checkpointRunCount<1)throw new i0("invalid_restore","checkpointRunCount must be a positive integer");return $}class N1{async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,Q=QM({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),Z=await f.getSession(Q);if(!Z)throw new i0("session_not_found",`Session ${Q} not found`);let W=$?await f.readMessages(Q):void 0;if($&&W?.length===0)throw new i0("session_messages_not_found",`No messages found for session ${Q}`);let j=RA({session:Z,messages:W,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??DA)(j.cwd,j.checkpoint);let H=pf({session:Z,messages:W});if(!$)return{checkpoint:j.checkpoint,sourceSnapshot:H};let X=GA(Z,f.checkpointRunCount),A=f.restore?.omitCheckpointMessageFromSession?UA(W??[],f.checkpointRunCount):j.messages??[],Y={sourceSession:Z,sourceMessages:W,sourceSnapshot:H,plan:j,restoredCheckpointMetadata:X,initialMessages:A,restoreMessages:$,restoreWorkspace:J,checkpointRunCount:f.checkpointRunCount};if(!f.start||!f.startSession)throw new i0("invalid_restore","start is required when restore.messages is true");let V=f.buildStartInput?await f.buildStartInput(Y,f.start):f.start,B=await f.startSession(V),K=f.getStartedSessionId?.(B);if(K)await(f.retainCheckpointRefs??vH)(j.cwd,K,X?.history??[]);let P=K&&f.readRestoredSession?await f.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:H,...P?{restoredSnapshot:pf({session:P,messages:A})}:{}}}}import{hasRuntimeConfigExtension as UM}from"@cline/shared";import{nanoid as RM}from"nanoid";t0();import{appendFileSync as ZM,existsSync as q1,mkdirSync as LA,readdirSync as WM,readFileSync as OA,renameSync as jM,writeFileSync as HM}from"node:fs";import{join as IQ}from"node:path";import{resolveTeamDataDir as XM}from"@cline/shared/storage";function _A(){return new Date().toISOString()}function xQ(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function TA(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class G4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??XM()}init(){this.ensureTeamDir()}listTeamNames(){if(!q1(this.teamDirPath))return[];return WM(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>q1(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?TA($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!q1(J))return[];return OA(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,$)}loadRuntime(f){let $=this.readEnvelope(f);return{state:$?.teamState?TA($.teamState):void 0,teammates:$?.teammates??[],interruptedRunIds:[]}}handleTeamEvent(f,$){this.ensureTeamSubdir(f),ZM(this.historyPath(f),`${JSON.stringify({ts:_A(),eventType:$.type,payload:$})}
562
+ `,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let Q={version:1,updatedAt:_A(),teamState:$,teammates:J},Z=this.statePath(f),W=`${Z}.tmp`;HM(W,`${JSON.stringify(Q,null,2)}
563
+ `,"utf8"),jM(W,Z)}markInProgressRunsInterrupted(f,$){let J=this.readEnvelope(f);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:$,endedAt:Z}:W)},this.persistRuntime(f,J.teamState,J.teammates),Q}ensureTeamDir(){if(!q1(this.teamDirPath))LA(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(f){let $=IQ(this.ensureTeamDir(),xQ(f));if(!q1($))LA($,{recursive:!0});return $}statePath(f){return IQ(this.ensureTeamDir(),xQ(f),"state.json")}historyPath(f){return IQ(this.ensureTeamDir(),xQ(f),"task-history.jsonl")}readEnvelope(f){let $=this.statePath(f);if(!q1($))return;try{let J=JSON.parse(OA($,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as AM,mkdirSync as YM}from"node:fs";import{join as VM}from"node:path";import{safeJsonParse as zA}from"@cline/shared";import{loadSqliteDb as BM,nowIso as gQ}from"@cline/shared/db";import{resolveDbDataDir as KM}from"@cline/shared/storage";function PM(){return KM()}function y1(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function GM(f){let $=zA(f);if(!Array.isArray($))return[];let J=[];for(let Q of $){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 H={agentId:W.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())H.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))H.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(H)}return J}function FM(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class r2{teamDirPath;db;constructor(f={}){this.teamDirPath=f.teamDir??PM()}init(){this.getRawDb()}ensureTeamDir(){if(!AM(this.teamDirPath))YM(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return VM(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let f=BM(this.dbPath());return this.ensureSchema(f),this.db=f,f}ensureSchema(f){if(f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.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
567
567
  );
568
- `),!$.prepare("SELECT version FROM team_store_schema_version WHERE lock = 1").get())$.prepare("INSERT INTO team_store_schema_version (lock, version) VALUES (1, 1)").run();$.exec(`
568
+ `),!f.prepare("SELECT version FROM team_store_schema_version WHERE lock = 1").get())f.prepare("INSERT INTO team_store_schema_version (lock, version) VALUES (1, 1)").run();f.exec(`
569
569
  CREATE TABLE IF NOT EXISTS team_events (
570
570
  id INTEGER PRIMARY KEY AUTOINCREMENT,
571
571
  team_name TEXT NOT NULL,
@@ -575,17 +575,17 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
575
575
  causation_id TEXT,
576
576
  correlation_id TEXT
577
577
  );
578
- `),$.exec(`
578
+ `),f.exec(`
579
579
  CREATE INDEX IF NOT EXISTS idx_team_events_name_ts
580
580
  ON team_events(team_name, ts DESC);
581
- `),$.exec(`
581
+ `),f.exec(`
582
582
  CREATE TABLE IF NOT EXISTS team_runtime_snapshot (
583
583
  team_name TEXT PRIMARY KEY,
584
584
  state_json TEXT NOT NULL,
585
585
  teammates_json TEXT NOT NULL,
586
586
  updated_at TEXT NOT NULL
587
587
  );
588
- `),$.exec(`
588
+ `),f.exec(`
589
589
  CREATE TABLE IF NOT EXISTS team_tasks (
590
590
  team_name TEXT NOT NULL,
591
591
  task_id TEXT NOT NULL,
@@ -599,7 +599,7 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
599
599
  updated_at TEXT NOT NULL,
600
600
  PRIMARY KEY(team_name, task_id)
601
601
  );
602
- `),$.exec(`
602
+ `),f.exec(`
603
603
  CREATE TABLE IF NOT EXISTS team_runs (
604
604
  team_name TEXT NOT NULL,
605
605
  run_id TEXT NOT NULL,
@@ -615,10 +615,10 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
615
615
  version INTEGER NOT NULL DEFAULT 1,
616
616
  PRIMARY KEY(team_name, run_id)
617
617
  );
618
- `),$.exec(`
618
+ `),f.exec(`
619
619
  CREATE INDEX IF NOT EXISTS idx_team_runs_status
620
620
  ON team_runs(team_name, status);
621
- `),$.exec(`
621
+ `),f.exec(`
622
622
  CREATE TABLE IF NOT EXISTS team_outcomes (
623
623
  team_name TEXT NOT NULL,
624
624
  outcome_id TEXT NOT NULL,
@@ -629,7 +629,7 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
629
629
  version INTEGER NOT NULL DEFAULT 1,
630
630
  PRIMARY KEY(team_name, outcome_id)
631
631
  );
632
- `),$.exec(`
632
+ `),f.exec(`
633
633
  CREATE TABLE IF NOT EXISTS team_outcome_fragments (
634
634
  team_name TEXT NOT NULL,
635
635
  outcome_id TEXT NOT NULL,
@@ -644,13 +644,13 @@ ${$.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 = ?",[Lf($)]);if(!f)return;let J=oX(f.state_json);if(!J)return;try{return _T(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 ?",[Lf($),f]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime($){let f=Lf($),J=this.readState(f),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f]),Z=W?zT(W.teammates_json):[];return{state:J,teammates:Z,interruptedRunIds:[]}}appendTeamEvent($,f,J,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
648
- VALUES (?, ?, ?, ?, NULL, ?)`,[Lf($),LZ(),f,JSON.stringify(J),W??null])}persistRuntime($,f,J){let W=Lf($),Z=LZ();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
647
+ `)}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}withTransaction(f){let $=this.getRawDb();$.exec("BEGIN IMMEDIATE;");try{f(),$.exec("COMMIT;")}catch(J){try{$.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((f)=>f.team_name)}readState(f){let $=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[y1(f)]);if(!$)return;let J=zA($.state_json);if(!J)return;try{return FM(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 ?",[y1(f),$]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime(f){let $=y1(f),J=this.readState($),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[$]),Z=Q?GM(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, ?)`,[y1(f),gQ(),$,JSON.stringify(J),Q??null])}persistRuntime(f,$,J){let Q=y1(f),Z=gQ();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,
652
652
  teammates_json = excluded.teammates_json,
653
- updated_at = excluded.updated_at`,[W,JSON.stringify(f),JSON.stringify(J),Z]);for(let Q of f.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
653
+ updated_at = excluded.updated_at`,[Q,JSON.stringify($),JSON.stringify(J),Z]);for(let W of $.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
654
654
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
655
655
  ON CONFLICT(team_name, task_id) DO UPDATE SET
656
656
  title = excluded.title,
@@ -660,7 +660,7 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
660
660
  depends_on_json = excluded.depends_on_json,
661
661
  summary = excluded.summary,
662
662
  version = team_tasks.version + 1,
663
- updated_at = excluded.updated_at`,[W,Q.id,Q.title,Q.description,Q.status,Q.assignee??null,JSON.stringify(Q.dependsOn??[]),Q.summary??null,Q.updatedAt.toISOString()]);for(let Q of f.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
663
+ updated_at = excluded.updated_at`,[Q,W.id,W.title,W.description,W.status,W.assignee??null,JSON.stringify(W.dependsOn??[]),W.summary??null,W.updatedAt.toISOString()]);for(let W of $.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
664
664
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
665
665
  ON CONFLICT(team_name, run_id) DO UPDATE SET
666
666
  agent_id = excluded.agent_id,
@@ -672,14 +672,14 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
672
672
  error = excluded.error,
673
673
  lease_owner = excluded.lease_owner,
674
674
  heartbeat_at = excluded.heartbeat_at,
675
- version = team_runs.version + 1`,[W,Q.id,Q.agentId,Q.taskId??null,Q.status,Q.message,Q.startedAt?Q.startedAt.toISOString():null,Q.endedAt?Q.endedAt.toISOString():null,Q.error??null,Q.leaseOwner??null,Q.heartbeatAt?Q.heartbeatAt.toISOString():null]);for(let Q of f.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
675
+ version = team_runs.version + 1`,[Q,W.id,W.agentId,W.taskId??null,W.status,W.message,W.startedAt?W.startedAt.toISOString():null,W.endedAt?W.endedAt.toISOString():null,W.error??null,W.leaseOwner??null,W.heartbeatAt?W.heartbeatAt.toISOString():null]);for(let W of $.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
676
676
  VALUES (?, ?, ?, ?, ?, ?, 1)
677
677
  ON CONFLICT(team_name, outcome_id) DO UPDATE SET
678
678
  title = excluded.title,
679
679
  status = excluded.status,
680
680
  schema_json = excluded.schema_json,
681
681
  finalized_at = excluded.finalized_at,
682
- version = team_outcomes.version + 1`,[W,Q.id,Q.title,Q.status,JSON.stringify({requiredSections:Q.requiredSections}),Q.finalizedAt?Q.finalizedAt.toISOString():null]);for(let Q of f.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
682
+ version = team_outcomes.version + 1`,[Q,W.id,W.title,W.status,JSON.stringify({requiredSections:W.requiredSections}),W.finalizedAt?W.finalizedAt.toISOString():null]);for(let W of $.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
683
683
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
684
684
  ON CONFLICT(team_name, fragment_id) DO UPDATE SET
685
685
  outcome_id = excluded.outcome_id,
@@ -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`,[W,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=Lf($),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(W.length===0)return[];let Z=LZ();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]),W.map((Q)=>Q.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function eX($={}){try{let f=new m2($);return f.init(),f}catch{let f=new Q4({teamDir:$.teamDir});return f.init(),f}}function j4($,f){return TT($,f)}function MT($,f){let J=f?.["*"]??{},W=f?.[$]??{};return{...J,...W}.enabled!==!1}function yT($,f){return $.filter((J)=>MT(J.name,f))}function $A($,f){return r1(yT($,f))}function fA(){return`team-${NT(5)}`}function OZ($,f,J,W,Z,Q,j,H){let X=s0[S$({mode:J})],A=uf(f,W,J,Z??vf);return $A(nf({cwd:$,...X,enableSkills:!!j,...A,executors:{...j?{skills:j}:{},...H??{}}}),Q)}function qT($){return OZ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,wT,$.toolExecutors).some((f)=>f.name==="skills")}var wT=async()=>"";async function ST($){let f=h0();if(!P1({filePath:f}))return{tools:[]};let J=new J2({clientFactory:KJ({settingsPath:f})}),W;try{W=await f2(J,{filePath:f})}catch(H){await J.dispose().catch(()=>{});let X=H instanceof Error?H.message:String(H);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${X}`),{tools:[]}}let Z=W.filter((H)=>H.disabled!==!0),Q=await Promise.allSettled(Z.map((H)=>PJ({serverName:H.name,provider:J}))),j=[];for(let[H,X]of Q.entries())if(X.status==="fulfilled")j.push(...X.value);else{let A=X.reason instanceof Error?X.reason.message:String(X.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[H].name}", skipping: ${A}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function hT($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function CT($){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 ET($){let f=s0[S$({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 H4{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:W,logger:Z,telemetry:Q,createSpawnTool:j,onTeamRestored:H,userInstructionService:X,configExtensions:A,toolExecutors:Y}=$,V=$.onTeamEvent??(()=>{}),B=ET(f),K=Q$(),G=[],R=f.teamName?.trim()||fA(),P=f.sessionId?.trim()||R,U=j4(A,"rules"),F=j4(A,"skills"),z=j4(A,"workflows"),_=j4(A,"plugins"),D=U||F||z,O=!1,T=Boolean(X),M=X,s;if(!M&&D)M=Zf({skills:F?{workspacePath:f.cwd,includePluginSkills:_,pluginSkillDirectories:_?$.pluginSkillDirectories:void 0,pluginPaths:f.pluginPaths,cwd:f.cwd}:{workspacePath:f.cwd},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(M)await M.start().catch(()=>{});let Z0=B.enableTools&&F&&Boolean(M)&&M?.hasConfiguredSkills(f.skills)===!0&&qT({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:f.toolPolicies,toolExecutors:Y}),a=M&&D?M.createExtension({includeRules:U,includeSkills:F,includeWorkflows:z,registerSkillsTool:Z0,allowedSkillNames:f.skills}):void 0,Q0=a?[...W??f.extensions??[],a]:W??f.extensions;if(B.enableTools){if(G.push(...OZ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,Y)),!B.disableMcpSettingsTools){let d=await ST(f.logger);G.push(...d.tools),s=d.shutdown}}let l,i0=B.enableAgentTeams?eX():void 0,c=i0?.loadRuntime(P),u0=c?.state,C=c?.teammates??[],V0=new Map(C.map((d)=>[d.agentId,d])),p=f.sessionId||R,c0,e$=[],$1=!1,m1=WJ({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:Q0,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(!this.teamRuntimeEntries.has(p))this.teamRuntimeEntries.set(p,{delegatedAgentConfigProvider:m1});let _f=()=>{if(!B.enableAgentTeams)return;let d=this.teamRuntimeEntries.get(p)??{delegatedAgentConfigProvider:m1};if(this.teamRuntimeEntries.set(p,d),l=d.runtime,!l){if(l=new q2({teamName:R,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(o)=>{if(V(o),l&&i0){if(o.type==="teammate_spawned"&&o.teammate?.rolePrompt){let J$={agentId:o.agentId,rolePrompt:o.teammate.rolePrompt,modelId:o.teammate.modelId,maxIterations:o.teammate.maxIterations};V0.set(J$.agentId,J$)}if(o.type==="teammate_shutdown"&&!CT(o.reason))V0.delete(o.agentId);i0.handleTeamEvent(P,o),i0.persistRuntime(P,l.exportState(),Array.from(V0.values()))}}}),u0)l.hydrateState(u0),$1=!0;d.runtime=l}if(!O){if(!l)return;O=!0;let o=HJ({runtime:l,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(u0),restoredTeammates:C,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(J$)=>{e$=J$,c0?.addTools(J$)},createBaseTools:B.enableTools?()=>OZ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,Y):void 0,teammateConfigProvider:m1});if($1)l.recoverActiveRuns("runtime_recovered");if(o.restoredFromPersistence)H?.();G.push(...o.tools)}return l};if(B.enableSpawnAgent&&j){let d=j();G.push({...d,execute:async(o,J$)=>{return _f(),d.execute(o,J$)}})}if(B.enableAgentTeams)_f();let i2=$A(G,f.toolPolicies),C4=i2.some((d)=>d.name===j0.SUBMIT_AND_EXIT&&d.lifecycle?.completesRun===!0),g1=B.enableAgentTeams?()=>{let d=this.teamRuntimeEntries.get(p)?.runtime;if(!d)return;let o=d.listTasks(),J$=o.some((F$)=>F$.status==="in_progress"||F$.status==="pending"),G9=d.listRuns({}),uY=G9.some((F$)=>F$.status==="running"||F$.status==="queued");if(J$||uY){let F$=o.filter((M0)=>M0.status==="in_progress"||M0.status==="pending").map((M0)=>`${M0.id} (${M0.status}): ${M0.title}`).join(", "),P9=G9.filter((M0)=>M0.status==="running"||M0.status==="queued").map((M0)=>`${M0.id} (${M0.status})`).join(", "),E4=[];if(F$)E4.push(`Unfinished tasks: ${F$}`);if(P9)E4.push(`Active runs: ${P9}`);return`[SYSTEM] You still have team obligations. ${E4.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,Tf=C4?{requireCompletionTool:!0,...g1?{completionGuard:g1}:{}}:g1?{completionGuard:g1}:void 0;return{tools:i2,logger:Z??f.logger,telemetry:Q??f.telemetry,teamRuntime:l,teamRestoredFromPersistence:Boolean(u0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(p)?.delegatedAgentConfigProvider??m1,extensions:Q0,completionPolicy:Tf,registerLeadAgent:(d)=>{if(c0=d,e$.length>0)d.addTools(r1(e$,[...K]))},shutdown:async(d)=>{if(hT(l,d),this.teamRuntimeEntries.delete(p),await s?.(),!T)M?.stop()}}}}import{getClineEnvironmentConfig as bT,isOAuthProviderId as kT}from"@cline/shared";var zZ="workos:";function IT($,f){if($==="cline")return`${zZ}${f}`;return f}function xT($,f){if($==="cline"&&f.toLowerCase().startsWith(zZ))return f.slice(zZ.length);return f}function mT($){let J=P0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function gT($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=mT(f);if(W)return W;return Date.now()-1}function vT($,f){let J=f.auth?.accessToken?.trim(),W=f.auth?.refreshToken?.trim();if(!J||!W)return null;let Z=xT($,J);if(!Z)return null;return{access:Z,refresh:W,expires:gT(f,Z),accountId:f.auth?.accountId}}function uT($,f){let J=$?.expiresAt,W=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===W}class X4 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 _Z{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new a$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!kT($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let W=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,W),W}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let W=vT($,J);if(!W)return null;let Z=await this.resolveCredentials($,J,W,f);if(!Z)throw new X4($);let Q=IT($,Z.access),j={...J.auth??{},accessToken:Q,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let H={...J,auth:j},X=!uT(J.auth,H.auth);if(X)this.providerSettingsManager.saveProviderSettings(H,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:Q,accountId:Z.accountId,refreshed:X}}async resolveCredentials($,f,J,W){if($==="cline")return j6(J,{apiBaseUrl:f.baseUrl?.trim()||bT().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if($==="oca")return G6(J,{forceRefresh:W,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return X6(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as cT}from"@cline/shared";import{nanoid as dT}from"nanoid";class JA{list($){return $?I0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((X)=>X.id===J);if(W<0)return{sessionId:f.sessionId,prompts:I0($),updated:!1};let Z=$.pendingPrompts[W];if(!Z)return{sessionId:f.sessionId,prompts:I0($),updated:!1};let Q=f.prompt===void 0?Z.prompt:cT(f.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,H={...Z,prompt:Q,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(W,1),lT($,H,W,Z.delivery),{sessionId:f.sessionId,prompts:I0($),prompt:A4(H),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:f.sessionId,prompts:I0($),removed:!1};let[Z]=$.pendingPrompts.splice(W,1);return{sessionId:f.sessionId,prompts:I0($),prompt:Z?A4(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j}=f,H=$.pendingPrompts.findIndex((X)=>X.prompt===J);if(H>=0){let[X]=$.pendingPrompts.splice(H,1),A={...X,prompt:J,mode:W??X.mode,userImages:Q??X.userImages,userFiles:j??X.userFiles};if(Z==="steer"||X.delivery==="steer")$.pendingPrompts.unshift({...A,delivery:"steer"});else $.pendingPrompts.push(A)}else{let X={id:`pending_${Date.now()}_${dT(5)}`,prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(X);else $.pendingPrompts.push(X)}return I0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((W)=>W.delivery==="steer");if(f<0)return{prompts:I0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:I0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:I0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),I0($)}clear($){return $.pendingPrompts.length=0,[]}}class TZ{deps;service=new JA;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:I0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let W=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{W=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,W&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=A4(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function A4($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function I0($){return $.pendingPrompts.map(A4)}function lT($,f,J,W){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(W==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}B0();class MZ{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let W=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=$Z(J),j=!!W&&(!Q.agentId||Q.agentId===NZ(W.agent));fZ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:NZ(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(kW(J,f),f.type==="agent_event"){let W={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};fZ(W,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let W=G$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:NZ(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(W)W1(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await IW($,f,this.deps.invokeBackendOptional),J)xW(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 X=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!X)return;let A=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!A)return;await X.ingestEvent(A);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let W=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():$,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:Q,delivery:j})}handlePluginLog($,f,J){let W=this.deps.getSession($),Z=J??W?.config.extensionContext?.logger??W?.config.logger;if(!Z||!f||typeof f!=="object")return;let Q=f,j=typeof Q.message==="string"?Q.message:"";if(!j)return;let H=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(H.sessionId??=$,typeof Q.pluginName==="string"&&Q.pluginName)H.pluginName=Q.pluginName;if(Q.level==="debug"){Z.debug(j,H);return}if(Q.level==="error"){if(Z.error)Z.error(j,H);else Z.log(j,{...H,severity:"error"});return}Z.log(j,H)}}function NZ($){return $.getAgentId()}function yZ($){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:r$($.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 qZ($,f){let J=$[f];return typeof J==="function"?J:null}async function WA($,f,...J){let W=qZ($,f);if(!W)throw Error(`session service method not available: ${f}`);return Promise.resolve(W.apply($,J))}async function ZA($,f,...J){let W=qZ($,f);if(!W)return;await Promise.resolve(W.apply($,J))}async function QA($,f,...J){let W=qZ($,f);if(!W)return;return await Promise.resolve(W.apply($,J))}n0();B0();function wZ($,f,J,W){return Wf({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=f.enableTools?nf({cwd:f.cwd,...s0[S$({mode:f.mode})],executors:W}):[];if(f.enableSpawnAgent)Q.push(wZ($,f,J,W));return r1(Q)},onSubAgentEvent:(Q)=>$.onAgentEvent(J,f,Q),onSubAgentStart:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let H=G$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId});if(H)W1(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...H});s2(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...H}),$.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime,H=$.subAgentStarts.get(Q.subAgentId),X=H?Date.now()-H.startedAt:0,A=Q.result?.text?Q.result.text.split(`
695
- `).length:0;s2(f.telemetry,{event:"ended",ulid:J,durationMs:X,outputLines:A,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...G$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as pT,stat as rT}from"node:fs/promises";var iT=20480000;async function jA($){let f=await rT($);if(!f.isFile())throw Error("Path is not a file");if(f.size>iT)throw Error("File is too large to read into context.");let J=await pT($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var HA=5000;function g2($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function fN($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=g2(f.inputTokens),W=g2(f.outputTokens),Z=g2(f.cacheReadTokens),Q=g2(f.cacheWriteTokens),j=g2(f.totalCost);if(J===void 0||W===void 0||Z===void 0||Q===void 0||j===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:Z,cacheWriteTokens:Q,totalCost:j}}function JN($,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 t${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new R2;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new Rf;constructor($){let f=aT();if(f)$N(f);let J=y1($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new H4,this.createAgentInstance=$.createAgent??((W)=>new h$(W)),this.defaultCapabilities=F0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new a$,this.oauthTokenManager=$.oauthTokenManager??new _Z({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new TZ({getSession:(W)=>this.sessions.get(W),emit:(W)=>this.emit(W),send:(W)=>this.runTurn(W)}),this.pendingPrompts={list:async(W)=>this.pendingPromptsController.list(W.sessionId),update:async(W)=>this.pendingPromptsController.update(W),delete:async(W)=>this.pendingPromptsController.delete(W)},this.eventBridge=new MZ({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,Z,Q)=>{this.invoke("persistSessionMessages",W,Z,Q)},enqueuePendingPrompt:(W,Z)=>this.pendingPromptsController.enqueue(W,Z),invokeBackendOptional:(W,...Z)=>this.invokeOptional(W,...Z)})}async startSession($){let f=$.source??U0.CLI,J=n(),W=$.config.sessionId?.trim()??"",Z=W||sT(),Q=$,j=Q.initialMessages??[],H=j.length>0?dJ(j):G0(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=SZ(X,Z),Y=SZ(A,`${Z}.messages.json`),V=SZ(A,`${Z}.json`),B=r$($.config),K=_0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:B,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:Y}),G;if(W.length>0&&j.length>0&&!Q.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",Z);if(C)K=C,G={manifestPath:V,messagesPath:C.messages_path||Y,manifest:C}}let P=await this.seedAggregateUsageFromArtifacts({initialUsage:H,sessionDir:A,rootMessagesPath:G?.messagesPath??Y,manifest:K});this.usageBySession.set(Z,H),this.aggregateUsageBySession.set(Z,P);let U=F0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,z=$.localRuntime,_=z?.extensionContext?.logger??z?.logger,D=z?.extensionContext?.automation,O;O=await OX({input:Q,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,C.payload,_);return}this.eventBridge.handlePluginEvent(Z,C,D)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(Z,C),O.config.onTeamEvent?.(C)},createSpawnTool:()=>wZ({getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,V0,p)=>this.eventBridge.dispatchAgentEvent(C,V0,p),invokeBackendOptional:(C,...V0)=>this.invokeOptional(C,...V0)},O.config,Z,F),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(Z,()=>C)}});let T=await this.runtimeBuilder.build(O.runtimeBuilderInput),M=O.config,s=O.providerConfig;if(T.teamRuntime&&!M.teamName?.trim())M.teamName=T.teamRuntime.getTeamName();let Z0=[...T.tools,...M.extraTools??[]],a=T.extensions??O.extensions,Q0={sessionId:Z,providerId:s.providerId,modelId:s.modelId,apiKey:s.apiKey,baseUrl:s.baseUrl,headers:s.headers,knownModels:s.knownModels,providerConfig:s,thinking:M.thinking,reasoningEffort:M.reasoningEffort??s.reasoningEffort,systemPrompt:M.systemPrompt,maxIterations:M.maxIterations,execution:M.execution,prepareTurn:eW(M),tools:Z0,hooks:O.hooks,extensions:a,hookErrorMode:M.hookErrorMode,initialMessages:O.effectiveInput.initialMessages,userFileContentLoader:jA,toolPolicies:O.toolPolicies,requestToolApproval:O.requestToolApproval?async(C)=>{let V0=O.requestToolApproval,p=this.sessions.get(Z);if(p)await this.markTurnPending(p);try{if(!V0)return{approved:!1,reason:"Tool approval callback is not configured."};return await V0(C)}finally{let c0=this.sessions.get(Z);if(c0?.status==="pending")await this.markTurnRunning(c0)}}:void 0,telemetry:M.telemetry,onConsecutiveMistakeLimitReached:M.onConsecutiveMistakeLimitReached,completionPolicy:T.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(Z);return C?S2(C.prompt,C.mode??M.mode):void 0},logger:T.logger??M.logger,extensionContext:M.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(Z,M,C)};Q0.hooks={...Q0.hooks,onEvent:async(C)=>{if(await O.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let V0=this.sessions.get(Z);if(!V0)return;let p=V0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,p,M.systemPrompt)}catch(c0){M.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:c0}),C1(M.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:c0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:M.providerId,modelId:M.modelId}})}}};let l=this.createAgentInstance(Q0);if(Q0.onEvent)l.subscribeEvents(Q0.onEvent);T.registerLeadAgent?.(l);let i0=G$({agentId:l.getAgentId(),conversationId:l.getConversationId(),teamId:T.teamRuntime?.getTeamId(),teamName:T.teamRuntime?.getTeamName(),teamRole:T.teamRuntime?"lead":void 0});if(zX(M,Z,W.length>0,B,i0),i0)W1(M.telemetry,{ulid:Z,modelId:M.modelId,provider:M.providerId,...i0});if(T.teamRuntime)t4(M.telemetry,{ulid:Z,teamId:T.teamRuntime.getTeamId(),teamName:T.teamRuntime.getTeamName(),leadAgentId:l.getAgentId(),restoredFromPersistence:T.teamRestoredFromPersistence===!0});let c={sessionId:Z,config:M,sessionMetadata:Q.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:T,agent:l,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:O.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,c),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(c),await this.invoke("persistSessionMessages",c.sessionId,j,c.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(c,"completed",0)}let u0;try{if(Q.prompt?.trim())if(u0=await this.executeTurn(c,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!c.interactive)await this.finalizeSingleRun(c,u0.finishReason);else await this.completeInteractiveTurn(c,u0.finishReason)}catch(C){if(c.interactive&&c.aborting)u0=await this.completeAbortedInteractiveTurn(c);else throw C1(c.config.telemetry,{component:"core",operation:"session.start",error:C,severity:"error",handled:!1,context:{sessionId:c.sessionId,providerId:c.config.providerId,modelId:c.config.modelId}}),await this.failSession(c),C}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:Y,result:u0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let W=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),W=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:W,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw C1(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=VW(this.usageBySession.get($)),J=VW(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&&!$0(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&&!$0(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 yZ(f);let J=$.trim();if(!J)return;let W=await this.getRow(J);if(W)return U2(W);let Z=await this.readManifest(J);return Z?GW(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(U2),W=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(W.has(Z.sessionId))continue;J.unshift(yZ(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 I$(J.messagesPath);let W=await this.readManifest(f);return I$(W?.messages_path)}async dispatchHookEvent($){await bj($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),W=J.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=W;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,W,J.userImages,J.userFiles);while(mW($,Z.finishReason)){let Q=await gW($);if(Q.length===0)break;let j=vW($,Q);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(w2($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),W=G0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:W}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:W,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,W){let Z=$.started||$.agent.getMessages().length>0,Q=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??G0(),H=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=H,$.turnPrimaryUsage=G0(),$.turnUsageByAgent=new Map,d4($.config.telemetry,$.sessionId,$.config.mode),Nf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let X=Z?()=>$.agent.continue(f,J,W):()=>$.agent.run(f,J,W),A=await this.runWithAuthRetry($,X,Q);$.started=!0;let Y=NJ(A.messages,A,Q);$.persistedMessages=Y;let V=cJ($.turnUsageByAgent?.values()??[]),B=A0(j,A.usage),K=A0(A0(G0(),A.usage),V),G=A0(H,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,Y,$.config.systemPrompt),this.observeTaskCompletionTool($,A),A}catch(X){throw C1($.config.telemetry,{component:"core",operation:"session.turn",error:X,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),X}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((W)=>W.name===j0.SUBMIT_AND_EXIT&&W.error===void 0))return;$.submitAndExitObserved=!0,a2($.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=r$($.config),W=eT(f.prompt).trim();if(!W)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await t8(W,J);_X($.config.telemetry,Z);let Q=S2(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),H=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),X=Array.from(new Set([...j,...H]));return{prompt:Q,userImages:f.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=r$($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),W=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(w2($))return;let J=f==="aborted"||$.aborting,W=f==="error";await this.shutdownSession($,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)a2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});gJ($);let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),C1($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){W("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){W("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),C1($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){W("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let W=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!W.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,$0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=W.endedAt??n(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=W.endedAt??n(),$.endedAt=$0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(W){if(!oT(W,$.config.providerId))throw W;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(W){if(W instanceof X4)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=new U1($);throw C1(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>tT(W)?W:hZ($,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return G$({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=A0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let W=hZ(f),Z=`${J}.messages.json`,Q;try{Q=nT($)}catch{return G0()}let j=G0();for(let H of Q){if(!H.endsWith(".messages.json"))continue;if(H===Z)continue;let X=hZ($,H);if(X===W)continue;let A=await I$(X);if(A.length===0)continue;j=A0(j,dJ(A))}return j}withPersistedAggregateUsageFloor($,f){let J=fN(f.metadata?.aggregateUsage);if(J)return JN($,J);let W=f.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=$.totalCost)return $;return{...$,totalCost:W}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:v$({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($)),HA))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(HA)).find((W)=>W.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return WA(this.sessionService,$,...f)}invokeOptional($,...f){return ZA(this.sessionService,$,...f)}invokeOptionalValue($,...f){return QA(this.sessionService,$,...f)}}function WN($){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 v2,u2;function ZN($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;sj(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function QN($){await $.reconcileDeadSessions?.().catch(()=>{})}function YA($){try{let f=new d$;return f.init(),new l$(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),AA($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new lW(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function XA($,f,J){return new t$({sessionService:J??$.sessionService??YA($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function jN($){if(v2)return v2;if(u2)return await u2;return u2=(async()=>{return v2=YA($),await QN(v2),v2})().finally(()=>{u2=void 0}),await u2}async function Y4($){let f=y1($.distinctId);$.telemetry?.setDistinctId(f);let J=WN($);if(ZN(J,$),J==="remote"){let W=$.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:W}),new hJ({endpoint:W,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let W=$.hub?.endpoint?.trim(),Z=W||await _2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:W||void 0}),new M1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let W=await NW({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(W){$.logger?.log("Using discovered local hub runtime host",{url:W});let Z=new M1({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(Q){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q}),AA($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:Q,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),XA($,f)}return XA($,f)}class CZ{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,W,Z,Q,j,H,X){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=W,this.capabilities=Z,this.logger=Q,this.telemetry=j,this.distinctId=H,this.settings=Jj($),this.pendingPrompts=Wj($),this.automation=new T6(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=X?new K2({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:AQ(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:YQ({host:$,getExtensionContext:()=>P8({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:X.dbPath,logger:X.logger,pollIntervalMs:X.pollIntervalMs,claimLeaseSeconds:X.claimLeaseSeconds,globalMaxConcurrency:X.globalMaxConcurrency,watcherDebounceMs:X.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((A)=>{if(A.type!=="ended")return;this.disposeSessionBootstrap(A.payload.sessionId)})}static async create($={}){let f=F0($.capabilities),J=await Y4({...$,capabilities:f}),W=XQ($.automation),Z=new CZ(J,$.clientName,J.runtimeAddress,$.prepare,f,$.logger,$.telemetry,$.distinctId,W?{...W,logger:$.logger}:void 0);if(W&&W.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=Zj($),J=await this.prepare?.(f);try{let W=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(x5(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>P8({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return Qj({input:W,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(W){throw await Promise.resolve(J?.dispose?.()),W}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await PW(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?x5($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>P8({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 BA,HookEventPayloadSchema as KA,parseHookEventPayload as B4,resolveHookSessionContext as KN}from"@cline/shared";import{z as E1}from"zod";import{spawn as HN}from"node:child_process";import{augmentNodeCommandForDebug as XN,withResolvedClineBuildEnv as AN}from"@cline/shared";function YN($){let f=$.trim();if(!f)return{};let W=f.split(`
696
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function VN($,f){let J=$ instanceof Error?$:Error(String($)),W=J,Z=f.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function BN($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,Z)=>{let Q=(j)=>{J.off("error",Q);let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){W();return}Z(j)};J.once("error",Q),J.end(f,(j)=>{if(J.off("error",Q),j){let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){W();return}Z(j);return}W()})})}async function V4($,f){let J=XN(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!f.detached,Z=HN(J[0],J.slice(1),{cwd:f.cwd,env:AN(f.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:W})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(G)=>{K(VN(G,J))})});if(await BN(Z,JSON.stringify($)),W){await Promise.race([Q,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let H="",X="",A=!1,Y;Z.stdout.on("data",(B)=>{H+=B.toString()}),Z.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:G,parseError:R}=YN(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:G,parseError:R,timedOut:A})})});return await Promise.race([V,j])}var GN=E1.object({contextModification:E1.string().optional(),cancel:E1.boolean().optional(),review:E1.boolean().optional(),errorMessage:E1.string().optional(),context:E1.string().optional(),overrideInput:E1.unknown().optional()}).passthrough();var PN=["agent","hook"];async function K4($,f={}){let J=f.command??PN;return await V4($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function GA($){return $ instanceof Error?$:Error(String($))}function UN($){if(!$||typeof $!=="object")return;let f=GN.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 VA($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))if(typeof W==="string")f[J]=W;else f[J]=JSON.stringify(W);return f}function P$($,f,J){let W=J.env??process.env,Z=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:KN(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function FN($){return{name:$.name,message:$.message,stack:$.stack}}function RN($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function DN($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function LN($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function ON($){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 zN($){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 b1($,f){try{let J=await K4($,{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?.(GA(J),$)}}function PA($={}){return{hooks:{beforeRun:async(H)=>{let X=DN(H);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let Y={...P$("agent_resume",X,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await b1(Y,$)}else{let Y={...P$("agent_start",X,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await b1(Y,$)}return},beforeTool:async(H)=>{let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...P$("tool_call",X,$),hookName:"tool_call",iteration:H.snapshot.iteration,tool_call:{id:H.toolCall.toolCallId,name:H.toolCall.toolName,input:H.input},preToolUse:{toolName:H.toolCall.toolName,parameters:VA(H.input)}};try{let Y=await K4(A,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:A,result:Y,detached:!1}),Y?.timedOut)throw Error("tool_call hook command timed out");if(Y?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${Y.parseError}`);return zN(UN(Y?.parsedJson))}catch(Y){$.onDispatchError?.(GA(Y),A);return}},afterTool:async(H)=>{let X=ON(H),A={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},Y={...P$("tool_result",A,$),hookName:"tool_result",iteration:H.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:VA(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await b1(Y,$);return},afterRun:async({snapshot:H,result:X})=>{let A={agentId:H.agentId,conversationId:H.conversationId??H.runId??H.agentId,parentAgentId:H.parentAgentId??null};if(X.status==="completed"){let B={...P$("agent_end",A,$),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await b1(B,$);return}let Y=X.status==="aborted"||RN(X.error?.message)?"agent_abort":"agent_error",V=Y==="agent_error"?{...P$(Y,A,$),hookName:Y,iteration:X.iterations,error:FN(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...P$(Y,A,$),hookName:Y,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await b1(V,$)},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...P$("prompt_submit",X,$),hookName:"prompt_submit",userPromptSubmit:{prompt:LN(H.message.content),attachments:[]}};await b1(A,$)}},shutdown:async({agentId:H,conversationId:X,parentAgentId:A,reason:Y})=>{let V={...P$("session_shutdown",{agentId:H,conversationId:X,parentAgentId:A},$),hookName:"session_shutdown",reason:Y};await b1(V,$)}}}import{createSessionId as _N}from"@cline/shared";function x0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function UA($,f,J){return{version:$.version,requestId:$.requestId??_N("hubreq_"),ok:!1,error:{code:f,message:J}}}class G4{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return x0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return x0($,{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 x0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return x0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return x0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return x0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return x0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return x0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return x0($,{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 x0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return x0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return x0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return UA($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return UA($,"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 U4($){return $?new Date($).getTime():void 0}function TN($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function P4($){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:U4($.nextRunAt),lastRunAt:U4($.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:TN($)}}function NN($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function EZ($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:U4($.startedAt),endedAt:U4($.completedAt),status:NN($.status),errorMessage:$.error}}class F4{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new B2({dbPath:$.dbPath}),this.materializer=new H2({store:this.store}),this.runner=new X2({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(n5($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return P4(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?P4(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>P4(f))}updateSchedule($,f){if(f.cronPattern!==void 0)n5(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let W=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule($,{...f,scheduleId:$});return Q?P4(Q):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return EZ(J,$)}triggerScheduleNowDetached($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;return this.runner.tick().catch(()=>{return}),EZ(f,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let Q=f??this.store.getSpec(Z.specId);if(!Q||Q.source!=="hub-schedule")return;return EZ(Z,Q.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,Z=0,Q;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!Q&&j.status!=="success"&&j.status!=="completed")Q=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,W+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:W>0?Z/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}O4();function nN($,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 aN="cline-hub-auth.";function tN($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function sN($,f){let J=new URL($),W=new URL(f);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function oN($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=R0(),W=await K0(J.discoveryPath);if(W?.url&&sN($.toString(),W.url))return W.authToken;return}async function eN($={}){let f=m$($);if(!tN($)){let J=R0(),W=await K0(J.discoveryPath);if(W?.url)return W.url}return Y$(f.host,f.port,f.pathname)}async function DA($){return await new Promise((f,J)=>{(async()=>{let W=new URL($),Z=await oN(W);W.hash="";let Q=new WebSocket(W.toString(),Z?[`${aN}${Z}`]:void 0),j=new Map,H=0;Q.addEventListener("open",()=>{f({send(X){let A=X.requestId??`hub-client-${++H}`;return new Promise((Y,V)=>{j.set(A,{resolve:Y,reject:V});let B={kind:"command",envelope:{...X,requestId:A}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(X)=>{let A=JSON.parse(String(X.data));if(A.kind==="reply"&&A.envelope.requestId){let Y=j.get(A.envelope.requestId);if(Y)j.delete(A.envelope.requestId),Y.resolve(A.envelope)}}),Q.addEventListener("close",()=>{for(let X of j.values())X.reject(Error("Hub connection closed"));j.clear()}),Q.addEventListener("error",(X)=>{J(nN(X,$))})})().catch(J)})}async function Uc($){try{return(await DA($)).close(),!0}catch{return!1}}async function Fc($,f){let J=await eN($),W=await DA(J);try{return await W.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{W.close()}}function xZ($){return $?JSON.parse(JSON.stringify($)):{}}function z4($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?xZ(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 LA($,f){return $.error?.message??`hub command failed: ${f}`}function $M($){let f=xZ($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...f,error:W.message.trim()};return f}function OA($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function fM($){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 JM($){let f=xZ($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||OA(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||OA(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:$M($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class WM{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new V$({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=z4(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(F1(J))return;throw J}return z4(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(LA(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},f);if(!Z.ok)throw Error(LA(Z,"session.restore"));let Q=z4(Z.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,H=fM(Z.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:H}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((W)=>z4({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),W=this.client.subscribe((Z)=>{let Q=JM(Z);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;f.onEvent?.(Q)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),W}streamTeamProgress($,f){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;f.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{f.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class ZM{client;constructor($){this.client=new V$({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 QM}from"@cline/llms";function jM($){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 HM($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function wc($={}){let f=new t$({sessionService:new l$(new d$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||U0.CLI,interactive:!1,config:{providerId:QM(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:HM(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:jM(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 XM($){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 zA=120,mZ="...";function gZ($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=zA)return f;let J=zA-Buffer.byteLength(mZ,"utf8");if(J<=0)return mZ;let W="";for(let Z of f){if(Buffer.byteLength(W+Z,"utf8")>J)break;W+=Z}return`${W}${mZ}`}async function _A($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await I$(J)].reverse().find((X)=>X.role==="assistant"),Q=Z?XM(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",H=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:gZ(Q&&Q.length>0?Q:H.length>0?H:j),severity:"info"}}import{captureSdkError as M4,createSessionId as mM}from"@cline/shared";import{createSessionId as BM}from"@cline/shared";import{createSessionId as VM}from"@cline/shared";function AM($){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 YM($){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 _4($,f,J,W){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:AM($.status),participants:f?[...f.participants.values()]:[],metadata:YM($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...W?{aggregateUsage:{...W}}:{}}}function 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 T4($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function N0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function I1($,f,J){return{version:"v1",event:$,eventId:VM("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function m0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let W=await $.sessionHost.getAccumulatedUsage?.(f);return _4(J,$.sessionState.get(f),W?.usage,W?.aggregateUsage)}async function g0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[W,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return v$({session:J,messages:W,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function N4($,f,J,W,Z={}){let Q=$.sessionState.get(f);if(Q){if(Z.interactive!==void 0)Q.interactive=Z.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:W});return Q}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:W}]])};return $.sessionState.set(f,j),j}async function vZ($,f){let J=BM("approval_"),W=f.sessionId;if($.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{$.pendingApprovals.set(J,{sessionId:W,resolve:Q}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},W))})}function uZ($,f,J){let W=$.pendingApprovals.get(f);if(!W)return;return $.pendingApprovals.delete(f),W.resolve(J),{sessionId:W.sessionId}}function cZ($,f,J){let W=0;for(let[Z,Q]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:Q.sessionId}))continue;$.pendingApprovals.delete(Z),Q.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},Q.sessionId)),W+=1}return W}async function TA($,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,Q=f.payload?.approved===!0,j=uZ($,J,{approved:Q,reason:Z});if(!j)return b(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:Z},j.sessionId)),m(f,{approvalId:J,approved:Q})}import{createSessionId as PM}from"@cline/shared";function KM($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var NA={debug:10,info:20,warn:30,error:40,silent:50};function GM(){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(NA[$]<NA[GM()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,Q])=>[Z,KM(Q)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function dZ($,f){let J=f instanceof Error?f.stack||f.message:String(f);I("error",$,{error:J})}async function MA($,f,J,W,Z,Q){let j=PM("capreq_"),H=performance.now();return I("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((X,A)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:Q,resolve:(Y)=>{if(I(Y.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:Y.ok,error:Y.error,durationMs:Math.round(performance.now()-H)}),!Y.ok){A(Error(Y.error||`Capability ${J} was rejected by ${Z}.`));return}X(Y.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:W},f)),I("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function yA($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return b(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==W.targetClientId)return b(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return b(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return W.onProgress?.(Q),m(f,{requestId:J})}function s$($,f,J){let W=0;for(let[Z,Q]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...Q}))continue;$.pendingCapabilityRequests.delete(Z),I("warn","capability.request.cancelled",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),W+=1}return W}async function qA($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",W=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!W||!Z)return b(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,W,Q,Z);return m(f,j)}catch(Q){return b(f,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function wA($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return b(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==W.targetClientId)return b(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return b(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);$.pendingCapabilityRequests.delete(J);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,H=f.payload?.ok===!0;return I(H?"info":"warn","capability.respond",{requestId:J,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:H,error:j}),W.resolve({ok:H,payload:Q,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:H,payload:Q,error:j},W.sessionId)),m(f,{requestId:J,ok:H})}import{createSessionId as UM}from"@cline/shared";function SA($,f){let J=f.payload,W=J?.clientId?.trim()||f.clientId?.trim()||UM("client_");return $.clients.set(W,{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),m(f,{clientId:W})}function hA($,f){let J=f.clientId?.trim(),W=J?$.clients.get(J):void 0;if(!J||!W)return b(f,"client_not_found","Client is not registered with this hub.");let Z=T4(f.payload?.metadata);if(W.lastSeenAt=Date.now(),Z)W.metadata=JSON.parse(JSON.stringify(Z));return m(f)}function CA($,f,J){let W=f.clientId?.trim();if(W)$.clients.delete(W),J(W),$.publish($.buildEvent("hub.client.disconnected",{clientId:W}));return m(f)}function EA($,f){return m(f,{clients:[...$.clients.values()]})}var FM=30000;function RM($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function DM($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function LM($,f,J){let W=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${f}`;return b($,Q2,W)}function OM($){return $?$:void 0}function zM($){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 _M($,f,J,W){let Z=performance.now(),Q=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:W},H=setInterval(()=>{if(Q)return;let Y=Math.round(performance.now()-Z);I("warn","run.heartbeat",{...j,elapsedMs:Y}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:Y,...W?{timeoutMs:W}:{}},J.sessionId))},FM),X=$.sessionHost.runTurn(J);X.then((Y)=>{if(!Q)return;I("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:Y?.finishReason})},(Y)=>{if(!Q)return;I("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:Y})});let A;try{if(!W)return await X;return await Promise.race([X,new Promise((Y,V)=>{A=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${W}ms.`;Q=!0,clearInterval(H),V(Error(B)),I("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),cZ($,(K)=>K.sessionId===J.sessionId,B),s$($,(K)=>K.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((K)=>{I("error","run.timeout_abort_failed",{...j,error:K})})},W)})])}finally{if(Q=!0,clearInterval(H),A)clearTimeout(A)}}async function bA($,f){let J=N0(f),W=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!Z.trim())return b(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let Q=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,j=Array.isArray(Q?.userFiles)?Q.userFiles.filter((Y)=>typeof Y==="string"):void 0,H=zM(W);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await _M($,f,{sessionId:J,prompt:Z,mode:OM(W.mode),delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:j,timeoutMs:H},H)}catch(Y){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);if(F1(Y))return LM(f,J,Y);throw $.publish($.buildEvent("run.failed",{reason:"error",error:Y instanceof Error?Y.message:String(Y)},J)),Y}if(X){let Y=await g0($,J),V=DM(X);if($.publish($.buildEvent(RM(X.finishReason),{reason:X.finishReason,...V?{error:V}:{},result:X,...Y?{snapshot:Y}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let A=await g0($,J);return m(f,X||A?{...X?{result:X}:{},...A?{snapshot:A}:{}}:void 0)}async function kA($,f){let J=N0(f),W=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";cZ($,(Z)=>Z.sessionId===J,W);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{s$($,(Z)=>Z.sessionId===J,W)}return m(f,{applied:!0})}async function IA($,f){let J=B4(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 xA($,f){switch(f.type){case"chunk":return;case"agent_event":await TM($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,W]=await Promise.all([m0($,f.payload.sessionId),g0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},f.payload.sessionId));return}case"ended":await NM($,f);return;default:return}}async function TM($,f){let{sessionId:J,event:W}=f.payload;if(W.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:W.iteration},J));return}if(W.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},J));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){$.publish($.buildEvent("assistant.delta",{text:W.text},J));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},J));return}if(W.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},J));return}}if(W.type==="content_end"){switch(W.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:W.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:W.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},J));break}return}if(W.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens??0,cacheWriteTokens:W.cacheWriteTokens??0,totalCost:W.cost??0},totals:{inputTokens:W.totalInputTokens,outputTokens:W.totalOutputTokens,cacheReadTokens:W.totalCacheReadTokens??0,cacheWriteTokens:W.totalCacheWriteTokens??0,totalCost:W.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(W.type==="done")$.publish($.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function NM($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),W=J===f.payload.reason||J==="run.start.reply";if(W)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,Q]=await Promise.all([m0($,f.payload.sessionId),g0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await _A(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(W)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...Q?{snapshot:Q}:{}},f.payload.sessionId))}import{createSessionId as gA,parseRuntimeConfigExtensions as vA}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as jd,HUB_COMPACTION_CAPABILITY as Hd,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Xd,HUB_HOOK_CAPABILITY_PREFIX as Ad,HUB_MISTAKE_LIMIT_CAPABILITY as Yd,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Vd,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Bd,isHubToolExecutorName as MM}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Fd,HUB_COMPACTION_CAPABILITY as Rd,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Dd,HUB_HOOK_CAPABILITY_PREFIX as Ld,HUB_MISTAKE_LIMIT_CAPABILITY as Od,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as zd,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as _d}from"@cline/shared";var yM=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function x1($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function qM($,f){let J=typeof $.name==="string"?$.name.trim():"",W=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",Q=x1($.inputSchema);if(!J||!W||!Q||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:W,inputSchema:Q,...x1($.lifecycle)?{lifecycle:x1($.lifecycle)}:{}}}function pZ($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let W of $){if(!W||typeof W!=="object"||Array.isArray(W))continue;let Z=W,Q=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(Q==="tool"){let H=qM(Z,J);if(H)f.push(H);continue}if(Q==="toolExecutor"){let H=Z.executor;if(!MM(H))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:H});continue}if(Q==="hook"){let H=typeof Z.name==="string"?Z.name.trim():"";if(!H)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:H});continue}if(Q==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...x1(Z.config)?{config:x1(Z.config)}:{}});continue}if(Q==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...x1(Z.config)?{config:x1(Z.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(Q==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function mA($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function wM($){return Object.hasOwn($,"update")?$.update:$}function p2($){return $.trim().replace(/^\/+/,"").toLowerCase()}function SM($){let f=($??[]).map(p2).filter(Boolean);return f.length>0?new Set(f):void 0}function hM($,f,J){if(!J)return!0;let W=p2($),Z=p2(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function lZ($,f){let J=SM(f);return $.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>hM(W.id,W.name,J))}function CM($,f){let J=async(W,Z)=>{let Q=p2(W),H=lZ($,f).filter((B)=>B.id===Q||p2(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(H.length!==1)return H.length>1?`Skill "${W}" is ambiguous. Use one of: ${H.map((B)=>B.id).join(", ")}`:`Skill "${W}" not found.`;let X=H[0].skill,A=Z?.trim(),Y=A?`
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=y1(f),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=gQ();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
694
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[$,Z,J]),Q.map((W)=>W.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function MA(f={}){try{let $=new r2(f);return $.init(),$}catch{let $=new G4({teamDir:f.teamDir});return $.init(),$}}function F4(f,$){return UM(f,$)}function DM(f,$){let J=$?.["*"]??{},Q=$?.[f]??{};return{...J,...Q}.enabled!==!1}function LM(f,$){return f.filter((J)=>DM(J.name,$))}function mQ(f,$){return o$(LM(f,$))}var OM={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function _M(f){let $=f.trim().toLowerCase();return OM[$]??$}function TM(f,$){if($.tools===void 0)return f;let J=new Set($.tools.map(_M));if($.skills!==void 0)J.add("skills");return f.filter((Q)=>J.has(Q.name))}function NA(){return`team-${RM(5)}`}function U4(f,$,J,Q,Z,W,j,H){let X=e0[kf({mode:J})],A=t1($,Q,J,Z??a1);return mQ(J2({cwd:f,...X,enableSkills:!!j,...A,executors:{...j?{skills:j}:{},...H??{}}}),W)}function zM(f){return U4(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,MM,f.toolExecutors).some(($)=>$.name==="skills")}var MM=async()=>"";async function NM(f){let $=b0();if(!D$({filePath:$}))return{tools:[]};let J=new Y2({clientFactory:LJ({settingsPath:$})}),Q;try{Q=await A2(J,{filePath:$})}catch(H){await J.dispose().catch(()=>{});let X=H instanceof Error?H.message:String(H);return f?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${X}`),{tools:[]}}let Z=Q.filter((H)=>H.disabled!==!0),W=await Promise.allSettled(Z.map((H)=>_J({serverName:H.name,provider:J}))),j=[];for(let[H,X]of W.entries())if(X.status==="fulfilled")j.push(...X.value);else{let A=X.reason instanceof Error?X.reason.message:String(X.reason);f?.log(`[mcp] Failed to load tools from MCP server "${Z[H].name}", skipping: ${A}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function qM(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function yM(f){if(f===void 0)return!0;switch(f){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 wM(f){let $=e0[kf({mode:f.mode})];return{sessionId:f.sessionId||"",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",enableTools:f.enableTools!==!1,enableSpawnAgent:f.enableSpawnAgent??$.enableSpawnAgent??!0,enableAgentTeams:f.enableAgentTeams??$.enableAgentTeams??!0,disableMcpSettingsTools:f.disableMcpSettingsTools===!0,yolo:f.yolo===!0,missionLogIntervalSteps:typeof f.missionLogIntervalSteps==="number"&&Number.isFinite(f.missionLogIntervalSteps)?f.missionLogIntervalSteps:3,missionLogIntervalMs:typeof f.missionLogIntervalMs==="number"&&Number.isFinite(f.missionLogIntervalMs)?f.missionLogIntervalMs:120000}}class R4{teamRuntimeEntries=new Map;async build(f){let{config:$,hooks:J,extensions:Q,logger:Z,telemetry:W,createSpawnTool:j,onTeamRestored:H,userInstructionService:X,configExtensions:A,toolExecutors:Y}=f,V=f.onTeamEvent??(()=>{}),B=wM($),K=$.workspaceRoot??$.cwd,P=f.toolPolicies??$.toolPolicies,R=Yf(),G=[],F=$.teamName?.trim()||NA(),U=$.sessionId?.trim()||F,_=B.enableSpawnAgent?lJ({workspaceRoot:K}):{configs:[],errors:[]},T=_.configs.some((k)=>k.skills!==void 0),L=F4(A,"rules"),D=F4(A,"skills"),M=D||T,S=F4(A,"workflows"),h=F4(A,"plugins"),a=L||D||S,W0=!1,t=Boolean(X),i=X,l0;for(let k of _.errors)(Z??$.logger)?.log?.(`[agents] Failed to load agent config at ${k.path}: ${k.error.message}`);if(!i&&(a||T))i=B1({skills:M?{workspacePath:K,includePluginSkills:h,pluginSkillDirectories:h?f.pluginSkillDirectories:void 0,pluginPaths:$.pluginPaths,cwd:$.cwd}:{workspacePath:K},rules:{workspacePath:$.cwd},workflows:{workspacePath:$.cwd}});if(i)await i.start().catch(()=>{});let W$=B.enableTools&&D&&Boolean(i)&&i?.hasConfiguredSkills($.skills)===!0&&zM({cwd:$.cwd,providerId:$.providerId,mode:B.mode,modelId:$.modelId,toolRoutingRules:$.toolRoutingRules,toolPolicies:P,toolExecutors:Y}),l=i&&a?i.createExtension({includeRules:L,includeSkills:D,includeWorkflows:S,registerSkillsTool:W$,allowedSkillNames:$.skills}):void 0,Zf=l?[...Q??$.extensions??[],l]:Q??$.extensions;if(B.enableTools){if(G.push(...U4($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,P,void 0,Y)),!B.disableMcpSettingsTools){let k=await NM($.logger);G.push(...k.tools),l0=k.shutdown}}let N,j0=B.enableAgentTeams?MA():void 0,e=j0?.loadRuntime(U),_0=e?.state,u$=e?.teammates??[],Wf=new Map(u$.map((k)=>[k.agentId,k])),a0=$.sessionId||F,S1,d$=[],$8=!1,jf=A1({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey??"",baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:J,extensions:Zf,logger:Z??$.logger,telemetry:f.telemetry??$.telemetry,workspaceMetadata:$.workspaceMetadata});if(B.enableSpawnAgent){if(_.configs.length>0)G.push(...mQ(rJ({configProvider:jf,agents:_.configs,createSubAgentTools:(k)=>B.enableTools?TM(U4($.cwd,k.providerId??$.providerId,B.mode,k.modelId??$.modelId,$.toolRoutingRules,P,k.skills!==void 0&&i?.createSkillsExecutor?i.createSkillsExecutor(k.skills):void 0,Y),k):[],hookErrorMode:$.hookErrorMode,toolPolicies:P,requestToolApproval:f.requestToolApproval,onSubAgentEvent:f.onSubAgentEvent,onSubAgentStart:f.onSubAgentStart,onSubAgentEnd:f.onSubAgentEnd}),P))}if(!this.teamRuntimeEntries.has(a0))this.teamRuntimeEntries.set(a0,{delegatedAgentConfigProvider:jf});let J8=()=>{if(!B.enableAgentTeams)return;let k=this.teamRuntimeEntries.get(a0)??{delegatedAgentConfigProvider:jf};if(this.teamRuntimeEntries.set(a0,k),N=k.runtime,!N){if(N=new I2({teamName:F,leadAgentId:$.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(s)=>{if(V(s),N&&j0){if(s.type==="teammate_spawned"&&s.teammate?.rolePrompt){let Hf={agentId:s.agentId,rolePrompt:s.teammate.rolePrompt,modelId:s.teammate.modelId,maxIterations:s.teammate.maxIterations};Wf.set(Hf.agentId,Hf)}if(s.type==="teammate_shutdown"&&!yM(s.reason))Wf.delete(s.agentId);j0.handleTeamEvent(U,s),j0.persistRuntime(U,N.exportState(),Array.from(Wf.values()))}}}),_0)N.hydrateState(_0),$8=!0;k.runtime=N}if(!W0){if(!N)return;W0=!0;let s=PJ({runtime:N,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(_0),restoredTeammates:u$,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(Hf)=>{d$=Hf,S1?.addTools(Hf)},createBaseTools:B.enableTools?()=>U4($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,P,void 0,Y):void 0,teammateConfigProvider:jf});if($8)N.recoverActiveRuns("runtime_recovered");if(s.restoredFromPersistence)H?.();G.push(...s.tools)}return N};if(B.enableSpawnAgent&&j){let k=j();G.push({...k,execute:async(s,Hf)=>{return J8(),k.execute(s,Hf)}})}if(B.enableAgentTeams)J8();let l$=mQ(G,P),d4=l$.some((k)=>k.name==="submit_and_exit"&&k.lifecycle?.completesRun===!0),Q8=B.enableAgentTeams?()=>{let k=this.teamRuntimeEntries.get(a0)?.runtime;if(!k)return;let s=k.listTasks(),Hf=s.some((_f)=>_f.status==="in_progress"||_f.status==="pending"),EZ=k.listRuns({}),PV=EZ.some((_f)=>_f.status==="running"||_f.status==="queued");if(Hf||PV){let _f=s.filter((w0)=>w0.status==="in_progress"||w0.status==="pending").map((w0)=>`${w0.id} (${w0.status}): ${w0.title}`).join(", "),hZ=EZ.filter((w0)=>w0.status==="running"||w0.status==="queued").map((w0)=>`${w0.id} (${w0.status})`).join(", "),l4=[];if(_f)l4.push(`Unfinished tasks: ${_f}`);if(hZ)l4.push(`Active runs: ${hZ}`);return`[SYSTEM] You still have team obligations. ${l4.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,KV=d4?{requireCompletionTool:!0,...Q8?{completionGuard:Q8}:{}}:Q8?{completionGuard:Q8}:void 0;return{tools:l$,logger:Z??$.logger,telemetry:W??$.telemetry,teamRuntime:N,teamRestoredFromPersistence:Boolean(_0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(a0)?.delegatedAgentConfigProvider??jf,extensions:Zf,completionPolicy:KV,registerLeadAgent:(k)=>{if(S1=k,d$.length>0)k.addTools(o$(d$,[...R]))},shutdown:async(k)=>{if(qM(N,k),this.teamRuntimeEntries.delete(a0),await l0?.(),!t)i?.stop()}}}}function CM(f,$){let J=f?.expiresAt,Q=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===Q}class D4 extends Error{providerId;constructor(f){super(`OAuth credentials for provider "${f}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=f}}class vQ{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new $$,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){let $=B0(f.providerId);if(!$)return null;return this.resolveWithSingleFlight($.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let Q=this.resolveProviderApiKeyInternal(f,$).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,Q),Q}async resolveProviderApiKeyInternal(f,$){let J=B0(f);if(!J)return null;let Q=this.providerSettingsManager.getProviderSettings(J.storageProviderId);if(!Q)return null;let Z=q6(f,Q);if(!Z)return null;let W=await J.refresh({settings:Q,credentials:Z,forceRefresh:$,telemetry:this.telemetry});if(!W)throw new D4(f);let j=k1({manager:this.providerSettingsManager,providerId:f,settings:Q,credentials:W,setLastUsed:!1,save:!1}),H=!CM(Q.auth,j.auth);if(H)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:J.getApiKey(j)??W.access,accountId:W.accountId,refreshed:H}}}import{normalizeUserInput as SM}from"@cline/shared";import{nanoid as EM}from"nanoid";class qA{list(f){return f?m0(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),Q=f.pendingPrompts.findIndex((X)=>X.id===J);if(Q<0)return{sessionId:$.sessionId,prompts:m0(f),updated:!1};let Z=f.pendingPrompts[Q];if(!Z)return{sessionId:$.sessionId,prompts:m0(f),updated:!1};let W=$.prompt===void 0?Z.prompt:SM($.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=$.delivery??Z.delivery,H={...Z,prompt:W,mode:$.mode??Z.mode,delivery:j};return f.pendingPrompts.splice(Q,1),hM(f,H,Q,Z.delivery),{sessionId:$.sessionId,prompts:m0(f),prompt:L4(H),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),Q=f.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:$.sessionId,prompts:m0(f),removed:!1};let[Z]=f.pendingPrompts.splice(Q,1);return{sessionId:$.sessionId,prompts:m0(f),prompt:Z?L4(Z):void 0,removed:!0}}enqueue(f,$){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=$,H=f.pendingPrompts.findIndex((X)=>X.prompt===J);if(H>=0){let[X]=f.pendingPrompts.splice(H,1),A={...X,prompt:J,mode:Q??X.mode,userImages:W??X.userImages,userFiles:j??X.userFiles};if(Z==="steer"||X.delivery==="steer")f.pendingPrompts.unshift({...A,delivery:"steer"});else f.pendingPrompts.push(A)}else{let X={id:`pending_${Date.now()}_${EM(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")f.pendingPrompts.unshift(X);else f.pendingPrompts.push(X)}return m0(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if($<0)return{prompts:m0(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:m0(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:m0(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),m0(f)}clear(f){return f.pendingPrompts.length=0,[]}}class cQ{deps;service=new qA;constructor(f){this.deps=f}list(f){return this.service.list(this.deps.getSession(f))}update(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=this.service.update($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}delete(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=this.service.delete($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}enqueue(f,$){let J=this.deps.getSession(f);if(!J||J.aborting)return;this.service.enqueue(J,$),this.emitPrompts(J),this.scheduleDrain(f,J)}consumeSteer(f){let $=this.deps.getSession(f);if(!$)return;let{entry:J}=this.service.consumeSteer($);if(!J)return;return this.emitPrompts($),this.emitSubmitted($,J),J}clearAborted(f){if(f.pendingPrompts.length===0)return;this.service.clear(f),this.emitPrompts(f)}emitPrompts(f){this.deps.emit({type:"pending_prompts",payload:{sessionId:f.sessionId,prompts:m0(f)}})}scheduleDrain(f,$){if($.pendingPrompts.length===0||$.aborting||$.drainingPendingPrompts||!$.agent.canStartRun())return;queueMicrotask(()=>{this.drain(f)})}async drain(f){let $=this.deps.getSession(f);if(!$)return;if($.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront($,J),this.emitPrompts($)}finally{if($.drainingPendingPrompts=!1,Q&&$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=L4($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function L4(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function m0(f){return f.pendingPrompts.map(L4)}function hM(f,$,J,Q){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(Q==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}V0();class dQ{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let Q=this.deps.getSession(f),Z={sessionId:f,config:$,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=RQ(J),j=!!Q&&(!W.agentId||W.agentId===uQ(Q.agent));DQ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:uQ(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(e9(J,$),$.type==="agent_event"){let Q={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};DQ(Q,$.event,{agentId:$.agentId,teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let Q=Df({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:uQ(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(Q)X$(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await fQ(f,$,this.deps.invokeBackendOptional),J)$Q(J,f,$,this.deps.emit)}async handlePluginEvent(f,$,J){if($.name==="plugin_log"){this.handlePluginLog(f,$.payload);return}if($.name==="automation_event"){let X=this.deps.getSession(f)?.config.extensionContext?.automation??J;if(!X)return;let A=$.payload&&typeof $.payload==="object"?$.payload:void 0;if(!A)return;await X.ingestEvent(A);return}if($.name!=="steer_message"&&$.name!=="queue_message"&&$.name!=="pending_prompt")return;let Q=$.payload&&typeof $.payload==="object"?$.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():f,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=$.name==="steer_message"?"steer":$.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(f),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!$||typeof $!=="object")return;let W=$,j=typeof W.message==="string"?W.message:"";if(!j)return;let H=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(H.sessionId??=f,typeof W.pluginName==="string"&&W.pluginName)H.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,H);return}if(W.level==="error"){if(Z.error)Z.error(j,H);else Z.log(j,{...H,severity:"error"});return}Z.log(j,H)}}function uQ(f){return f.getAgentId()}function lQ(f){return{sessionId:f.sessionId,source:f.source,pid:process.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:of(f.config),teamName:f.config.teamName?.trim()||void 0,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,parentSessionId:typeof f.sessionMetadata?.parentSessionId==="string"?f.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof f.sessionMetadata?.parentAgentId==="string"?f.sessionMetadata.parentAgentId:void 0,agentId:typeof f.sessionMetadata?.agentId==="string"?f.sessionMetadata.agentId:void 0,conversationId:typeof f.sessionMetadata?.conversationId==="string"?f.sessionMetadata.conversationId:void 0,isSubagent:typeof f.sessionMetadata?.isSubagent==="boolean"?f.sessionMetadata.isSubagent:!1,prompt:f.pendingPrompt,metadata:f.sessionMetadata,messagesPath:f.artifacts?.messagesPath,updatedAt:f.updatedAt??f.endedAt??f.startedAt}}function pQ(f,$){let J=f[$];return typeof J==="function"?J:null}async function yA(f,$,...J){let Q=pQ(f,$);if(!Q)throw Error(`session service method not available: ${$}`);return Promise.resolve(Q.apply(f,J))}async function wA(f,$,...J){let Q=pQ(f,$);if(!Q)return;await Promise.resolve(Q.apply(f,J))}async function CA(f,$,...J){let Q=pQ(f,$);if(!Q)return;return await Promise.resolve(Q.apply(f,J))}t0();V0();function rQ(f,$,J){return{onSubAgentEvent:(Q)=>f.onAgentEvent(J,$,Q),onSubAgentStart:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime;f.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let W=Df({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(W)X$($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...W});X8($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...W}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,W=f.subAgentStarts.get(Q.subAgentId),j=W?Date.now()-W.startedAt:0,H=Q.result?.text?Q.result.text.split(`
695
+ `).length:0;X8($.telemetry,{event:"ended",ulid:J,durationMs:j,outputLines:H,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...Df({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),f.subAgentStarts.delete(Q.subAgentId),f.invokeBackendOptional("handleSubAgentEnd",J,Q)}}}function iQ(f,$,J,Q){let Z=rQ(f,$,J);return V1({configProvider:{getRuntimeConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:$.hooks,extensions:$.extensions,logger:$.logger,telemetry:$.telemetry},getConnectionConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let j=$.enableTools?J2({cwd:$.cwd,...e0[kf({mode:$.mode})],executors:Q}):[];if($.enableSpawnAgent)j.push(iQ(f,$,J,Q));return o$(j)},...Z})}import{readFile as bM,stat as kM}from"node:fs/promises";var IM=20480000;async function SA(f){let $=await kM(f);if(!$.isFile())throw Error("Path is not a file");if($.size>IM)throw Error("File is too large to read into context.");let J=await bM(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var EA=5000;function i2(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function lM(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=i2($.inputTokens),Q=i2($.outputTokens),Z=i2($.cacheReadTokens),W=i2($.cacheWriteTokens),j=i2($.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 pM(f,$){return{inputTokens:Math.max(f.inputTokens,$.inputTokens),outputTokens:Math.max(f.outputTokens,$.outputTokens),cacheReadTokens:Math.max(f.cacheReadTokens,$.cacheReadTokens),cacheWriteTokens:Math.max(f.cacheWriteTokens,$.cacheWriteTokens),totalCost:Math.max(f.totalCost,$.totalCost)}}class J${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new N2;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new N1;constructor(f){let $=gM();if($)dM($);let J=S$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new R4,this.createAgentInstance=f.createAgent??((Q)=>new If(Q)),this.defaultCapabilities=R0(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new $$,this.oauthTokenManager=f.oauthTokenManager??new vQ({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new cQ({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 dQ({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(f){let $=f.source??U0.CLI,J=n(),Q=f.config.sessionId?.trim()??"",Z=Q||vM(),W=f,j=W.initialMessages??[],H=j.length>0?eJ(j):G0(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=nQ(X,Z),Y=nQ(A,`${Z}.messages.json`),V=nQ(A,`${Z}.json`),B=of(f.config),K=N0.parse({version:1,session_id:Z,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.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:Y}),P;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let N=await this.invokeOptionalValue("readSessionManifest",Z);if(N)K=N,P={manifestPath:V,messagesPath:N.messages_path||Y,manifest:N}}let G=await this.seedAggregateUsageFromArtifacts({initialUsage:H,sessionDir:A,rootMessagesPath:P?.messagesPath??Y,manifest:K});this.usageBySession.set(Z,H),this.aggregateUsageBySession.set(Z,G);let F=R0(this.defaultCapabilities,f.capabilities),U=F?.toolExecutors??this.toolExecutors,_=f.localRuntime,T=_?.extensionContext?.logger??_?.logger,L=_?.extensionContext?.automation,D,M={getSession:(N)=>this.sessions.get(N),subAgentStarts:this.subAgentStarts,onAgentEvent:(N,j0,e)=>this.eventBridge.dispatchAgentEvent(N,j0,e),invokeBackendOptional:(N,...j0)=>this.invokeOptional(N,...j0)};D=await iX({input:W,localRuntime:f.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(N)=>{if(N.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,N.payload,T);return}this.eventBridge.handlePluginEvent(Z,N,L)},onTeamEvent:(N)=>{this.eventBridge.handleTeamEvent(Z,N),D.config.onTeamEvent?.(N)},createSpawnTool:()=>iQ(M,D.config,Z,U),createSubAgentLifecycleCallbacks:(N)=>rQ(M,N,Z),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(N)=>{await this.persistSessionMetadata(Z,()=>N)}});let S=await this.runtimeBuilder.build(D.runtimeBuilderInput),h=D.config,a=D.providerConfig;if(S.teamRuntime&&!h.teamName?.trim())h.teamName=S.teamRuntime.getTeamName();let W0=[...S.tools,...h.extraTools??[]],t=S.extensions??D.extensions,i={sessionId:Z,providerId:a.providerId,modelId:a.modelId,apiKey:a.apiKey,baseUrl:a.baseUrl,headers:a.headers,knownModels:a.knownModels,providerConfig:a,thinking:h.thinking,reasoningEffort:h.reasoningEffort??a.reasoningEffort,systemPrompt:h.systemPrompt,maxIterations:h.maxIterations,execution:h.execution,prepareTurn:UQ(h),tools:W0,hooks:D.hooks,extensions:t,hookErrorMode:h.hookErrorMode,initialMessages:D.effectiveInput.initialMessages,userFileContentLoader:SA,toolPolicies:D.toolPolicies,requestToolApproval:D.requestToolApproval?async(N)=>{let j0=D.requestToolApproval,e=this.sessions.get(Z);if(e)await this.markTurnPending(e);try{if(!j0)return{approved:!1,reason:"Tool approval callback is not configured."};return await j0(N)}finally{let _0=this.sessions.get(Z);if(_0?.status==="pending")await this.markTurnRunning(_0)}}:void 0,telemetry:h.telemetry,onConsecutiveMistakeLimitReached:h.onConsecutiveMistakeLimitReached,completionPolicy:S.completionPolicy,consumePendingUserMessage:()=>{let N=this.pendingPromptsController.consumeSteer(Z);return N?g2(N.prompt,N.mode??h.mode):void 0},logger:S.logger??h.logger,extensionContext:h.extensionContext,onEvent:(N)=>this.eventBridge.dispatchAgentEvent(Z,h,N)};i.hooks={...i.hooks,onEvent:async(N)=>{if(await D.hooks?.onEvent?.(N),N.type!=="assistant-message")return;let j0=this.sessions.get(Z);if(!j0)return;let e=j0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,e,h.systemPrompt)}catch(_0){h.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:_0}),I$(h.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:_0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:h.providerId,modelId:h.modelId}})}}};let l0=this.createAgentInstance(i);if(i.onEvent)l0.subscribeEvents(i.onEvent);S.registerLeadAgent?.(l0);let W$=Df({agentId:l0.getAgentId(),conversationId:l0.getConversationId(),teamId:S.teamRuntime?.getTeamId(),teamName:S.teamRuntime?.getTeamName(),teamRole:S.teamRuntime?"lead":void 0});if(nX(h,Z,Q.length>0,B,W$),W$)X$(h.telemetry,{ulid:Z,modelId:h.modelId,provider:h.providerId,...W$});if(S.teamRuntime)j6(h.telemetry,{ulid:Z,teamId:S.teamRuntime.getTeamId(),teamName:S.teamRuntime.getTeamName(),leadAgentId:l0.getAgentId(),restoredFromPersistence:S.teamRestoredFromPersistence===!0});let l={sessionId:Z,config:h,sessionMetadata:W.sessionMetadata,...P?{artifacts:P}:{},source:$,startedAt:P?.manifest.started_at??J,updatedAt:P?.manifest.ended_at??P?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:S,agent:l0,started:!1,status:P?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:D.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,l),this.emitStatus(Z,"running"),j.length>0&&!P){if(await this.ensureSessionPersisted(l),await this.invoke("persistSessionMessages",l.sessionId,j,l.config.systemPrompt),!W.prompt?.trim())await this.updateStatus(l,"completed",0)}let Zf;try{if(W.prompt?.trim())if(Zf=await this.executeTurn(l,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!l.interactive)await this.finalizeSingleRun(l,Zf.finishReason);else await this.completeInteractiveTurn(l,Zf.finishReason)}catch(N){if(l.interactive&&l.aborting)Zf=await this.completeAbortedInteractiveTurn(l);else throw I$(l.config.telemetry,{component:"core",operation:"session.start",error:N,severity:"error",handled:!1,context:{sessionId:l.sessionId,providerId:l.config.providerId,modelId:l.config.modelId}}),await this.failSession(l),N}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:Y,result:Zf}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let Q=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),Q=f.delivery??($.interactive&&!J?"queue":void 0);if($.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:f.sessionId,promptLength:f.prompt.length,userImageCount:f.userImages?.length??0,userFileCount:f.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,mode:f.mode,delivery:Q,userImages:f.userImages,userFiles:f.userFiles});return}try{let Z=await this.executeTurn($,{prompt:f.prompt,mode:f.mode,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,Z.finishReason);else await this.completeInteractiveTurn($,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),Z}catch(Z){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw I$($.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.failSession($),Z}}async getAccumulatedUsage(f){let $=M9(this.usageBySession.get(f)),J=M9(this.aggregateUsageBySession.get(f));return $||J?{usage:$,aggregateUsage:J}:void 0}async abort(f,$){let J=this.sessions.get(f);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:f}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort($)}async stopSession(f){let $=this.sessions.get(f);if(!$)return;if($.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:f}}),$.interactive&&!$0($.status)){await this.releaseSessionRuntime($,"session_stop");return}if($.interactive&&$.agent.canStartRun()){await this.shutdownSession($,{status:this.resolveInteractiveStopStatus($),exitCode:this.resolveInteractiveStopExitCode($),shutdownReason:"session_stop",endReason:"stopped"});return}$.aborting=!0,$.agent.abort(Error("session_stop")),await this.shutdownSession($,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(f="session_manager_dispose"){let $=[...this.sessions.values()];if($.length===0)return;await Promise.allSettled($.map((J)=>J.interactive&&!$0(J.status)?this.releaseSessionRuntime(J,f):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:f,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:f,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession(f){let $=this.sessions.get(f);if($)return lQ($);let J=f.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return z2(Q);let Z=await this.readManifest(J);return Z?y9(Z):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(z2),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift(lQ(Z))}return J.slice(0,f)}async deleteSession(f){if(this.sessions.has(f))await this.stopSession(f);let $=await this.invoke("deleteSession",f);if($.deleted)this.usageBySession.delete(f),this.aggregateUsageBySession.delete(f);return $.deleted}async updateSession(f,$){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:f,prompt:$.prompt,metadata:$.metadata,title:$.title}))?.updated===!0}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.getRow($);if(J?.messagesPath)return cf(J.messagesPath);let Q=await this.readManifest($);return cf(Q?.messages_path)}async dispatchHookEvent(f){await $H(f,{queueSpawnRequest:($)=>this.invokeOptional("queueSpawnRequest",$),upsertSubagentSessionFromHook:($)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",$),appendSubagentHookAudit:($,J)=>this.invokeOptional("appendSubagentHookAudit",$,J),applySubagentStatus:($,J)=>this.invokeOptional("applySubagentStatus",$,J)})}subscribe(f,$){return this.events.subscribe(f,$)}async updateSessionModel(f,$){let J=this.getSessionOrThrow(f);J.config.modelId=$,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:$}),J.agent.updateConnection({modelId:$})}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(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=Q;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let Z=await this.executeAgentTurn(f,Q,J.userImages,J.userFiles);while(JQ(f,Z.finishReason)){let W=await QQ(f);if(W.length===0)break;let j=ZQ(f,W);Z=await this.executeAgentTurn(f,j)}return Z}async completeInteractiveTurn(f,$){if(x2(f))return;f.lastInteractiveTurnFinishReason=$,await this.markTurnIdle(f),f.aborting=!1}resolveInteractiveStopStatus(f){let $=f.lastInteractiveTurnFinishReason;if(!$)return"cancelled";switch($){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return $}resolveInteractiveStopExitCode(f){return f.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages(),Q=G0();return f.persistedMessages=J,f.started=f.started||J.length>0,this.eventBridge.dispatchAgentEvent(f.sessionId,f.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,Q){let Z=f.started||f.agent.getMessages().length>0,W=f.persistedMessages??f.agent.getMessages(),j=this.usageBySession.get(f.sessionId)??G0(),H=this.aggregateUsageBySession.get(f.sessionId)??j;f.turnUsageBaseline=j,f.turnAggregateUsageBaseline=H,f.turnPrimaryUsage=G0(),f.turnUsageByAgent=new Map,e4(f.config.telemetry,f.sessionId,f.config.mode),E1(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,model:f.config.modelId,source:"user",mode:f.config.mode,...this.getSessionAgentTelemetryIdentity(f)});try{let X=Z?()=>f.agent.continue($,J,Q):()=>f.agent.run($,J,Q),A=await this.runWithAuthRetry(f,X,W);f.started=!0;let Y=EJ(A.messages,A,W);f.persistedMessages=Y;let V=oJ(f.turnUsageByAgent?.values()??[]),B=A0(j,A.usage),K=A0(A0(G0(),A.usage),V),P=A0(H,K);return this.usageBySession.set(f.sessionId,B),this.aggregateUsageBySession.set(f.sessionId,P),await this.persistSessionMetadata(f.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:P.totalCost,usage:B,aggregateUsage:P})),await this.invoke("persistSessionMessages",f.sessionId,Y,f.config.systemPrompt),this.observeTaskCompletionTool(f,A),A}catch(X){throw I$(f.config.telemetry,{component:"core",operation:"session.turn",error:X,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.invoke("persistSessionMessages",f.sessionId,f.agent.getMessages(),f.config.systemPrompt),X}finally{f.turnUsageBaseline=void 0,f.turnAggregateUsageBaseline=void 0,f.turnPrimaryUsage=void 0,f.turnUsageByAgent=void 0}}observeTaskCompletionTool(f,$){if(f.submitAndExitObserved)return;if(!$.toolCalls.some((Q)=>Q.name===K0.SUBMIT_AND_EXIT&&Q.error===void 0))return;f.submitAndExitObserved=!0,j8(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=of(f.config),Q=uM($.prompt).trim();if(!Q)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let Z=await WJ(Q,J);aX(f.config.telemetry,Z);let W=g2(Z.prompt,$.mode??f.config.mode),j=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),H=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),X=Array.from(new Set([...j,...H]));return{prompt:W,userImages:$.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=of(f.config);f.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:f.sessionId,source:f.source,pid:process.pid,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:$,teamName:f.config.teamName,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,prompt:f.pendingPrompt,metadata:f.sessionMetadata,startedAt:f.startedAt})}async markTurnRunning(f){if(f.status==="running")return;await this.updateStatus(f,"running",null)}async markTurnPending(f){if(f.status==="pending")return;await this.updateStatus(f,"pending",null)}async markTurnIdle(f){if(f.status==="idle")return;await this.updateStatus(f,"idle",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),Q=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,Z=$(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun(f,$){if(x2(f))return;let J=$==="aborted"||f.aborting,Q=$==="error";await this.shutdownSession(f,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)j8(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});aJ(f);let J=[],Q=(Z,W)=>{J.push(W),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:Z,error:W,severity:"warn"}),I$(f.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:f.sessionId,stage:Z,status:$.status,shutdownReason:$.shutdownReason,providerId:f.config.providerId,modelId:f.config.modelId}})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(Z){Q("update_status",Z)}try{await f.agent.shutdown($.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await f.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete(f.sessionId),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$.endReason,ts:Date.now()}}),J.length>0&&$.status==="failed")throw J[0]}async releaseSessionRuntime(f,$){let J=[],Q=(Z,W)=>{J.push(W),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:Z,error:W,severity:"warn"}),I$(f.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:f.sessionId,stage:Z,reason:$,providerId:f.config.providerId,modelId:f.config.modelId}})};try{await f.agent.shutdown($)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve(f.runtime.shutdown($))}catch(Z){Q("runtime_shutdown",Z)}try{await f.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let Q=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(Z.status=$,$0($))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??n(),Z.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=Z,f.status=$,f.updatedAt=Q.endedAt??n(),f.endedAt=$0($)?null:Z.ended_at,f.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,Z),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(Q){if(!b1(f.config.providerId)||!cM(Q))throw Q;return await this.syncOAuthCredentials(f,{forceRefresh:!0}),f.agent.restore(J),$()}}async syncOAuthCredentials(f,$){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:f.config.providerId,forceRefresh:$?.forceRefresh})}catch(Q){if(Q instanceof D4)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!J?.apiKey||f.config.apiKey===J.apiKey)return;f.config.apiKey=J.apiKey,f.agent.updateConnection({apiKey:J.apiKey}),f.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),f.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow(f){let $=this.sessions.get(f);if(!$){let J=new L$(f);throw I$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:f,activeSessionCount:this.sessions.size}}),J}return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>mM(Q)?Q:aQ(f,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return Df({agentId:f.agent.getAgentId(),conversationId:f.agent.getConversationId(),teamId:f.runtime.teamRuntime?.getTeamId(),teamName:f.runtime.teamRuntime?.getTeamName(),teamRole:f.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts(f){let $=await this.summarizePersistedTeammateUsage(f.sessionDir,f.rootMessagesPath,f.manifest.session_id),J=A0(f.initialUsage,$);return this.withPersistedAggregateUsageFloor(J,f.manifest)}async summarizePersistedTeammateUsage(f,$,J){let Q=aQ($),Z=`${J}.messages.json`,W;try{W=xM(f)}catch{return G0()}let j=G0();for(let H of W){if(!H.endsWith(".messages.json"))continue;if(H===Z)continue;let X=aQ(f,H);if(X===Q)continue;let A=await cf(X);if(A.length===0)continue;j=A0(j,eJ(A))}return j}withPersistedAggregateUsageFloor(f,$){let J=lM($.metadata?.aggregateUsage);if(J)return pM(f,J);let Q=$.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=f.totalCost)return f;return{...f,totalCost:Q}}emitStatus(f,$){this.emitSessionSnapshot(f),this.emit({type:"status",payload:{sessionId:f,status:$}})}async emitSessionSnapshot(f){let $=await this.getSession(f);if(!$)return;this.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:pf({session:$,messages:await this.readSessionMessages(f),usage:this.usageBySession.get(f),aggregateUsage:this.aggregateUsageBySession.get(f)})}})}emit(f){this.events.emit(f)}async listRows(f){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor(f)),EA))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(EA)).find((Q)=>Q.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return yA(this.sessionService,f,...$)}invokeOptional(f,...$){return wA(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return CA(this.sessionService,f,...$)}}function rM(f){if(f.backendMode)return f.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let $=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if($==="local"||$==="hub"||$==="remote")return $;return"auto"}var n2,a2;function iM(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;RH($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function nM(f){await f.reconcileDeadSessions?.().catch(()=>{})}function kA(f){try{let $=new af;return $.init(),new tf($,{messagesArtifactUploader:f.messagesArtifactUploader,logger:f.logger})}catch($){return f.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),bA(f.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:$,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new XQ(void 0,{messagesArtifactUploader:f.messagesArtifactUploader,logger:f.logger})}}function hA(f,$,J){return new J$({sessionService:J??f.sessionService??kA(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function aM(f){if(n2)return n2;if(a2)return await a2;return a2=(async()=>{return n2=kA(f),await nM(n2),n2})().finally(()=>{a2=void 0}),await a2}async function O4(f){let $=S$(f.distinctId);f.telemetry?.setDistinctId($);let J=rM(f);if(iM(J,f),J==="remote"){let Q=f.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return f.logger?.log("Using remote runtime host",{endpoint:Q}),new gJ({endpoint:Q,authToken:f.remote?.authToken,clientType:f.remote?.clientType,displayName:f.remote?.displayName,workspaceRoot:f.remote?.workspaceRoot,cwd:f.remote?.cwd,capabilities:f.capabilities})}if(J==="hub"){let Q=f.hub?.endpoint?.trim(),Z=Q||await S2({strategy:f.hub?.strategy??"require-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return f.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:Q||void 0}),new C$({url:Z,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities,telemetry:f.telemetry},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd})}if(J==="auto"){let Q=await m9({endpoint:f.hub?.endpoint,strategy:f.hub?.strategy??"prefer-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(Q){f.logger?.log("Using discovered local hub runtime host",{url:Q});let Z=new C$({url:Q,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities,telemetry:f.telemetry},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});try{return await Z.connect(),Z}catch(W){f.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:W}),bA(f.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:W,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return f.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),hA(f,$)}return hA(f,$)}class tQ{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor(f,$,J,Q,Z,W,j,H,X){this.clientName=$,this.runtimeAddress=J,this.host=f,this.prepare=Q,this.capabilities=Z,this.logger=W,this.telemetry=j,this.distinctId=H,this.settings=Tj(f),this.pendingPrompts=zj(f),this.automation=new x6(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=X?new O2({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:CW(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:SW({host:f,getExtensionContext:()=>z8({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:X.dbPath,logger:X.logger,pollIntervalMs:X.pollIntervalMs,claimLeaseSeconds:X.claimLeaseSeconds,globalMaxConcurrency:X.globalMaxConcurrency,watcherDebounceMs:X.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((A)=>{if(A.type!=="ended")return;this.disposeSessionBootstrap(A.payload.sessionId)})}static async create(f={}){let $=R0(f.capabilities),J=await O4({...f,capabilities:$}),Q=wW(f.automation),Z=new tQ(J,f.clientName,J.runtimeAddress,f.prepare,$,f.logger,f.telemetry,f.distinctId,Q?{...Q,logger:f.logger}:void 0);if(Q&&Q.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap(f){let $=this.activeSessionBootstraps.get(f);if(!$)return;this.activeSessionBootstraps.delete(f),await Promise.resolve($.dispose?.())}async start(f){let $=Mj(f),J=await this.prepare?.($);try{let Q=J?await J.applyToStartSessionInput($):$,Z=await this.host.startSession(s5(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(W)=>z8({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 Nj({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=(...f)=>this.host.runTurn(...f);getAccumulatedUsage=(...f)=>{return this.host.getAccumulatedUsage?.(...f)??Promise.resolve(void 0)};abort=(...f)=>this.host.abort(...f);stop=async(f)=>{await this.host.stopSession(f),await this.disposeSessionBootstrap(f)};dispose=async(...f)=>{try{await this.automationService?.dispose(),await this.host.dispose(...f)}finally{this.unsubscribeBootstrapCleanup();let $=[...this.activeSessionBootstraps.keys()];await Promise.allSettled($.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...f)=>this.host.getSession(...f);listHistory=async(f={})=>await w9(this.host,f);list=async(f=200,$={})=>await this.listHistory({...$,limit:f});delete=async(f)=>{let $=await this.host.deleteSession(f);if($)await this.disposeSessionBootstrap(f);return $};update=(...f)=>this.host.updateSession(...f);readMessages=(...f)=>this.host.readSessionMessages(...f);async restore(f){let $=f.start?s5(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>z8({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:f.sessionId,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restore:f.restore,start:$})}ingestHookEvent=(...f)=>this.host.dispatchHookEvent(...f);subscribe(f,$){return this.host.subscribe(f,$)}updateSessionModel=(...f)=>{return this.host.updateSessionModel?.(...f)??Promise.resolve()}}import{HookEventNameSchema as xA,HookEventPayloadSchema as gA,parseHookEventPayload as T4,resolveHookSessionContext as JN}from"@cline/shared";import{z as x$}from"zod";import{spawn as tM}from"node:child_process";import{augmentNodeCommandForDebug as sM,withResolvedClineBuildEnv as oM}from"@cline/shared";function eM(f){let $=f.trim();if(!$)return{};let Q=$.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]:$;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function fN(f,$){let J=f instanceof Error?f:Error(String(f)),Q=J,Z=$.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 $N(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end($,(j)=>{if(J.off("error",W),j){let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function _4(f,$){let J=sM($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!$.detached,Z=tM(J[0],J.slice(1),{cwd:$.cwd,env:oM($.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q}),W=new Promise((B)=>{Z.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(P)=>{K(fN(P,J))})});if(await $N(Z,JSON.stringify(f)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let H="",X="",A=!1,Y;Z.stdout.on("data",(B)=>{H+=B.toString()}),Z.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if(($.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,Z.kill("SIGKILL")},$.timeoutMs);Z.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:P,parseError:R}=eM(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:P,parseError:R,timedOut:A})})});return await Promise.race([V,j])}var QN=x$.object({contextModification:x$.string().optional(),cancel:x$.boolean().optional(),review:x$.boolean().optional(),errorMessage:x$.string().optional(),context:x$.string().optional(),overrideInput:x$.unknown().optional()}).passthrough();var ZN=["agent","hook"];async function z4(f,$={}){let J=$.command??ZN;return await _4(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function mA(f){return f instanceof Error?f:Error(String(f))}function WN(f){if(!f||typeof f!=="object")return;let $=QN.safeParse(f);if(!$.success)return;let J=$.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 IA(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,Q]of Object.entries(f))if(typeof Q==="string")$[J]=Q;else $[J]=JSON.stringify(Q);return $}function Lf(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:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:JN(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function jN(f){return{name:f.name,message:f.message,stack:f.stack}}function HN(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function XN(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function AN(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function YN(f){return{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}function VN(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}async function g$(f,$){try{let J=await z4(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(mA(J),f)}}function vA(f={}){return{hooks:{beforeRun:async(H)=>{let X=XN(H);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let Y={...Lf("agent_resume",X,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await g$(Y,f)}else{let Y={...Lf("agent_start",X,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await g$(Y,f)}return},beforeTool:async(H)=>{let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...Lf("tool_call",X,f),hookName:"tool_call",iteration:H.snapshot.iteration,tool_call:{id:H.toolCall.toolCallId,name:H.toolCall.toolName,input:H.input},preToolUse:{toolName:H.toolCall.toolName,parameters:IA(H.input)}};try{let Y=await z4(A,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:A,result:Y,detached:!1}),Y?.timedOut)throw Error("tool_call hook command timed out");if(Y?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${Y.parseError}`);return VN(WN(Y?.parsedJson))}catch(Y){f.onDispatchError?.(mA(Y),A);return}},afterTool:async(H)=>{let X=YN(H),A={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},Y={...Lf("tool_result",A,f),hookName:"tool_result",iteration:H.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:IA(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await g$(Y,f);return},afterRun:async({snapshot:H,result:X})=>{let A={agentId:H.agentId,conversationId:H.conversationId??H.runId??H.agentId,parentAgentId:H.parentAgentId??null};if(X.status==="completed"){let B={...Lf("agent_end",A,f),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await g$(B,f);return}let Y=X.status==="aborted"||HN(X.error?.message)?"agent_abort":"agent_error",V=Y==="agent_error"?{...Lf(Y,A,f),hookName:Y,iteration:X.iterations,error:jN(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...Lf(Y,A,f),hookName:Y,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await g$(V,f)},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...Lf("prompt_submit",X,f),hookName:"prompt_submit",userPromptSubmit:{prompt:AN(H.message.content),attachments:[]}};await g$(A,f)}},shutdown:async({agentId:H,conversationId:X,parentAgentId:A,reason:Y})=>{let V={...Lf("session_shutdown",{agentId:H,conversationId:X,parentAgentId:A},f),hookName:"session_shutdown",reason:Y};await g$(V,f)}}}import{createSessionId as BN}from"@cline/shared";function v0(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function cA(f,$,J){return{version:f.version,requestId:f.requestId??BN("hubreq_"),ok:!1,error:{code:$,message:J}}}class M4{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return v0(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return v0(f,{schedules:this.schedules.listSchedules({enabled:typeof f.payload?.enabled==="boolean"?f.payload.enabled:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0,tags:Array.isArray(f.payload?.tags)?f.payload?.tags:void 0})});case"schedule.get":return v0(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return v0(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return v0(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return v0(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return v0(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return v0(f,{execution:f.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String(f.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return v0(f,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof f.payload?.scheduleId==="string"?f.payload.scheduleId:void 0,status:typeof f.payload?.status==="string"?f.payload.status:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0})});case"schedule.stats":return v0(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return v0(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return v0(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return cA(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return cA(f,"schedule_command_failed",$ instanceof Error?$.message:String($))}}toCreateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider&&f.model?{providerId:String(f.provider),modelId:String(f.model)}:void 0;return{...f,modelSelection:$}}toUpdateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider||f.model?{providerId:typeof f.provider==="string"?f.provider:"",modelId:typeof f.model==="string"?f.model:""}:void 0;return{...f,modelSelection:$}}}function q4(f){return f?new Date(f).getTime():void 0}function KN(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function N4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:q4(f.nextRunAt),lastRunAt:q4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:KN(f)}}function PN(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function sQ(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:q4(f.startedAt),endedAt:q4(f.completedAt),status:PN(f.status),errorMessage:f.error}}class y4{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new L2({dbPath:f.dbPath}),this.materializer=new G2({store:this.store}),this.runner=new F2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,eventPublisher:f.eventPublisher,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.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(f){if(X9(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return N4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?N4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>N4($))}updateSchedule(f,$){if($.cronPattern!==void 0)X9($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let Q=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule(f,{...$,scheduleId:f});return W?N4(W):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return sQ(J,f)}triggerScheduleNowDetached(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;return this.runner.tick().catch(()=>{return}),sQ($,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((Z)=>{let W=$??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return sQ(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!f.status||Z.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,Q=0,Z=0,W;for(let j of $){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:$.length,successRate:J/$.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).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,f).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}E4();function xN(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var gN="cline-hub-auth.";function mN(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function vN(f,$){let J=new URL(f),Q=new URL($);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}async function cN(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=D0(),Q=await P0(J.discoveryPath);if(Q?.url&&vN(f.toString(),Q.url))return Q.authToken;return}async function uN(f={}){let $=df(f);if(!mN(f)){let J=D0(),Q=await P0(J.discoveryPath);if(Q?.url)return Q.url}return Gf($.host,$.port,$.pathname)}async function lA(f){return await new Promise(($,J)=>{(async()=>{let Q=new URL(f),Z=await cN(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${gN}${Z}`]:void 0),j=new Map,H=0;W.addEventListener("open",()=>{$({send(X){let A=X.requestId??`hub-client-${++H}`;return new Promise((Y,V)=>{j.set(A,{resolve:Y,reject:V});let B={kind:"command",envelope:{...X,requestId:A}};W.send(JSON.stringify(B))})},close(){W.close()}})}),W.addEventListener("message",(X)=>{let A=JSON.parse(String(X.data));if(A.kind==="reply"&&A.envelope.requestId){let Y=j.get(A.envelope.requestId);if(Y)j.delete(A.envelope.requestId),Y.resolve(A.envelope)}}),W.addEventListener("close",()=>{for(let X of j.values())X.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(X)=>{J(xN(X,f))})})().catch(J)})}async function Dd(f){try{return(await lA(f)).close(),!0}catch{return!1}}async function Ld(f,$){let J=await uN(f),Q=await lA(J);try{return await Q.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{Q.close()}}function $Z(f){return f?JSON.parse(JSON.stringify(f)):{}}function h4(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?$Z($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function pA(f,$){return f.error?.message??`hub command failed: ${$}`}function dN(f){let $=$Z(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,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{...$,error:Q.message.trim()};return $}function rA(f){let $=f?.sessionId;return typeof $==="string"&&$.trim()?$.trim():void 0}function lN(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;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 pN(f){let $=$Z(f.payload);if(f.event==="schedule.execution_completed")return{sessionId:f.sessionId?.trim()||rA($)||"",eventType:"schedule.execution.completed",payload:$};if(f.event==="schedule.execution_failed")return{sessionId:f.sessionId?.trim()||rA($)||"",eventType:"schedule.execution.failed",payload:$};let J=f.sessionId?.trim();if(!J)return;switch(f.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:$};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:$};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:$};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:$};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:$};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:$};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:$};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:$};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:dN(f.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:$};default:return}}class rN{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new Ff({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.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(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=h4($.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:$.prompt,mode:$.config.mode,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $;try{$=await this.client.command("session.get",void 0,f)}catch(J){if(O$(J))return;throw J}return h4($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(pA(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=f.config,Z=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.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}:{}},$);if(!Z.ok)throw Error(pA(Z,"session.restore"));let W=h4(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,H=lN(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:H}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((Q)=>h4({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=pN(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;$.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{$.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;$.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{$.onError?.(Q instanceof Error?Q:Error(String(Q)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});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 f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class iN{client;constructor(f){this.client=new Ff({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.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(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as nN}from"@cline/llms";function aN(f){return{text:f.text,usage:f.usage,inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function tN(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function Ed(f={}){let $=new J$({sessionService:new tf(new af),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await $.startSession({source:J.source?.trim()||U0.CLI,interactive:!1,config:{providerId:nN(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:tN(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 $.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:aN(Z)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function sN(f){if(typeof f==="string")return f.trim()||void 0;if(!Array.isArray(f))return;return f.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 iA=120,JZ="...";function QZ(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=iA)return $;let J=iA-Buffer.byteLength(JZ,"utf8");if(J<=0)return JZ;let Q="";for(let Z of $){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${JZ}`}async function nA(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,Z=[...await cf(J)].reverse().find((X)=>X.role==="assistant"),W=Z?sN(Z.content):void 0,j=f?.workspaceRoot?.trim()||"workspace",H=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():j;return{title:`Task completed (${$})`,body:QZ(W&&W.length>0?W:H.length>0?H:j),severity:"info"}}import{captureSdkError as x4,createSessionId as Nq}from"@cline/shared";import{createSessionId as $q}from"@cline/shared";import{createSessionId as fq}from"@cline/shared";function oN(f){switch(f){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function eN(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):{};if(f.parentSessionId?.trim())$.parentSessionId=f.parentSessionId;if(f.parentAgentId?.trim())$.parentAgentId=f.parentAgentId;if(f.agentId?.trim())$.agentId=f.agentId;if(f.conversationId?.trim())$.conversationId=f.conversationId;if(f.messagesPath?.trim())$.messagesPath=f.messagesPath;if(f.prompt?.trim())$.prompt=f.prompt;if(f.provider?.trim())$.provider=f.provider;if(f.model?.trim())$.model=f.model;if(f.source?.trim())$.source=f.source;if(typeof f.pid==="number")$.pid=f.pid;return Object.keys($).length>0?$:void 0}function b4(f,$,J,Q){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:oN(f.status),participants:$?[...$.participants.values()]:[],metadata:eN(f),runtimeOptions:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,mode:typeof f.metadata?.mode==="string"?f.metadata.mode:void 0,systemPrompt:typeof f.metadata?.systemPrompt==="string"?f.metadata.systemPrompt:void 0},runtimeSession:f.agentId?{agentId:f.agentId,team:f.teamName?{teamId:f.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function v(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function I(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function k4(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function y0(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function v$(f,$,J){return{version:"v1",event:f,eventId:fq("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function c0(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let Q=await f.sessionHost.getAccumulatedUsage?.($);return b4(J,f.sessionState.get($),Q?.usage,Q?.aggregateUsage)}async function u0(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[Q,Z]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return pf({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function I4(f,$,J,Q,Z={}){let W=f.sessionState.get($);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 f.sessionState.set($,j),j}async function ZZ(f,$){let J=$q("approval_"),Q=$.sessionId;if(f.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)=>{f.pendingApprovals.set(J,{sessionId:Q,resolve:W}),f.publish(f.buildEvent("approval.requested",{approvalId:J,sessionId:$.sessionId,agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:JSON.stringify($.input??null),policy:$.policy},Q))})}function WZ(f,$,J){let Q=f.pendingApprovals.get($);if(!Q)return;return f.pendingApprovals.delete($),Q.resolve(J),{sessionId:Q.sessionId}}function jZ(f,$,J){let Q=0;for(let[Z,W]of[...f.pendingApprovals.entries()]){if(!$({approvalId:Z,sessionId:W.sessionId}))continue;f.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function aA(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return I($,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof $.payload?.reason==="string"?$.payload.reason:$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)&&typeof $.payload.payload.reason==="string"?$.payload.payload.reason:void 0,W=$.payload?.approved===!0,j=WZ(f,J,{approved:W,reason:Z});if(!j)return I($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),v($,{approvalId:J,approved:W})}import{createSessionId as Zq}from"@cline/shared";function Jq(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var tA={debug:10,info:20,warn:30,error:40,silent:50};function Qq(){let f=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if(f==="debug"||f==="info"||f==="warn"||f==="error"||f==="silent")return f;return process.env.VITEST?"error":"info"}function g(f,$,J={}){if(tA[f]<tA[Qq()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,Jq(W)]).filter(([,Z])=>Z!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function HZ(f,$){let J=$ instanceof Error?$.stack||$.message:String($);g("error",f,{error:J})}async function sA(f,$,J,Q,Z,W){let j=Zq("capreq_"),H=performance.now();return g("info","capability.request.start",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z}),await new Promise((X,A)=>{f.pendingCapabilityRequests.set(j,{sessionId:$,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(Y)=>{if(g(Y.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z,ok:Y.ok,error:Y.error,durationMs:Math.round(performance.now()-H)}),!Y.ok){A(Error(Y.error||`Capability ${J} was rejected by ${Z}.`));return}X(Y.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},$)),g("info","capability.request.published",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z})})}function oA(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",Q=f.pendingCapabilityRequests.get(J);if(!Q)return I($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==Q.targetClientId)return I($,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==Q.sessionId)return I($,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return Q.onProgress?.(W),v($,{requestId:J})}function Q$(f,$,J){let Q=0;for(let[Z,W]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:Z,...W}))continue;f.pendingCapabilityRequests.delete(Z),g("warn","capability.request.cancelled",{requestId:Z,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,reason:J}),W.resolve({ok:!1,error:J}),f.publish(f.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 eA(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",Q=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!Q||!Z)return I($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},j=await f.requestCapability(J,Q,W,Z);return v($,j)}catch(W){return I($,"capability_request_failed",W instanceof Error?W.message:String(W))}}function fY(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",Q=f.pendingCapabilityRequests.get(J);if(!Q)return I($,"capability_not_found",`Unknown capability request: ${J}`);let Z=$.clientId?.trim()||"";if(Z!==Q.targetClientId)return I($,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==Q.sessionId)return I($,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);f.pendingCapabilityRequests.delete(J);let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,j=typeof $.payload?.error==="string"?$.payload.error:void 0,H=$.payload?.ok===!0;return g(H?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:H,error:j}),Q.resolve({ok:H,payload:W,error:j}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:H,payload:W,error:j},Q.sessionId)),v($,{requestId:J,ok:H})}import{createSessionId as Wq}from"@cline/shared";function $Y(f,$){let J=$.payload,Q=J?.clientId?.trim()||$.clientId?.trim()||Wq("client_");return f.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}),f.publish(f.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),v($,{clientId:Q})}function JY(f,$){let J=$.clientId?.trim(),Q=J?f.clients.get(J):void 0;if(!J||!Q)return I($,"client_not_found","Client is not registered with this hub.");let Z=k4($.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return v($)}function QY(f,$,J){let Q=$.clientId?.trim();if(Q)f.clients.delete(Q),J(Q),f.publish(f.buildEvent("hub.client.disconnected",{clientId:Q}));return v($)}function ZY(f,$){return v($,{clients:[...f.clients.values()]})}var jq=30000;function Hq(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function Xq(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function Aq(f,$,J){let Q=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${$}`;return I(f,K2,Q)}function Yq(f){return f?f:void 0}function Vq(f){let $=typeof f.timeoutMs==="number"?f.timeoutMs:typeof f.timeout_ms==="number"?f.timeout_ms:void 0;if($&&Number.isFinite($)&&$>0)return Math.floor($);let J=typeof f.timeoutSeconds==="number"?f.timeoutSeconds:typeof f.timeout_seconds==="number"?f.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function Bq(f,$,J,Q){let Z=performance.now(),W=!1,j={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:Q},H=setInterval(()=>{if(W)return;let Y=Math.round(performance.now()-Z);g("warn","run.heartbeat",{...j,elapsedMs:Y}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:Y,...Q?{timeoutMs:Q}:{}},J.sessionId))},jq),X=f.sessionHost.runTurn(J);X.then((Y)=>{if(!W)return;g("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:Y?.finishReason})},(Y)=>{if(!W)return;g("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:Y})});let A;try{if(!Q)return await X;return await Promise.race([X,new Promise((Y,V)=>{A=setTimeout(()=>{let B=`Hub run ${$.command} timed out after ${Q}ms.`;W=!0,clearInterval(H),V(Error(B)),g("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),jZ(f,(K)=>K.sessionId===J.sessionId,B),Q$(f,(K)=>K.sessionId===J.sessionId,B),f.sessionHost.abort(J.sessionId,B).catch((K)=>{g("error","run.timeout_abort_failed",{...j,error:K})})},Q)})])}finally{if(W=!0,clearInterval(H),A)clearTimeout(A)}}async function WY(f,$){let J=y0($),Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return I($,"invalid_session_input","session input requires a prompt string");f.publish(f.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((Y)=>typeof Y==="string"):void 0,H=Vq(Q);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await Bq(f,$,{sessionId:J,prompt:Z,mode:Yq(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:H},H)}catch(Y){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);if(O$(Y))return Aq($,J,Y);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:Y instanceof Error?Y.message:String(Y)},J)),Y}if(X){let Y=await u0(f,J),V=Xq(X);if(f.publish(f.buildEvent(Hq(X.finishReason),{reason:X.finishReason,...V?{error:V}:{},result:X,...Y?{snapshot:Y}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let A=await u0(f,J);return v($,X||A?{...X?{result:X}:{},...A?{snapshot:A}:{}}:void 0)}async function jY(f,$){let J=y0($),Q=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";jZ(f,(Z)=>Z.sessionId===J,Q);try{await f.sessionHost.abort(J,$.payload?.reason)}catch(Z){g("warn","run.abort_failed",{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J,error:Z})}finally{Q$(f,(Z)=>Z.sessionId===J,Q)}return v($,{applied:!0})}async function HY(f,$){let J=T4($.payload?.payload);if(!J)return I($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),v($,{applied:!0})}async function XY(f,$){switch($.type){case"chunk":return;case"agent_event":await Kq(f,$);return;case"hook":if($.payload.hookEventName==="tool_call")f.publish(f.buildEvent("tool.started",{toolName:$.payload.toolName},$.payload.sessionId));else if($.payload.hookEventName==="tool_result")f.publish(f.buildEvent("tool.finished",{toolName:$.payload.toolName},$.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:$.payload.sessionId,summary:$.payload.summary,lastEvent:$.payload.lifecycle};f.publish(f.buildEvent("team.progress",J,$.payload.sessionId));return}case"pending_prompts":f.publish(f.buildEvent("session.pending_prompts",{sessionId:$.payload.sessionId,prompts:$.payload.prompts},$.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:$.payload.id,prompt:$.payload.prompt,delivery:$.payload.delivery,attachmentCount:$.payload.attachmentCount};f.publish(f.buildEvent("session.pending_prompt_submitted",{sessionId:$.payload.sessionId,prompt:J},$.payload.sessionId));return}case"session_snapshot":f.publish(f.buildEvent("session.updated",{sessionId:$.payload.sessionId,snapshot:$.payload.snapshot},$.payload.sessionId));return;case"status":{let[J,Q]=await Promise.all([c0(f,$.payload.sessionId),u0(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},$.payload.sessionId));return}case"ended":await Pq(f,$);return;default:return}}async function Kq(f,$){let{sessionId:J,event:Q}=$.payload;if(Q.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){f.publish(f.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){f.publish(f.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":f.publish(f.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 f.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}f.publish(f.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:$.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:$.payload.teamAgentId,teamRole:$.payload.teamRole}},J));return}if(Q.type==="done")f.publish(f.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function Pq(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),Q=J===$.payload.reason||J==="run.start.reply";if(Q)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[Z,W]=await Promise.all([c0(f,$.payload.sessionId),u0(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let j=await nA(Z);f.publish(f.buildEvent("ui.notify",j,$.payload.sessionId))}if(Q)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...W?{snapshot:W}:{}},$.payload.sessionId))}import{createSessionId as VY,parseRuntimeConfigExtensions as BY}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Al,HUB_COMPACTION_CAPABILITY as Yl,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Vl,HUB_HOOK_CAPABILITY_PREFIX as Bl,HUB_MISTAKE_LIMIT_CAPABILITY as Kl,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Pl,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Gl,isHubToolExecutorName as Gq}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Ll,HUB_COMPACTION_CAPABILITY as Ol,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as _l,HUB_HOOK_CAPABILITY_PREFIX as Tl,HUB_MISTAKE_LIMIT_CAPABILITY as zl,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Ml,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Nl}from"@cline/shared";var Fq=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function c$(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function Uq(f,$){let J=typeof f.name==="string"?f.name.trim():"",Q=typeof f.description==="string"?f.description:"",Z=typeof f.capabilityName==="string"?f.capabilityName.trim():"",W=c$(f.inputSchema);if(!J||!Q||!W||!Z||$.has(Z))return;return $.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...c$(f.lifecycle)?{lifecycle:c$(f.lifecycle)}:{}}}function AZ(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let Q of f){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 H=Uq(Z,J);if(H)$.push(H);continue}if(W==="toolExecutor"){let H=Z.executor;if(!Gq(H))continue;J.add(j),$.push({kind:"toolExecutor",capabilityName:j,executor:H});continue}if(W==="hook"){let H=typeof Z.name==="string"?Z.name.trim():"";if(!H)continue;J.add(j),$.push({kind:"hook",capabilityName:j,name:H});continue}if(W==="compaction"){J.add(j),$.push({kind:"compaction",capabilityName:j,...c$(Z.config)?{config:c$(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),$.push({kind:"checkpoint",capabilityName:j,...c$(Z.config)?{config:c$(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),$.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),$.push({kind:"userInstructionService",capabilityName:j})}return $}function YY(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function Rq(f){return Object.hasOwn(f,"update")?f.update:f}function e2(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function Dq(f){let $=(f??[]).map(e2).filter(Boolean);return $.length>0?new Set($):void 0}function Lq(f,$,J){if(!J)return!0;let Q=e2(f),Z=e2($),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 XZ(f,$){let J=Dq($);return f.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)=>Lq(Q.id,Q.name,J))}function AY(f,$){let J=async(Q,Z)=>{let W=e2(Q),H=XZ(f,$).filter((B)=>B.id===W||e2(B.name)===W||B.id.endsWith(`:${W}`)).filter((B)=>!B.disabled);if(H.length!==1)return H.length>1?`Skill "${Q}" is ambiguous. Use one of: ${H.map((B)=>B.id).join(", ")}`:`Skill "${Q}" not found.`;let X=H[0].skill,A=Z?.trim(),Y=A?`
698
698
  <command-args>${A}</command-args>`:"",V=X.description?.trim()?`Description: ${X.description.trim()}
699
699
 
700
700
  `:"";return`<command-name>${X.name}</command-name>${Y}
701
701
  <command-instructions>
702
702
  ${V}${X.instructions}
703
- </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>lZ($,f).map(({skill:W,...Z})=>Z),enumerable:!0}),J}function EM($,f,J,W){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},Q=async()=>{let j=await W($,J.capabilityName,{},f);if(j?.snapshot)Z=j.snapshot};return{start:Q,stop:()=>{},refreshType:async()=>{await Q()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let X=j.match(/^\/(\S+)/)?.[1];if(!X)return j;let A=Z.runtimeCommands.find((Y)=>Y.name===X);return A?`${A.instructions}${j.slice(X.length+1)}`:j},hasConfiguredSkills:(j)=>lZ(Z,j).some((H)=>!H.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((H)=>Boolean(H))},setup(H){if(j.includeRules)H.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>b8(Z.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(j.registerSkillsTool)H.registerTool(e1(CM(Z,j.allowedSkillNames)));for(let X of Z.runtimeCommands.filter((A)=>A.kind==="skill"&&j.includeSkills||A.kind==="workflow"&&j.includeWorkflows))H.registerCommand({name:X.name,description:X.description,handler:(A)=>{let Y=A.trim();return Y?`${X.instructions}
703
+ </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>XZ(f,$).map(({skill:Q,...Z})=>Z),enumerable:!0}),J}function Oq(f,$,J,Q){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},W=async()=>{let j=await Q(f,J.capabilityName,{},$);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 X=j.match(/^\/(\S+)/)?.[1];if(!X)return j;let A=Z.runtimeCommands.find((Y)=>Y.name===X);return A?`${A.instructions}${j.slice(X.length+1)}`:j},hasConfiguredSkills:(j)=>XZ(Z,j).some((H)=>!H.disabled),createSkillsExecutor:(j)=>AY(Z,j),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((H)=>Boolean(H))},setup(H){if(j.includeRules)H.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>d8(Z.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(j.registerSkillsTool)H.registerTool(W1(AY(Z,j.allowedSkillNames)));for(let X of Z.runtimeCommands.filter((A)=>A.kind==="skill"&&j.includeSkills||A.kind==="workflow"&&j.includeWorkflows))H.registerCommand({name:X.name,description:X.description,handler:(A)=>{let Y=A.trim();return Y?`${X.instructions}
704
704
 
705
- ${Y}`:X.instructions}})}})}}function bM($,f,J,W){let Z=J.map((Q)=>[Q.executor,async(...j)=>{let H=j.at(-1),X=j.slice(0,-1);return(await W($,Q.capabilityName,{executor:Q.executor,args:X,context:mA(H)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function kM($,f,J,W){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(Q,j){return(await W($,Z.capabilityName,{toolName:Z.name,input:Q,context:mA(j)},f,j.emitUpdate?(X)=>{j.emitUpdate?.(wM(X))}:void 0))?.result}}))}function IM($,f,J,W){let Z=new Map(J.map((j)=>[j.name,j])),Q={};for(let j of yM){let H=Z.get(j);if(!H)continue;Q[j]=async(X)=>{return(await W($,H.capabilityName,{context:X},f))?.control}}return Object.keys(Q).length>0?Q:void 0}function rZ($){let f=$.contributions.filter((X)=>X.kind==="toolExecutor"),J=$.contributions.filter((X)=>X.kind==="tool"),W=$.contributions.filter((X)=>X.kind==="hook"),Z=$.contributions.find((X)=>X.kind==="compaction"),Q=$.contributions.find((X)=>X.kind==="checkpoint"),j=$.contributions.find((X)=>X.kind==="mistakeLimit"),H=$.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:bM($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...W.length>0?{hooks:IM($.sessionId,$.targetClientId,W,$.requestCapability)}:{},...J.length>0?{extraTools:kM($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(X)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:X},$.targetClientId))?.result}}}:{},...Q?{checkpoint:{...$.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(X)=>{return(await $.requestCapability($.sessionId,Q.capabilityName,{context:X},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(X)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:X},$.targetClientId))?.result}}:{},...H?{userInstructionService:EM($.sessionId,$.targetClientId,H,$.requestCapability)}:{}}}}var uA="hubCapabilityOwnerClientId";function cA($,f){$[uA]=f}function xM($){let f=$?.[uA];return typeof f==="string"&&f.trim()?f.trim():void 0}async function dA($,f,J){let W=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};I("info","session.create.begin",Z);let Q=f.payload&&typeof f.payload==="object"?f.payload:{},j=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},H=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,X=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof H?.mode==="string")j.mode=H.mode;else if(typeof X.mode==="string")j.mode=X.mode;if(typeof H?.systemPrompt==="string")j.systemPrompt=H.systemPrompt;else if(typeof X.systemPrompt==="string")j.systemPrompt=X.systemPrompt;if(H?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)j.checkpointEnabled=!0;let A=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},Y=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!Y)return I("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),b(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let V=f.clientId?.trim()||"hub-client",B=pZ(X.clientContributions);if(I("info","session.create.contributions_parsed",{...Z,clientId:V,workspaceRoot:Y,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:B.length}),B.length>0)cA(j,V);let G=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||gA(),R=vA(X.configExtensions);I("info","session.create.runtime_build.begin",{...Z,sessionId:G,configExtensionCount:R?.length??0});let P=rZ({sessionId:G,targetClientId:V,contributions:B,sessionConfig:H,requestCapability:$.requestCapability});I("info","session.create.start_session.begin",{...Z,sessionId:G,provider:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),model:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub")});let U=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(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:G,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub"),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:H?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():Y),workspaceRoot:H?.workspaceRoot??Y,systemPrompt:H?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:H?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:H?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:H?.enableTools??X.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??X.enableTeams!==!1,checkpoint:H?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});I("info","session.create.start_session.end",{...Z,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!U.result}),N4($,U.sessionId,V,"creator",{interactive:j.interactive!==!1}),I("info","session.create.read_records.begin",{...Z,sessionId:U.sessionId});let[F,z]=await Promise.all([m0($,U.sessionId),g0($,U.sessionId)]);if(I("info","session.create.read_records.end",{...Z,sessionId:U.sessionId,hasSession:!!F,hasSnapshot:!!z,elapsedMs:Math.round(performance.now()-W)}),F)$.publish($.buildEvent("session.created",{session:F,...z?{snapshot:z}:{}},U.sessionId));return I("info","session.create.reply",{...Z,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-W)}),m(f,{session:F,...z?{snapshot:z}:{}})}async function lA($,f,J){let W=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof W.sessionId==="string"?W.sessionId.trim():f.sessionId?.trim()||"",Q=W.checkpointRunCount;if(!Z)return b(f,"invalid_restore","session.restore requires a session id");let j=W.restore&&typeof W.restore==="object"?W.restore:{},H=j.messages!==!1;if(typeof Q!=="number")return b(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(H&&!X)return b(f,"invalid_restore","sessionConfig is required when restore.messages is true");let A=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},Y=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof X?.mode==="string")Y.mode=X.mode;else if(typeof A.mode==="string")Y.mode=A.mode;if(typeof X?.systemPrompt==="string")Y.systemPrompt=X.systemPrompt;else if(typeof A.systemPrompt==="string")Y.systemPrompt=A.systemPrompt;if(X?.checkpoint?.enabled===!0)Y.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)Y.checkpointEnabled=!0;let V=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},B=f.clientId?.trim()||"hub-client",K=pZ(A.clientContributions);if(K.length>0)cA(Y,B);let R=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||gA(),P=vA(A.configExtensions),U=rZ({sessionId:R,targetClientId:B,contributions:K,sessionConfig:X,requestCapability:$.requestCapability}),z=await new Rf().restoreCheckpoint({sessionId:Z,checkpointRunCount:Q,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(T)=>$.sessionHost.getSession(T),readMessages:(T)=>$.sessionHost.readSessionMessages(T),buildStartInput:(T)=>{if(T.restoredCheckpointMetadata)Y.checkpoint=T.restoredCheckpointMetadata;let M=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():T.sourceSession.workspaceRoot||T.sourceSession.cwd;return{source:typeof Y.source==="string"?Y.source:void 0,interactive:Y.interactive!==!1,sessionMetadata:{...Y,restoredFromSessionId:Z,restoredCheckpointRunCount:Q},initialMessages:T.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:P,...U.localRuntime},capabilities:{toolExecutors:U.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:R,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:T.sourceSession.provider),modelId:X?.modelId??(typeof V.model==="string"?V.model:T.sourceSession.model),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:""),cwd:X?.cwd??T.plan.cwd,workspaceRoot:X?.workspaceRoot??M,systemPrompt:X?.systemPrompt??(typeof A.systemPrompt==="string"?A.systemPrompt:""),mode:X?.mode??(A.mode==="plan"||A.mode==="yolo"?A.mode:"act"),maxIterations:X?.maxIterations??(typeof A.maxIterations==="number"?A.maxIterations:void 0),enableTools:X?.enableTools??A.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??A.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??A.enableTeams!==!1,checkpoint:X?.checkpoint??(A.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof Y.teamName==="string"?Y.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(T)=>$.sessionHost.startSession(T),getStartedSessionId:(T)=>T.sessionId,readRestoredSession:(T)=>$.sessionHost.getSession(T)});if(!H)return m(f,{checkpoint:z.checkpoint});let _=z.startResult;if(!_)return b(f,"restore_failed","Checkpoint restore did not start a session");N4($,_.sessionId,B,"creator",{interactive:Y.interactive!==!1});let[D,O]=await Promise.all([m0($,_.sessionId),g0($,_.sessionId)]);if(D)$.publish($.buildEvent("session.created",{session:D,...O?{snapshot:O}:{}},_.sessionId));return m(f,{session:D,...O?{snapshot:O}:{},messages:z.messages??[],checkpoint:z.checkpoint})}catch(X){if(X instanceof p0)return b(f,X.code,X.code==="session_not_found"?`Unknown session: ${Z}`:X.message);return b(f,"restore_failed",X instanceof Error?X.message:String(X))}}async function pA($,f){let J=N0(f);if(!J)return b(f,"invalid_session_attach","session.attach requires a session id");N4($,J,f.clientId?.trim()||"hub-client","participant");let W=await m0($,J);if(W)$.publish($.buildEvent("session.attached",{session:W},J));return W?m(f,{session:W}):b(f,"session_not_found",`Unknown session: ${J}`)}async function rA($,f){let J=N0(f);if(!J)return b(f,"invalid_session_detach","session.detach requires a session id");let W=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([m0($,J)]),Q=xM(Z?.metadata)??W,j=$.sessionState.get(J);if(j){if(j.participants.delete(W),j.createdByClientId===W)j.createdByClientId=Q;if(j.participants.size===0)$.sessionState.delete(J)}s$($,(A)=>A.sessionId===J&&A.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[H,X]=await Promise.all([m0($,J),g0($,J)]);return $.publish($.buildEvent("session.detached",H?{session:H,...X?{snapshot:X}:{},clientId:W}:{clientId:W},J)),m(f)}async function iA($,f){let J=N0(f),W=f.payload?.includeSnapshot===!0,[Z,Q]=await Promise.all([m0($,J),W?g0($,J):Promise.resolve(void 0)]);return Z?m(f,{session:Z,...Q?{snapshot:Q}:{}}):b(f,"session_not_found",`Unknown session: ${J}`)}async function nA($,f){let J=N0(f);if(!J)return b(f,"invalid_session_id","session.messages requires a session id");if(!await m0($,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 aA($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((Q)=>_4(Q,$.sessionState.get(Q.sessionId)));return m(f,{sessions:Z})}async function tA($,f){let J=N0(f),W=T4(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:W}),[Q,j]=await Promise.all([m0($,J),g0($,J)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:Q,...j?{snapshot:j}:{}}}}async function sA($,f){let J=N0(f),W=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),m(f,{deleted:W})}async function oA($,f){let J=N0(f),W=$.sessionHost.pendingPrompts;if(!W)return b(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await W.list({sessionId:J});return m(f,{sessionId:J,prompts:Z})}async function eA($,f){let J=N0(f),W=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,Q=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 H=await j.update({sessionId:J,promptId:W,prompt:Z,delivery:Q});return m(f,H)}async function $Y($,f){let J=N0(f),W=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 Q=await Z.delete({sessionId:J,promptId:W});return m(f,Q)}function fY($){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 gM=new Set(["skills","workflows","rules","tools","mcp"]);function iZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function r2($,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 vM($,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 JY($){if($===void 0)return{};if(!iZ($))throw Error("settings.list payload must be an object.");return{cwd:r2($,"cwd"),workspaceRoot:r2($,"workspaceRoot"),availabilityContext:iZ($.availabilityContext)?$.availabilityContext:void 0}}function uM($){if(!iZ($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!gM.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...JY($),type:f,id:r2($,"id"),path:r2($,"path"),name:r2($,"name"),enabled:vM($,"enabled")}}class y4{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=mM("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new t$({sessionService:new l$(new d$),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:I1,requestCapability:(f,J,W,Z,Q)=>MA(this.ctx,f,J,W,Z,Q)},this.schedules=new F4({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let W=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(I1(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new G4(this.schedules),this.settings=$.settingsService??new Hf,$.cronOptions)this.cronService=new K2({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{xA(this.ctx,f).catch((J)=>{dZ("session event handling failed",J),M4(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())uZ(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(s$(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 M4(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 SA(this.ctx,$);case"client.update":return hA(this.ctx,$);case"client.unregister":return CA(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return EA(this.ctx,$);case"session.create":return await dA(this.ctx,$,(f)=>vZ(this.ctx,f));case"session.restore":return await lA(this.ctx,$,(f)=>vZ(this.ctx,f));case"session.attach":return await pA(this.ctx,$);case"session.detach":return await rA(this.ctx,$);case"session.get":return await iA(this.ctx,$);case"session.messages":return await nA(this.ctx,$);case"session.list":return await aA(this.ctx,$);case"session.update":return await tA(this.ctx,$);case"session.pending_prompts":return await oA(this.ctx,$);case"session.update_pending_prompt":return await eA(this.ctx,$);case"session.remove_pending_prompt":return await $Y(this.ctx,$);case"session.delete":return await sA(this.ctx,$);case"session.hook":return await IA(this.ctx,$);case"run.start":case"session.send_input":return await bA(this.ctx,$);case"run.abort":return await kA(this.ctx,$);case"capability.request":return await qA(this.ctx,$);case"approval.respond":return await TA(this.ctx,$);case"capability.respond":return wA(this.ctx,$);case"capability.progress":return yA(this.ctx,$);case"ui.notify":return this.publish(I1("ui.notify",$.payload??{})),m($);case"ui.show_window":return this.publish(I1("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=fY($.command);if(J)this.publish(I1(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!cM(f.error.code))return;M4(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(JY($.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(uM($.payload));return this.publish(I1("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 W=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return W.add(Z),this.listeners.set($,W),()=>{let Q=this.listeners.get($);if(!Q)return;if(Q.delete(Z),Q.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);s$(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(W){dZ(`listener threw while publishing ${$.event}`,W),M4(this.options.telemetry,{component:"core",operation:"hub.publish",error:W,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function cM($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as rM}from"node:crypto";import iM from"node:http";import nM from"node:net";import{URL as QY}from"node:url";import{WebSocketServer as aM}from"ws";import{captureSdkError as WY,HUB_COMMAND_SLOW_LOG_MS as dM,resolveHubCommandTimeoutMs as lM,safeJsonParse as pM}from"@cline/shared";function nZ($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function ZY($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class aZ{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,W=!1,Z=(X)=>{try{$.send(JSON.stringify(X))}catch(A){console.error(`[hub] failed to send websocket frame: ${A instanceof Error?A.stack||A.message:String(A)}`)}},Q=(X)=>{Z({kind:"event",envelope:X})},j=async(X)=>{try{let A=JSON.parse(X.data);switch(A.kind){case"command":{let Y=performance.now(),V=!1,B=nZ(A);I("info","command.start",B);let K=setTimeout(()=>{if(V)return;I("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-Y)})},dM),G=this.transport.command(A.envelope);G.then((_)=>{if(!V)return;I(_.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-Y),ok:_.ok,errorCode:_.error?.code,errorMessage:_.error?.message})},(_)=>{if(!V)return;I("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-Y),error:_})});let R=!1,P,U,F=lM(A.envelope.command,A.envelope.timeoutMs);try{U=F===null?await G:await Promise.race([G,new Promise((_)=>{P=setTimeout(()=>{R=!0,WY(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${A.envelope.command} did not complete within ${F}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:F}}),_(ZY(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${F}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},F)})])}catch(_){if(clearTimeout(K),P)clearTimeout(P);throw _}if(V=R,clearTimeout(K),P)clearTimeout(P);let z=Math.round(performance.now()-Y);if(R)I("error","command.timeout",{...B,durationMs:z,timeoutMs:F});else I(U.ok?"info":"warn","command.end",{...B,durationMs:z,ok:U.ok,errorCode:U.error?.code,errorMessage:U.error?.message});if(A.envelope.command==="client.register"&&U.ok){let D=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(D)J.add(D)}else if(A.envelope.command==="client.unregister"&&U.ok){let _=A.envelope.clientId?.trim();if(_)J.delete(_)}Z({kind:"reply",envelope:U});break}case"stream.subscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;if(f.has(Y))break;let V=await this.transport.subscribe(A.clientId,Q,{sessionId:A.sessionId});f.set(Y,V);break}case"stream.unsubscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;f.get(Y)?.(),f.delete(Y);break}case"reply":case"event":break}}catch(A){let Y=typeof X.data==="string"?pM(X.data):void 0;if(!Y||Y.kind!=="command"){I("error","rejected malformed websocket frame",{error:A});return}I("error","command.error",{...nZ(Y),error:A}),WY(this.telemetry,{component:"core",operation:"hub.websocket_command",error:A,severity:"error",handled:!0,context:nZ(Y)}),Z({kind:"reply",envelope:ZY(Y,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},H=()=>{if(W)return;W=!0;for(let X of f.values())X();f.clear();for(let X of J)this.transport.command({version:"v1",command:"client.unregister",clientId:X});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",H)};return $.addEventListener("message",j),$.addEventListener("close",H),H}}class tZ{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function tM($){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 sM($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(W)=>{J({data:tM(W)})});return}$.on("close",J)},removeEventListener(){}}}function oM($){try{$.write(`HTTP/1.1 400 Bad Request\r
705
+ ${Y}`:X.instructions}})}})}}function _q(f,$,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let H=j.at(-1),X=j.slice(0,-1);return(await Q(f,W.capabilityName,{executor:W.executor,args:X,context:YY(H)},$))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function Tq(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(f,Z.capabilityName,{toolName:Z.name,input:W,context:YY(j)},$,j.emitUpdate?(X)=>{j.emitUpdate?.(Rq(X))}:void 0))?.result}}))}function zq(f,$,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of Fq){let H=Z.get(j);if(!H)continue;W[j]=async(X)=>{return(await Q(f,H.capabilityName,{context:X},$))?.control}}return Object.keys(W).length>0?W:void 0}function YZ(f){let $=f.contributions.filter((X)=>X.kind==="toolExecutor"),J=f.contributions.filter((X)=>X.kind==="tool"),Q=f.contributions.filter((X)=>X.kind==="hook"),Z=f.contributions.find((X)=>X.kind==="compaction"),W=f.contributions.find((X)=>X.kind==="checkpoint"),j=f.contributions.find((X)=>X.kind==="mistakeLimit"),H=f.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:_q(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...Q.length>0?{hooks:zq(f.sessionId,f.targetClientId,Q,f.requestCapability)}:{},...J.length>0?{extraTools:Tq(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...Z?{compaction:{...f.sessionConfig?.compaction??{},...Z.config,compact:async(X)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...W?{checkpoint:{...f.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(X)=>{return(await f.requestCapability(f.sessionId,W.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(X)=>{return(await f.requestCapability(f.sessionId,j.capabilityName,{context:X},f.targetClientId))?.result}}:{},...H?{userInstructionService:Oq(f.sessionId,f.targetClientId,H,f.requestCapability)}:{}}}}var KY="hubCapabilityOwnerClientId";function PY(f,$){f[KY]=$}function Mq(f){let $=f?.[KY];return typeof $==="string"&&$.trim()?$.trim():void 0}async function GY(f,$,J){let Q=performance.now(),Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};g("info","session.create.begin",Z);let W=$.payload&&typeof $.payload==="object"?$.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},H=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,X=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof H?.mode==="string")j.mode=H.mode;else if(typeof X.mode==="string")j.mode=X.mode;if(typeof H?.systemPrompt==="string")j.systemPrompt=H.systemPrompt;else if(typeof X.systemPrompt==="string")j.systemPrompt=X.systemPrompt;if(H?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)j.checkpointEnabled=!0;let A=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},Y=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!Y)return g("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),I($,"invalid_session_create","session.create requires workspaceRoot or cwd");let V=$.clientId?.trim()||"hub-client",B=AZ(X.clientContributions);if(g("info","session.create.contributions_parsed",{...Z,clientId:V,workspaceRoot:Y,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:B.length}),B.length>0)PY(j,V);let P=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||VY(),R=BY(X.configExtensions);g("info","session.create.runtime_build.begin",{...Z,sessionId:P,configExtensionCount:R?.length??0});let G=YZ({sessionId:P,targetClientId:V,contributions:B,sessionConfig:H,requestCapability:f.requestCapability});g("info","session.create.start_session.begin",{...Z,sessionId:P,provider:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),model:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub")});let F=await f.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,...G.localRuntime},capabilities:{toolExecutors:G.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:P,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub"),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:H?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():Y),workspaceRoot:H?.workspaceRoot??Y,systemPrompt:H?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:H?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:H?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:H?.enableTools??X.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??X.enableTeams!==!1,checkpoint:H?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.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)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});g("info","session.create.start_session.end",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!F.result}),I4(f,F.sessionId,V,"creator",{interactive:j.interactive!==!1}),g("info","session.create.read_records.begin",{...Z,sessionId:F.sessionId});let[U,_]=await Promise.all([c0(f,F.sessionId),u0(f,F.sessionId)]);if(g("info","session.create.read_records.end",{...Z,sessionId:F.sessionId,hasSession:!!U,hasSnapshot:!!_,elapsedMs:Math.round(performance.now()-Q)}),U)f.publish(f.buildEvent("session.created",{session:U,..._?{snapshot:_}:{}},F.sessionId));return g("info","session.create.reply",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q)}),v($,{session:U,..._?{snapshot:_}:{}})}async function FY(f,$,J){let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():$.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return I($,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},H=j.messages!==!1;if(typeof W!=="number")return I($,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(H&&!X)return I($,"invalid_restore","sessionConfig is required when restore.messages is true");let A=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},Y=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof X?.mode==="string")Y.mode=X.mode;else if(typeof A.mode==="string")Y.mode=A.mode;if(typeof X?.systemPrompt==="string")Y.systemPrompt=X.systemPrompt;else if(typeof A.systemPrompt==="string")Y.systemPrompt=A.systemPrompt;if(X?.checkpoint?.enabled===!0)Y.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)Y.checkpointEnabled=!0;let V=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},B=$.clientId?.trim()||"hub-client",K=AZ(A.clientContributions);if(K.length>0)PY(Y,B);let R=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||VY(),G=BY(A.configExtensions),F=YZ({sessionId:R,targetClientId:B,contributions:K,sessionConfig:X,requestCapability:f.requestCapability}),_=await new N1().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(M)=>f.sessionHost.getSession(M),readMessages:(M)=>f.sessionHost.readSessionMessages(M),buildStartInput:(M)=>{if(M.restoredCheckpointMetadata)Y.checkpoint=M.restoredCheckpointMetadata;let S=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():M.sourceSession.workspaceRoot||M.sourceSession.cwd;return{source:typeof Y.source==="string"?Y.source:void 0,interactive:Y.interactive!==!1,sessionMetadata:{...Y,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:M.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:G,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:R,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:M.sourceSession.provider),modelId:X?.modelId??(typeof V.model==="string"?V.model:M.sourceSession.model),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:""),cwd:X?.cwd??M.plan.cwd,workspaceRoot:X?.workspaceRoot??S,systemPrompt:X?.systemPrompt??(typeof A.systemPrompt==="string"?A.systemPrompt:""),mode:X?.mode??(A.mode==="plan"||A.mode==="yolo"?A.mode:"act"),maxIterations:X?.maxIterations??(typeof A.maxIterations==="number"?A.maxIterations:void 0),enableTools:X?.enableTools??A.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??A.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??A.enableTeams!==!1,checkpoint:X?.checkpoint??(A.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof Y.teamName==="string"?Y.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(M)=>f.sessionHost.startSession(M),getStartedSessionId:(M)=>M.sessionId,readRestoredSession:(M)=>f.sessionHost.getSession(M)});if(!H)return v($,{checkpoint:_.checkpoint});let T=_.startResult;if(!T)return I($,"restore_failed","Checkpoint restore did not start a session");I4(f,T.sessionId,B,"creator",{interactive:Y.interactive!==!1});let[L,D]=await Promise.all([c0(f,T.sessionId),u0(f,T.sessionId)]);if(L)f.publish(f.buildEvent("session.created",{session:L,...D?{snapshot:D}:{}},T.sessionId));return v($,{session:L,...D?{snapshot:D}:{},messages:_.messages??[],checkpoint:_.checkpoint})}catch(X){if(X instanceof i0)return I($,X.code,X.code==="session_not_found"?`Unknown session: ${Z}`:X.message);return I($,"restore_failed",X instanceof Error?X.message:String(X))}}async function UY(f,$){let J=y0($);if(!J)return I($,"invalid_session_attach","session.attach requires a session id");I4(f,J,$.clientId?.trim()||"hub-client","participant");let Q=await c0(f,J);if(Q)f.publish(f.buildEvent("session.attached",{session:Q},J));return Q?v($,{session:Q}):I($,"session_not_found",`Unknown session: ${J}`)}async function RY(f,$){let J=y0($);if(!J)return I($,"invalid_session_detach","session.detach requires a session id");let Q=$.clientId?.trim()||"hub-client",[Z]=await Promise.all([c0(f,J)]),W=Mq(Z?.metadata)??Q,j=f.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)f.sessionState.delete(J)}Q$(f,(A)=>A.sessionId===J&&A.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[H,X]=await Promise.all([c0(f,J),u0(f,J)]);return f.publish(f.buildEvent("session.detached",H?{session:H,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},J)),v($)}async function DY(f,$){let J=y0($),Q=$.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([c0(f,J),Q?u0(f,J):Promise.resolve(void 0)]);return Z?v($,{session:Z,...W?{snapshot:W}:{}}):I($,"session_not_found",`Unknown session: ${J}`)}async function LY(f,$){let J=y0($);if(!J)return I($,"invalid_session_id","session.messages requires a session id");if(!await c0(f,J))return I($,"session_not_found",`Unknown session: ${J}`);let Z=await f.sessionHost.readSessionMessages(J);return v($,{sessionId:J,messages:Z})}async function OY(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,Z=(await f.sessionHost.listSessions(J)).map((W)=>b4(W,f.sessionState.get(W.sessionId)));return v($,{sessions:Z})}async function _Y(f,$){let J=y0($),Q=k4($.payload?.metadata),Z=await f.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([c0(f,J),u0(f,J)]);if(W)f.publish(f.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:$.version,requestId:$.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function TY(f,$){let J=y0($),Q=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),v($,{deleted:Q})}async function zY(f,$){let J=y0($),Q=f.sessionHost.pendingPrompts;if(!Q)return I($,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return v($,{sessionId:J,prompts:Z})}async function MY(f,$){let J=y0($),Q=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",Z=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,W=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,j=f.sessionHost.pendingPrompts;if(!j)return I($,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return v($,H)}async function NY(f,$){let J=y0($),Q=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",Z=f.sessionHost.pendingPrompts;if(!Z)return I($,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return v($,W)}function qY(f){switch(f){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 qq=new Set(["skills","workflows","rules","tools","mcp"]);function VZ(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function f8(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function yq(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function yY(f){if(f===void 0)return{};if(!VZ(f))throw Error("settings.list payload must be an object.");return{cwd:f8(f,"cwd"),workspaceRoot:f8(f,"workspaceRoot"),availabilityContext:VZ(f.availabilityContext)?f.availabilityContext:void 0}}function wq(f){if(!VZ(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!qq.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...yY(f),type:$,id:f8(f,"id"),path:f8(f,"path"),name:f8(f,"name"),enabled:yq(f,"enabled")}}class g4{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=Nq("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new J$({sessionService:new tf(new af),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:f.telemetry,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:v$,requestCapability:($,J,Q,Z,W)=>sA(this.ctx,$,J,Q,Z,W)},this.schedules=new y4({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let Q=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(v$(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new M4(this.schedules),this.settings=f.settingsService??new G1,f.cronOptions)this.cronService=new O2({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{XY(this.ctx,$).catch((J)=>{HZ("session event handling failed",J),x4(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:$.type,sessionId:$.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(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())WZ(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(Q$(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(f){console.error("[hub] cron service stop failed",f)}}async handleCommand(f){try{let $=await this.dispatchCommand(f);return this.captureFailedReply(f,$),$}catch($){throw x4(this.options.telemetry,{component:"core",operation:"hub.command",error:$,severity:"error",handled:!1,context:this.commandTelemetryContext(f)}),$}}async dispatchCommand(f){switch(f.command){case"client.register":return $Y(this.ctx,f);case"client.update":return JY(this.ctx,f);case"client.unregister":return QY(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return ZY(this.ctx,f);case"session.create":return await GY(this.ctx,f,($)=>ZZ(this.ctx,$));case"session.restore":return await FY(this.ctx,f,($)=>ZZ(this.ctx,$));case"session.attach":return await UY(this.ctx,f);case"session.detach":return await RY(this.ctx,f);case"session.get":return await DY(this.ctx,f);case"session.messages":return await LY(this.ctx,f);case"session.list":return await OY(this.ctx,f);case"session.update":return await _Y(this.ctx,f);case"session.pending_prompts":return await zY(this.ctx,f);case"session.update_pending_prompt":return await MY(this.ctx,f);case"session.remove_pending_prompt":return await NY(this.ctx,f);case"session.delete":return await TY(this.ctx,f);case"session.hook":return await HY(this.ctx,f);case"run.start":case"session.send_input":return await WY(this.ctx,f);case"run.abort":return await jY(this.ctx,f);case"capability.request":return await eA(this.ctx,f);case"approval.respond":return await aA(this.ctx,f);case"capability.respond":return fY(this.ctx,f);case"capability.progress":return oA(this.ctx,f);case"ui.notify":return this.publish(v$("ui.notify",f.payload??{})),v(f);case"ui.show_window":return this.publish(v$("ui.show_window",f.payload??{})),v(f);case"settings.list":return await this.handleSettingsList(f);case"settings.toggle":return await this.handleSettingsToggle(f);case"settings.get":case"settings.patch":return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"not_implemented",message:`${f.command} is not implemented yet.`}};default:{let $=await this.scheduleCommands.handleCommand(f);if($.ok){let J=qY(f.command);if(J)this.publish(v$(J,$.payload))}return $}}}captureFailedReply(f,$){if($.ok||!$.error||!Cq($.error.code))return;x4(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error($.error.message),severity:$.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext(f),errorCode:$.error.code}})}commandTelemetryContext(f){return{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:typeof f.payload?.sessionId==="string"?f.payload.sessionId:f.sessionId}}async handleSettingsList(f){try{let $=await this.settings.list(yY(f.payload));return{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_list_failed",message:$ instanceof Error?$.message:String($)}}}}async handleSettingsToggle(f){try{let $=await this.settings.toggle(wq(f.payload));return this.publish(v$("settings.changed",{types:$.changedTypes,snapshot:$.snapshot})),{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$.snapshot,changedTypes:$.changedTypes}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_toggle_failed",message:$ instanceof Error?$.message:String($)}}}}subscribe(f,$,J){let Q=this.listeners.get(f)??new Set,Z={sessionId:J?.sessionId,listener:$};return Q.add(Z),this.listeners.set(f,Q),()=>{let W=this.listeners.get(f);if(!W)return;if(W.delete(Z),W.size===0)this.listeners.delete(f)}}detachClientFromSessions(f){for(let[$,J]of this.sessionState.entries())if(J.participants.delete(f),J.participants.size===0)this.sessionState.delete($);Q$(this.ctx,($)=>$.targetClientId===f,`Capability owner client ${f} disconnected before request was resolved.`)}publish(f){for(let $ of this.listeners.values())for(let J of $){if(J.sessionId&&J.sessionId!==f.sessionId)continue;try{J.listener(f)}catch(Q){HZ(`listener threw while publishing ${f.event}`,Q),x4(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:f.event,sessionId:f.sessionId}})}}}}function Cq(f){return f==="session_not_found"||f==="session_messages_not_found"||f==="hub_command_timeout"||f.endsWith("_failed")}import{timingSafeEqual as bq}from"node:crypto";import kq from"node:http";import Iq from"node:net";import{URL as SY}from"node:url";import{WebSocketServer as xq}from"ws";import{captureSdkError as wY,HUB_COMMAND_SLOW_LOG_MS as Sq,resolveHubCommandTimeoutMs as Eq,safeJsonParse as hq}from"@cline/shared";function BZ(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function CY(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class KZ{transport;telemetry;constructor(f,$){this.transport=f;this.telemetry=$}attach(f){let $=new Map,J=new Set,Q=!1,Z=(X)=>{try{f.send(JSON.stringify(X))}catch(A){console.error(`[hub] failed to send websocket frame: ${A instanceof Error?A.stack||A.message:String(A)}`)}},W=(X)=>{Z({kind:"event",envelope:X})},j=async(X)=>{try{let A=JSON.parse(X.data);switch(A.kind){case"command":{let Y=performance.now(),V=!1,B=BZ(A);g("info","command.start",B);let K=setTimeout(()=>{if(V)return;g("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-Y)})},Sq),P=this.transport.command(A.envelope);P.then((T)=>{if(!V)return;g(T.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-Y),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!V)return;g("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-Y),error:T})});let R=!1,G,F,U=Eq(A.envelope.command,A.envelope.timeoutMs);try{F=U===null?await P:await Promise.race([P,new Promise((T)=>{G=setTimeout(()=>{R=!0,wY(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${A.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:U}}),T(CY(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},U)})])}catch(T){if(clearTimeout(K),G)clearTimeout(G);throw T}if(V=R,clearTimeout(K),G)clearTimeout(G);let _=Math.round(performance.now()-Y);if(R)g("error","command.timeout",{...B,durationMs:_,timeoutMs:U});else g(F.ok?"info":"warn","command.end",{...B,durationMs:_,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(A.envelope.command==="client.register"&&F.ok){let L=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(L)J.add(L)}else if(A.envelope.command==="client.unregister"&&F.ok){let T=A.envelope.clientId?.trim();if(T)J.delete(T)}Z({kind:"reply",envelope:F});break}case"stream.subscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;if($.has(Y))break;let V=await this.transport.subscribe(A.clientId,W,{sessionId:A.sessionId});$.set(Y,V);break}case"stream.unsubscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;$.get(Y)?.(),$.delete(Y);break}case"reply":case"event":break}}catch(A){let Y=typeof X.data==="string"?hq(X.data):void 0;if(!Y||Y.kind!=="command"){g("error","rejected malformed websocket frame",{error:A});return}g("error","command.error",{...BZ(Y),error:A}),wY(this.telemetry,{component:"core",operation:"hub.websocket_command",error:A,severity:"error",handled:!0,context:BZ(Y)}),Z({kind:"reply",envelope:CY(Y,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},H=()=>{if(Q)return;Q=!0;for(let X of $.values())X();$.clear();for(let X of J)this.transport.command({version:"v1",command:"client.unregister",clientId:X});J.clear(),f.removeEventListener("message",j),f.removeEventListener("close",H)};return f.addEventListener("message",j),f.addEventListener("close",H),H}}class PZ{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function gq(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();return String(f)}function mq(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(Q)=>{J({data:gq(Q)})});return}f.on("close",J)},removeEventListener(){}}}function vq(f){try{f.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 eM($){try{$.write(`HTTP/1.1 401 Unauthorized\r
709
+ `),f.end()}catch{f.destroy()}}function cq(f){try{f.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 jY($,f){if(!$||!f)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(f,"utf8");return J.length===W.length&&rM(J,W)}function HY($,f){let J=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,W=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",Z=`Failed to start hub server on ${f.host}:${f.port}${f.pathname}: ${W}`,Q=Error(J?`${Z} (${J})`:Z);if(J)$.code=J,Q.code=J;if($ instanceof Error&&$.stack)Q.stack=`${Q.name}: ${Q.message}
714
- Caused by: ${$.stack}`;return Q}async function $y($){return await new Promise((f,J)=>{let W=nM.createServer();W.once("error",J),W.listen(0,$,()=>{let Z=W.address();if(!Z||typeof Z==="string"){W.close(()=>J(Error("Failed to resolve free port")));return}let Q=Z.port;W.close((j)=>{if(j){J(j);return}f(Q)})})})}function fy($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var sZ=new Map,XY="cline-hub-auth.",Jy=30000;function AY($){return Array.isArray($)?$.join(","):$??""}function Wy($){let f=AY($).trim();return/^Bearer\s+(.+)$/i.exec(f)?.[1]?.trim()||null}function Zy($){for(let f of AY($).split(",")){let J=f.trim();if(J.startsWith(XY))return J.slice(XY.length).trim()||null}return null}async function oZ($){let f=$.owner??_1(),J=$.host??"127.0.0.1",W=$.pathname??"/hub",Z=$.port??yJ(),Q=Z===0?await $y(J):Z,j=Q,H=Y$(J,Q,W),X=Xf(),A=rj(),Y=new y4($);await Y.start();let V=new aZ(new tZ(Y),$.telemetry),B=new Set,K=new Date().toISOString(),G={protocolVersion:"v1",coreVersion:L2.version,buildId:X,pid:process.pid,startedAt:K},R=new Set,P,U,F=async()=>{if(U)return U;return U=(async()=>{if(P)clearInterval(P),P=void 0;for(let O of R)O.terminate?.();R.clear();for(let O of B)O();if(B.clear(),await new Promise((O,T)=>{_.close((M)=>{if(M){T(M);return}O()})}),await new Promise((O,T)=>{z.close((M)=>{if(M){T(M);return}O()})}),await Y.stop(),(await K0(f.discoveryPath))?.url===H)await e0(f.discoveryPath)})(),U},z=iM.createServer((D,O)=>{if((D.url??"/")==="/health"){let M=JSON.stringify({hubId:Y.getHubId(),...G,authToken:"",host:J,port:j,url:H,updatedAt:new Date().toISOString()});O.statusCode=200,O.setHeader("content-type","application/json"),O.end(M);return}if((D.url??"/")==="/version"){O.statusCode=200,O.setHeader("content-type","application/json"),O.end(JSON.stringify(G));return}if(new QY(D.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&D.method==="POST"){if(!jY(Wy(D.headers.authorization),A)){O.statusCode=401,O.end("Unauthorized");return}O.statusCode=202,O.setHeader("content-type","application/json"),O.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{F()});return}O.statusCode=404,O.end("Not found")}),_=new aM({noServer:!0});P=setInterval(()=>{for(let D of R){if(D.isAlive===!1){try{D.terminate?.()}catch{}R.delete(D);continue}D.isAlive=!1;try{D.ping?.()}catch{try{D.terminate?.()}catch{}R.delete(D)}}},Jy),z.on("upgrade",(D,O,T)=>{if(new QY(D.url??"/",`http://${J}:${j}`).pathname!==W){O.destroy();return}if(!jY(Zy(D.headers["sec-websocket-protocol"]),A)){eM(O);return}try{_.handleUpgrade(D,O,T,(s)=>{let Z0=s;Z0.isAlive=!0,Z0.on("pong",()=>{Z0.isAlive=!0}),R.add(Z0);let a=V.attach(sM(s));B.add(a),s.once("close",()=>{R.delete(Z0),a(),B.delete(a)})})}catch{oM(O)}});try{await new Promise((D,O)=>{z.once("error",(T)=>{O(HY(T,{host:J,port:Q,pathname:W}))}),z.listen(Q,J,()=>{let T=z.address();if(!T||typeof T==="string"){O(HY(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:W}));return}j=T.port,H=Y$(J,j,W),D()})})}catch(D){if(P)clearInterval(P),P=void 0;throw await Y.stop().catch(()=>{return}),D}return await ij(f.discoveryPath,{hubId:Y.getHubId(),protocolVersion:"v1",coreVersion:L2.version,buildId:X,authToken:A,host:J,port:j,url:H,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:H,authToken:A,close:F}}async function YY($){let f=$.owner??_1(),J=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.host??"127.0.0.1",Z=$.port??yJ(),Q=$.pathname??"/hub",j=Y$(W,Z,Q),H=f.discoveryPath,X=(Y)=>{if(!J)Af(Y.url,Y.authToken);return Y},A=sZ.get(H);if(A){let Y=await A;if(Y.url===j)return X({server:Y,url:Y.url,authToken:Y.authToken,action:"reuse"})}return await nj(f.discoveryPath,async()=>{let Y=await K0(f.discoveryPath);if(Y?.url&&(Y.url===j||$.allowPortFallback===!0)){let G=await x$(Y.url);if(G?.url&&await g$(G.url,{authToken:Y.authToken}))return X({url:G.url,authToken:Y.authToken,action:"reuse"})}if((await x$(j))?.url||Y?.url)await e0(f.discoveryPath);let K=async(G)=>{let R=oZ({...G,owner:f});sZ.set(H,R);try{let P=await R;return X({server:P,url:P.url,authToken:P.authToken,action:"started"})}catch(P){throw sZ.delete(H),P}};try{return await K($)}catch(G){if(!$.allowPortFallback||!fy(G))throw G;return await K({...$,port:0})}})}async function Tl($){let f=m$({host:$.host,port:$.port,pathname:$.pathname});return await oZ({...$,...f,owner:R0()})}async function Nl($){let f=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=m$({host:$.host,port:$.port,pathname:$.pathname});return await YY({...$,...J,allowPortFallback:$.allowPortFallback??!f,owner:R0()})}eZ();import{buildRemoteConfigSessionBlobUploadMetadata as BY,clearRemoteConfigSessionBlobUpload as Qy,createClineTelemetryServiceConfig as jy,createSessionId as Hy,createRemoteConfigSessionMessagesArtifactUploader as Xy,prepareRemoteConfigRuntime as Ay,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as KY,readRemoteConfigSessionBlobUploadMetadata as Yy,registerRemoteConfigSessionBlobUpload as GY}from"@cline/shared";function Vy($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return k1(jy(J)).telemetry}function By(){let $=Xy();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function Ky($){let f=await Ay($),J=Vy(f,$),W=[f.pluginDefinition],Z=f.claims?.subject,Q=BY(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:W,telemetry:J,applyToStartSessionInput(H){let X=H.config.extensions??[],A=H.config.telemetry,Y=Q?H.config.sessionId?.trim()||Hy():H.config.sessionId;if(Y&&Q)j=Y;let V=Y&&Q?GY(Y,f.bundle?.remoteConfig,Z):void 0,B=V?{...H.sessionMetadata??{},[KY]:V}:H.sessionMetadata;return{...H,...B?{sessionMetadata:B}:{},config:{...H.config,...Y?{sessionId:Y}:{},extensions:[...X,...W],telemetry:J??A}}},async dispose(){if(j)Qy(j)}}}import{mkdir as Gy,readFile as Py,unlink as Uy,writeFile as Fy}from"node:fs/promises";import{join as PY}from"node:path";function Ry($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function Dy($){return new Promise((f)=>setTimeout(f,$))}async function $9($){try{await Uy($)}catch{}}async function Ly($,f={}){let J=f.approvalDir?.trim(),W=f.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await Gy(J,{recursive:!0});let Z=Ry(`${$.toolCallId}`),Q=PY(J,`${W}.request.${Z}.json`),j=PY(J,`${W}.decision.${Z}.json`),H=f.nowIso??(()=>new Date().toISOString());await Fy(Q,`${JSON.stringify({requestId:Z,sessionId:W,createdAt:H(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
715
- `,"utf8");let X=f.timeoutMs??300000,A=f.pollIntervalMs??200,Y=Date.now();while(Date.now()-Y<X){try{let V=await Py(j,"utf8"),B=JSON.parse(V),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([$9(j),$9(Q)]),K}catch{}await Dy(A)}return await $9(Q),{approved:!1,reason:"Tool approval request timed out"}}n0();n0();import{existsSync as zf,readdirSync as Oy,readFileSync as zy,rmdirSync as _y,rmSync as Ty,statSync as Ny}from"node:fs";import{basename as v0,dirname as o$,extname as My,isAbsolute as yy,join as U$,relative as qy,resolve as Of,sep as f9}from"node:path";import{discoverPluginModulePaths as wy,resolvePluginConfigSearchPaths as Sy}from"@cline/shared/storage";var j9="_installed",hy="package",Cy=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function J9($){return $.trim().toLowerCase()}function r0($,f){let J=f?.trim();if(!J)return;$.add(J)}function Ey($){return $.replace(/-[0-9a-f]{12}$/i,"")}function W9($){let f=My($);return f?$.slice(0,-f.length):$}function Z9($){if(!zf($))return;try{let f=JSON.parse(zy($,"utf8"));return typeof f.name==="string"?f.name.trim():void 0}catch{return}}function H9($,f){let J=qy(f,$);return J===""||!J.startsWith("..")&&!yy(J)}function UY($){let J=Of($).split(f9),W=J.lastIndexOf(j9);if(W<0)return;let Z=J[W+1];if(!Z)return;let Q=Cy.get(Z)??1,j=W+2+Q;if(J.length<j)return;let H=J.slice(0,j).join(f9)||f9;return zf(H)?H:void 0}function q4($){try{return Oy($,{withFileTypes:!0})}catch{return[]}}function by($){let f=U$($,j9);if(!zf(f))return[];let J=[];for(let W of q4(f)){if(!W.isDirectory())continue;let Z=U$(f,W.name);if(W.name==="git"){for(let Q of q4(Z)){if(!Q.isDirectory())continue;let j=U$(Z,Q.name);for(let H of q4(j))if(H.isDirectory())J.push(U$(j,H.name))}continue}for(let Q of q4(Z))if(Q.isDirectory())J.push(U$(Z,Q.name))}return J.sort((W,Z)=>W.localeCompare(Z))}function FY($){try{return wy($)}catch{return[]}}function Q9($){let f=FY($),J=new Set;r0(J,v0($)),r0(J,Ey(v0($))),r0(J,Z9(U$($,"package.json"))),r0(J,Z9(U$($,hy,"package.json")));for(let W of f)r0(J,v0(W)),r0(J,W9(v0(W)));return{installPath:$,entryPaths:f,names:[...J].sort((W,Z)=>W.localeCompare(Z)),installed:!0}}function ky($,f){let J=Of($),W=f.find((j)=>H9(J,j));if(!W)return;let Z=o$(J);while(Z!==W&&Z!==o$(Z)){if(zf(U$(Z,"package.json")))return Z;Z=o$(Z)}let Q=v0(J);if((Q==="index.ts"||Q==="index.js")&&o$(J)!==W)return o$(J);return J}function RY($,f){let J=ky($,f);if(!J)return;let W=new Set;return r0(W,v0($)),r0(W,W9(v0($))),r0(W,v0(J)),r0(W,W9(v0(J))),r0(W,Z9(U$(J,"package.json"))),{installPath:J,entryPaths:[$],names:[...W].sort((Z,Q)=>Z.localeCompare(Q)),installed:!1}}function Iy($){let f=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Sy(f).filter((J)=>zf(J))}function xy($){let f=new Map;for(let J of $){for(let W of by(J))f.set(W,Q9(W));for(let W of FY(J)){let Z=UY(W);if(Z){if(!f.has(Z))f.set(Z,Q9(Z));continue}let Q=RY(W,$);if(Q)f.set(Q.installPath,Q)}}return[...f.values()].sort((J,W)=>J.installPath.localeCompare(W.installPath))}function my($,f){let J=J9(f);if(!J)return!1;if(J9($.installPath)===J)return!0;return $.names.some((W)=>J9(W)===J)}function gy($,f,J){let W=Of($);for(let Q of f){if(H9(W,Q.installPath))return Q;if(Q.entryPaths.some((j)=>Of(j)===W))return Q}let Z=UY(W);if(Z)return Q9(Z);if(zf(W))return RY(W,J);return}function vy($){let f=L0(),J=f.disabledPlugins;if(!J?.length)return;let W=J.filter((Z)=>{let Q=Of(Z);if(H9(Q,$.installPath))return!1;return!$.entryPaths.some((j)=>Of(j)===Q)});if(W.length===J.length)return;T$({...f,disabledPlugins:W})}function uy($){let f=o$($);while(f!==o$(f)&&v0(f)!==j9){try{_y(f)}catch{return}f=o$(f)}}function cy($){return`${$.names[0]??v0($.installPath)} at ${$.installPath}`}async function dy($){let f=Iy($),J=xy(f),W=$.path?.trim(),Z=$.name?.trim(),Q;if(W){if(Q=gy(W,J,f),!Q)throw Error(`No plugin found at ${W}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let H=J.filter((X)=>my(X,Z));if(H.length===0)throw Error(`No plugin found matching "${Z}"`);if(H.length>1)throw Error(`Multiple plugins match "${Z}": ${H.map(cy).join(", ")}`);Q=H[0]}let j=Ny(Q.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${Q.installPath}`);if(Ty(Q.installPath,{recursive:j.isDirectory(),force:!0}),vy(Q),Q.installed)uy(Q.installPath);return{name:Z||Q.names[0]||v0(Q.installPath),installPath:Q.installPath,removedPaths:[Q.installPath],entryPaths:Q.entryPaths}}import*as D0 from"@cline/llms";import{getClineEnvironmentConfig as ly}from"@cline/shared";function py($){return $.apiKey??$.auth?.apiKey}function ry($){return($.auth?.accessToken?.trim()??"").length>0}function LY($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function iy($){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 ny($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of $)J=J*31+W.charCodeAt(0)>>>0;return f[J%f.length]}function OY($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>wX(f,J))}async function ay($,f){let J=await D0.getModelsForProvider($);if(!f)return J;let W=await L6($,{loadPrivateOnAuth:!0,failOnError:!1},f);return W?.knownModels?{...J,...W.knownModels}:J}function X9($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function ty($){if(!$?.length)return;return[...new Set($)]}function sy($,f){return ty([...$??[],...f??[]])}function oy($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function ey($){if(!$||typeof $!=="object")return!1;let f=$;return typeof f.path==="string"&&f.path.trim().length>0&&typeof f.label==="string"&&f.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(f.type))}function $q($){let f=$?.configFields;if(!Array.isArray(f))return;return f.filter(ey)}var w4={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},DY={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function fq($){if(!$)return[w4];if($.source!=="system")return $.baseUrl?[w4,DY]:[w4];let f=[];if($.env?.length)f.push(w4);if($.baseUrl)f.push(DY);return f}function Jq($,f){return f.split(".").reduce((J,W)=>{if(!J||typeof J!=="object")return;return J[W]},$)}function Wq($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function Zq($,f,J){if(!$?.length)return;let W={};for(let Z of $){let j=Wq(Z.path==="baseUrl"&&f?.baseUrl===void 0?J?.baseUrl:Jq(f,Z.path))??Z.defaultValue;if(j!==void 0)W[Z.path]=j}return W}function zY($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function A9($,f){let J=f?.includes("vision")??!1,W=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function _Y($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await j8($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function TY($,f){let J=$.read(),W=!1;if(J.providers[f])delete J.providers[f],W=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,W=!0;if(W)$.write(J);D0.unregisterProvider(f)}async function Qq($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!W&&!Z){let G=h1($);if((await Uf(G)).providers[J]){let P=await MY($,{providerId:J});return{providerId:J,settingsPath:P.settingsPath,modelsPath:P.modelsPath,modelsCount:0}}return TY($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(D0.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=f.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let j=X9(f.models),H=f.modelsSourceUrl?.trim(),X=await _Y({providerId:J,explicitModels:j,modelsSourceUrl:H,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=f.defaultModelId?.trim()&&X.includes(f.defaultModelId.trim())?f.defaultModelId.trim():X[0],Y=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,V=zY(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:W,headers:V,timeout:f.timeoutMs,model:A,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=h1($),K=await Uf(B);return K.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:A,protocol:f.protocol,client:f.client,capabilities:Y,modelsSourceUrl:H},models:A9(X,Y)},await f4(B,K),x2(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:X.length}}async function NY($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=h1($),Z=await Uf(W),Q=Z.providers[J];if(!Q){let _=$.getProviderSettings(J);if(!_)throw Error(`provider "${J}" does not exist`);let D=f.modelsSourceUrl?.trim(),O=X9(f.models)[0]??_.model?.trim();if(!O&&!D)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:f.name?.trim()||LY(J),baseUrl:f.baseUrl?.trim()??_.baseUrl?.trim()??"",defaultModelId:O,protocol:_.protocol,client:_.client,capabilities:_.capabilities},models:O?A9([O],_.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??Q.provider.name.trim();if(!j)throw Error("name is required");let H=f.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!H)throw Error("baseUrl is required");let X=f.capabilities===void 0?Q.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],A=f.protocol===void 0?Q.provider.protocol:f.protocol??void 0,Y=f.client===void 0?Q.provider.client:f.client??void 0,V=X9(f.models),B=f.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,G=Object.keys(Q.models??{}).map((_)=>_.trim()).filter(Boolean),R=await _Y({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let P=f.defaultModelId===void 0?Q.provider.defaultModelId?.trim():f.defaultModelId?.trim(),U=P&&R.includes(P)?P:R[0],z={...$.getProviderSettings(J)??{},provider:J,baseUrl:H,model:U};if(A)z.protocol=A;else delete z.protocol;if(Y)z.client=Y;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 _=zY(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:H,defaultModelId:U,protocol:A,client:Y,capabilities:X,modelsSourceUrl:B},models:A9(R,X)},await f4(W,Z),x2(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W,modelsCount:R.length}}async function MY($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=h1($),Z=await Uf(W);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await f4(W,Z),D0.unregisterProvider(J),TY($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W}}async function jq($){let f=$.read(),J=D0.getProviderIds(),W=await Promise.all(J.map(async(Q)=>{let[j,H]=await Promise.all([D0.getProvider(Q),D0.getModelsForProvider(Q)]),X=OY(H),A=f.providers[Q]?.settings,Y=j?.name??LY(Q),V=sy(j?.capabilities,A?.capabilities),B=$q(j?.metadata)??fq(j);return{provider:{id:Q,name:Y,models:X.length,color:ny(Q),letter:iy(Y),enabled:Boolean(A),apiKey:A?py(A):void 0,oauthAccessTokenPresent:A?ry(A):void 0,baseUrl:A?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:A?.protocol??j?.protocol,client:A?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:Zq(B,A,j),modelList:X},rank:oy(j?.metadata)}}));return W.sort((Q,j)=>{if(Q.rank!==j.rank)return Q.rank-j.rank;return Q.provider.name.localeCompare(j.provider.name)||Q.provider.id.localeCompare(j.provider.id)}),{providers:W.map((Q)=>Q.provider),settingsPath:$.getFilePath()}}async function Hq($,f){let J=$.trim(),W=await ay(J,f),Z=OY(W);return{providerId:J,models:Z}}function S4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function yY($,f){if(!S4(f))return S4($)?{...$}:void 0;let J=S4($)?{...$}:{};for(let[W,Z]of Object.entries(f)){if(Z==null||Z===""){delete J[W];continue}if(S4(Z)){let Q=yY(J[W],Z);if(Q&&Object.keys(Q).length>0)J[W]=Q;else delete J[W];continue}J[W]=Z}return Object.keys(J).length>0?J:void 0}function Xq($,f){let J=f.providerId.trim();if(f.enabled===!1){let Q=$.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return $.write(Q),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,Q)&&typeof f[Q]==="string")if(f[Q].trim().length===0)delete Z[Q];else Z[Q]=f[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,Q))Z[Q]=f[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,Q)&&f[Q]!=null){let j=yY(Z[Q],f[Q]);if(j)Z[Q]=j;else delete Z[Q]}return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function Aq($,f){let J=f.trim(),W=$.getProviderSettings(J),Q=D0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),H=H8(j,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!j||!H)return{providerId:J,refreshed:!1};let X=await NY($,{providerId:J,name:Q.name,baseUrl:j,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:H,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function Yq($){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 Vq($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function Bq($,f,J,W){let Z=x4({onPrompt:async(Q)=>Q.defaultValue??"",openUrl:J,onOpenUrlError:({error:Q})=>{throw Q instanceof Error?Q:Error(String(Q))}});if($==="cline")return f8({apiBaseUrl:f?.baseUrl?.trim()||ly().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:W});if($==="oca")return Q8({mode:f?.oca?.mode,callbacks:Z,telemetry:W});return W8({onAuth:Z.onAuth,onPrompt:Z.onPrompt,onProgress:Z.onProgress,onManualCodeInput:Z.onManualCodeInput,telemetry:W})}function Kq($,f,J,W){let Z={...J?.auth??{},accessToken:Vq(f,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function Gq($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}import*as h4 from"@cline/llms";import{isOAuthProviderId as Pq}from"@cline/shared";var Uq=["apiKey","baseUrl","awsRegion","awsProfile","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Fq={bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function Rq($,f){let J={};for(let W of Uq){let Z=$[W],Q=f[W];if(Z||Q)J[W]={...Z,...Q}}return J}function Dq($){let f=Fq[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:Rq($.fields,f.fields)}}var Lq=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Oq($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return Lq.has($)}function zq($){let f=h4.normalizeProviderId($);if(Pq(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=h4.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let W=J?.provider.baseUrl,Z={apiKey:{}};if(Oq(f,J))Z.baseUrl={defaultValue:W};return Dq({providerId:f,authMethod:"api-key",fields:Z})}B0();O4();import{appendFileSync as _q,existsSync as Y9,mkdirSync as Tq,readFileSync as Nq,renameSync as Mq,unlinkSync as yq,writeFileSync as qq}from"node:fs";import{join as V9}from"node:path";import{resolveTeamDataDir as wq}from"@cline/shared/storage";function Sq($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class qY{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=Sq($.teamName),J=$.baseDir?.trim()||wq();this.dirPath=V9(J,f),this.statePath=V9(this.dirPath,"state.json"),this.taskHistoryPath=V9(this.dirPath,"task-history.jsonl")}loadState(){if(!Y9(this.statePath))return;try{let $=Nq(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 bH(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`;qq(J,`${JSON.stringify(f,null,2)}
716
- `,"utf8"),Mq(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(),_q(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
717
- `,"utf8")}ensureDir(){if(!Y9(this.dirPath))Tq(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(Y9(this.statePath))yq(this.statePath)}}import{z as w}from"zod";var wY=w.object({workspaceRoot:w.string().min(1),cwd:w.string().optional(),provider:w.string().min(1),model:w.string().min(1),mode:w.enum(["act","plan"]).default("act"),apiKey:w.string(),systemPrompt:w.string().optional(),rules:w.string().optional(),maxIterations:w.number().int().positive().optional(),enableTools:w.boolean(),enableSpawn:w.boolean().optional(),enableTeams:w.boolean().optional(),autoApproveTools:w.boolean().optional(),missionStepInterval:w.number().int().positive().optional(),missionTimeIntervalMs:w.number().int().positive().optional()}),SY=w.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),hY=w.enum(["user","assistant","tool","system","status","error"]),CY=w.object({id:w.string().min(1),sessionId:w.string().nullable(),role:hY,content:w.string(),createdAt:w.number().int().nonnegative(),meta:w.object({stream:w.enum(["stdout","stderr"]).optional(),toolName:w.string().optional(),iteration:w.number().int().nonnegative().optional(),agentId:w.string().optional(),conversationId:w.string().optional(),hookEventName:w.string().optional(),inputTokens:w.number().int().nonnegative().optional(),outputTokens:w.number().int().nonnegative().optional(),checkpoint:w.object({ref:w.string(),createdAt:w.number().int().nonnegative(),runCount:w.number().int().positive(),kind:w.enum(["stash","commit"]).optional()}).optional()}).optional()}),EY=w.object({toolCalls:w.number().int().nonnegative(),tokensIn:w.number().int().nonnegative(),tokensOut:w.number().int().nonnegative()}),hq=w.object({sessionId:w.string().nullable(),status:SY,config:wY,messages:w.array(CY),rawTranscript:w.string(),error:w.string().nullable(),summary:EY});var Cq=vj;import{Agent as er,createAgentRuntime as $i}from"@cline/agents";import{getClineEnvironmentConfig as Eq}from"@cline/shared";var bq=5000,kY={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 kq($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function bY($){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 Iq($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],W=Array.isArray(f.free)?f.free:[],Z=J.map(bY).filter((j)=>j!==null),Q=W.map(bY).filter((j)=>j!==null);if(Z.length===0&&Q.length===0)return null;return{recommended:Z,free:Q}}function xq($){let f=$.baseUrl?.trim();if(f)return f;let J=Eq().apiBaseUrl;try{return($.providerSettingsManager??new a$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function mq($,f,J){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await $(f,{signal:W.signal})}finally{clearTimeout(Z)}}async function gq($={}){try{let f=xq($),J=$.fetchImpl??fetch,W=await mq(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??bq);if(!W.ok)throw Error(`HTTP ${W.status}`);let Z=await W.json(),Q=Iq(Z);if(Q)return Q}catch{}return kq(kY)}import{readFile as vq}from"node:fs/promises";import uq from"node:path";function cq($){return $}async function dq($){let f=uq.resolve($),J=await vq(f,"utf8"),W;try{W=JSON.parse(J)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${Q}`)}return lq(W,f)}function lq($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let W=$.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}import{BUILT_IN_PROVIDER_IDS as mY,createHandler as iq,createHandlerAsync as nq,getProviderCollection as aq,hasProvider as gY,registerAsyncHandler as tq,registerHandler as sq,registerModel as oq,registerProvider as vY}from"@cline/llms";function IY($){return $?{...$}:{}}function pq($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function rq($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function xY($){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 B9{providers=new Map;register($){rq($.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??{},...IY($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:pq($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...IY($.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 K9{configuredProviders=new B9;constructor($){this.applyConfig($)}createHandler($){return iq(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return nq(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(vY($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)sq($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)tq($.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.`);vY({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($){oq($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...mY]}async getBuiltInProviders(){return(await Promise.all(mY.map((f)=>aq(f)))).filter((f)=>f!==void 0).map((f)=>xY({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=gY(f.id),W=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof W==="string"&&gY(W);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function eq($){return new K9($)}bZ();async function kp(){return Promise.resolve().then(() => (eZ(),VY))}export{ij as writeHubDiscovery,T$ as writeGlobalSettings,nj as withHubStartupLock,g$ as verifyHubConnection,$2 as updateMcpServerOAuthState,NY as updateLocalProvider,dy as uninstallPlugin,gZ as truncateNotificationBody,M6 as toggleDisabledTool,mJ as toTeamProgressLifecycleEvent,Z$ as toProviderConfig,nD as toHubHealthUrl,ZZ as toHookConfigFileName,dJ as summarizeUsageFromMessages,tL as stopLocalHubServerGracefully,W$ as startLocalOAuthServer,oZ as startHubWebSocketServer,Tl as startHubServer,KV as startClineDeviceAuth,I5 as splitCoreSessionConfig,qJ as spawnDetachedHubServerWithRetry,wL as spawnDetachedHubServer,pB as setTelemetryOptOutGlobally,of as setMcpServerDisabled,UQ as setDisabledTools,tB as setDisabledPlugin,iB as setAutoUpdateEnabledGlobally,Fc as sendHubCommand,Xq as saveLocalProviderSettings,Kq as saveLocalProviderOAuthCredentials,G2 as sanitizeSessionToken,HQ as safeParseSettings,_B as safeCreateProviderConfig,V4 as runSubprocessEvent,K4 as runHook,O3 as reviveTeamStateDates,HH as restartLocalHubIfIdleAfterStartupTimeout,pk as resolveWorkspaceHubOwnerContext,W5 as resolveWorkflowsConfigSearchPaths,f5 as resolveSkillsConfigSearchPaths,R0 as resolveSharedHubOwnerContext,jN as resolveSessionBackend,J5 as resolveRulesConfigSearchPaths,L6 as resolveProviderConfig,bf as resolvePluginSkillDirectoriesFromPaths,c6 as resolvePluginConfigSearchPaths,C$ as resolveMcpServerRegistrations,Gq as resolveLocalClineAuthToken,eN as resolveHubUrl,_1 as resolveHubOwnerContext,m$ as resolveHubEndpointOptions,Xf as resolveHubBuildId,JZ as resolveHooksConfigSearchPaths,Q$ as resolveDisabledToolNames,D8 as resolveDisabledPluginPaths,h0 as resolveDefaultMcpSettingsPath,yJ as resolveDefaultHubPort,QL as resolveDefaultHubPathname,ZL as resolveDefaultHubHost,N3 as resolveCoreSelectedToolIds,NW as resolveCompatibleLocalHubUrl,Ik as resolveClineDir,DW as resolveClineDataDir,q8 as resolveAndLoadAgentPlugins,Ef as resolveAgentPluginPaths,LW as requestHubShutdown,Ly as requestDesktopToolApproval,Af as rememberRecoverableLocalHubUrl,GY as registerRemoteConfigSessionBlobUpload,f2 as registerMcpServersFromSettingsFile,ep as registerDisposable,Aq as refreshProviderModelsFromSource,H6 as refreshOpenAICodexToken,K6 as refreshOcaToken,Q6 as refreshClineToken,FZ as readSessionCheckpointHistory,Yy as readRemoteConfigSessionBlobUploadMetadata,K0 as readHubDiscovery,L0 as readGlobalSettings,x$ as probeHubServer,Uc as probeHubConnection,h7 as prewarmFileIndex,sj as prewarmDetachedHubServer,Ky as prepareRemoteConfigCoreIntegration,$5 as parseWorkflowConfigFromMarkdown,op as parseUserCommandEnvelope,o6 as parseSkillConfigFromMarkdown,jQ as parseSettings,e6 as parseRuleConfigFromMarkdown,B4 as parseHookEventPayload,_V as openaiCodexOAuthProvider,R1 as normalizeWorkspacePath,sp as normalizeUserInput,tp as normalizeSdkError,F0 as normalizeRuntimeCapabilities,G8 as normalizeProviderId,zV as normalizeOpenAICodexCredentials,Yq as normalizeOAuthProvider,Yf as normalizeHubWebSocketUrl,ap as noopBasicLogger,GZ as migrateLegacyProviderSettings,k8 as mergeRulesForSystemPrompt,I2 as mergeAgentHooks,ZW as makeTeamTaskSubSessionId,zJ as makeSubSessionId,W8 as loginOpenAICodex,Q8 as loginOcaOAuth,Bq as loginLocalProvider,f8 as loginClineOAuth,kp as loadOpenTelemetryAdapter,sf as loadMcpSettingsFile,dq as loadLlmsConfigFromFile,hf as loadAgentPluginsFromPathsWithDiagnostics,hQ as loadAgentPluginsFromPaths,I6 as loadAgentPluginFromPath,ED as listSessionHistoryFromBackend,o3 as listPluginToolsWithDiagnostics,k5 as listPluginTools,h5 as listMcpServerOAuthStatuses,jq as listLocalProviders,Gf as listHookConfigFiles,nB as isToolDisabledGlobally,N6 as isTelemetryOptedOutGlobally,F1 as isSessionNotFoundError,tQ as isRuleEnabled,aB as isPluginDisabledGlobally,OV as isOpenAICodexTokenExpired,dL as isHubReconnectableTransportError,QH as isHubCommandTimeoutError,gk as isDiscoveryFilePresent,R9 as isClineAccountActionRequest,DB as isBuiltInProviderId,rB as isAutoUpdateEnabledGlobally,O$ as identifyAccount,P1 as hasMcpSettingsFile,X6 as getValidOpenAICodexCredentials,G6 as getValidOcaCredentials,j6 as getValidClineCredentials,zq as getProviderConfigFields,a9 as getProviderConfig,ef as getMcpServerOAuthState,Hq as getLocalProviderModels,K8 as getLiveModelsCatalog,Y1 as getFileIndex,kz as getCurrentContextSize,y5 as getCoreHeadlessToolNames,T3 as getCoreDefaultEnabledToolIds,rf as getCoreBuiltinToolCatalog,M3 as getCoreAcpToolNames,gp as getClineDefaultSystemPrompt,u5 as generateWorkspaceInfoWithDiagnostics,LJ as generateWorkspaceInfo,v9 as generateOcaOpcRequestId,b8 as formatRulesForSystemPrompt,np as formatDisplayUserInput,q6 as filterExtensionToolRegistrations,r1 as filterDisabledTools,y6 as filterDisabledPluginPaths,gq as fetchClineRecommendedModels,D9 as executeClineAccountAction,YY as ensureHubWebSocketServer,Nl as ensureHubServer,JI as ensureDetachedHubServer,IX as ensureCustomProvidersLoaded,_2 as ensureCompatibleLocalHubUrl,t8 as enrichPromptWithMentions,ip as emptyWorkspaceManifest,Pf as emptyStoredProviderSettings,d6 as discoverPluginModulePaths,QW as deriveSubsessionStatus,MY as deleteLocalProvider,cq as defineLlmsConfig,j5 as createWorkflowsConfigDefinition,Zf as createUserInstructionConfigService,k7 as createToolPoliciesWithPreset,rp as createTool,fA as createTeamName,PA as createSubprocessHooks,Wf as createSpawnAgentTool,Z5 as createSkillsConfigDefinition,Y4 as createSessionHost,Y4 as createRuntimeHost,Q5 as createRulesConfigDefinition,By as createRemoteConfigSessionMessagesArtifactUploader,zB as createProviderConfig,D4 as createOpenTelemetryTelemetryService,lV as createOcaRequestHeaders,dV as createOcaOAuthProvider,x4 as createOAuthClientCallbacks,PJ as createMcpTools,wc as createLocalHubScheduleRuntimeHandlers,eq as createLlmsSdk,G0 as createInitialAccumulatedUsage,mk as createInMemoryHubOwnerContext,Y$ as createHubServerUrl,rj as createHubAuthToken,XZ as createHookConfigFileHooks,aJ as createHookConfigFileExtension,nJ as createHookAuditHooks,b5 as createDisabledMcpToolPolicy,t3 as createDisabledMcpToolPolicies,WJ as createDelegatedAgentConfigProvider,ZJ as createDelegatedAgent,I7 as createDefaultToolsWithPreset,$f as createDefaultTools,KJ as createDefaultMcpServerClientFactory,$J as createDefaultExecutors,Z2 as createCoreSettingsService,v$ as createCoreSessionSnapshot,pp as createContributionRegistry,eW as createContextCompactionPrepareTurn,k1 as createConfiguredTelemetryService,L4 as createConfiguredTelemetryHandle,lp as createClineTelemetryServiceMetadata,dp as createClineTelemetryServiceConfig,PV as createClineOAuthProvider,nf as createBuiltinTools,pf as createAgentTeamsTools,$i as createAgentRuntime,lJ as createAgentHooksExtension,DA as connectToHub,GV as completeClineDeviceAuth,UB as clearPrivateModelsCatalogCache,PB as clearLiveModelsCatalogCache,e0 as clearHubDiscovery,oY as captureWorkspacePathResolved,m4 as captureWorkspaceInitialized,g4 as captureWorkspaceInitError,l4 as captureToolUsage,c4 as captureTokenUsage,u4 as captureTaskRestarted,v4 as captureTaskCreated,a2 as captureTaskCompleted,s2 as captureSubagentExecution,p4 as captureSkillUsed,cp as captureSdkError,eY as captureProviderConfigured,t2 as captureProviderApiError,d4 as captureModeSwitch,i4 as captureMentionUsed,a4 as captureMentionSearchResults,n4 as captureMentionFailed,s4 as captureHookDiscovery,sY as captureExtensionActivated,r4 as captureDiffEditFailure,Nf as captureConversationTurnEvent,e4 as captureCompactionSkipped,o4 as captureCompactionExecuted,D$ as captureAuthSucceeded,R$ as captureAuthStarted,J1 as captureAuthLoggedOut,L$ as captureAuthFailed,t4 as captureAgentTeamCreated,W1 as captureAgentCreated,c5 as buildWorkspaceMetadata,xJ as buildTeamProgressSummary,vp as buildSdkErrorProperties,BY as buildRemoteConfigSessionBlobUploadMetadata,df as buildDelegatedAgentConfig,HJ as bootstrapAgentTeams,v3 as authorizeMcpServerOAuth,Qq as addLocalProvider,A0 as accumulateUsageTotals,n6 as WORKFLOWS_CONFIG_DIRECTORY_NAME,qf as UnifiedConfigFileWatcher,s0 as ToolPresets,d2 as TelemetryService,R4 as TelemetryLoggerSink,jJ as TEAM_TOOL_NAMES,O8 as SubprocessSandbox,sJ as StoredProviderSettingsSchema,UX as StoredProviderSettingsEntrySchema,m2 as SqliteTeamStore,d$ as SqliteSessionStore,Rf as SessionVersioningService,p0 as SessionVersioningError,U0 as SessionSource,U1 as SessionNotFoundError,WQ as SapSettingsSchema,i6 as SKILLS_CONFIG_DIRECTORY_NAME,_6 as SESSION_STATUSES,Q2 as SESSION_NOT_FOUND_ERROR_CODE,$r as SDK_ERROR_TELEMETRY_EVENT,I4 as RpcClineAccountService,hJ as RemoteRuntimeHost,e9 as ReasoningSettingsSchema,dQ as RULES_CONFIG_DIRECTORY_NAME,KY as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,l1 as ProviderSettingsSchema,a$ as ProviderSettingsManager,t9 as ProviderProtocolSchema,z6 as ProviderIdSchema,s9 as ProviderClientSchema,l2 as OpenTelemetryProvider,ZQ as OcaSettingsSchema,D6 as OPENAI_COMPATIBLE_PROVIDERS,V$ as NodeHubClient,tZ as NativeHubTransportAdapter,QQ as ModelCatalogSettingsSchema,t$ as LocalRuntimeHost,xp as Llms,oJ as InMemoryWorkspaceManager,J2 as InMemoryMcpManager,ZM as HubUIClient,k0 as HubTransportError,WM as HubSessionClient,y4 as HubServerTransport,F4 as HubScheduleService,G4 as HubScheduleCommandService,M1 as HubRuntimeHost,wJ as HubCommandError,KA as HookEventPayloadSchema,BA as HookEventNameSchema,pJ as HookConfigFileName,WZ as HOOK_CONFIG_FILE_EVENT_MAP,HX as HOOKS_CONFIG_DIRECTORY_NAME,R8 as GlobalSettingsSchema,fQ as GcpSettingsSchema,qY as FileTeamPersistenceStore,kY as FALLBACK_CLINE_RECOMMENDED_MODELS,j0 as DefaultToolNames,H4 as DefaultRuntimeBuilder,K9 as DefaultLlmsSdk,r9 as DEFAULT_MODELS_CATALOG_URL,JL as DEFAULT_HUB_PORT,WL as DEFAULT_HUB_PATHNAME,fL as DEFAULT_HUB_HOST,Hf as CoreSettingsService,l$ as CoreSessionService,up as ContributionRegistry,CZ as ClineCore,k4 as ClineAccountService,hq as ChatViewStateSchema,EY as ChatSummarySchema,SY as ChatSessionStatusSchema,wY as ChatSessionConfigSchema,CY as ChatMessageSchema,hY as ChatMessageRoleSchema,k as CORE_TELEMETRY_EVENTS,Cq as CORE_BUILD_VERSION,aZ as BrowserWebSocketHubAdapter,RB as BUILT_IN_PROVIDER_IDS,O6 as BUILT_IN_PROVIDER,JQ as AzureSettingsSchema,$Q as AwsSettingsSchema,o9 as AuthSettingsSchema,q2 as AgentTeamsRuntime,bW as AgentTeam,er as Agent,o1 as ALL_DEFAULT_TOOL_NAMES};
713
+ `),f.end()}catch{f.destroy()}}function EY(f,$){if(!f||!$)return!1;let J=Buffer.from(f,"utf8"),Q=Buffer.from($,"utf8");return J.length===Q.length&&bq(J,Q)}function hY(f,$){let J=f&&typeof f==="object"&&"code"in f&&typeof f.code==="string"?f.code:void 0,Q=f instanceof Error?f.message:typeof f==="string"?f:"Unknown startup error",Z=`Failed to start hub server on ${$.host}:${$.port}${$.pathname}: ${Q}`,W=Error(J?`${Z} (${J})`:Z);if(J)f.code=J,W.code=J;if(f instanceof Error&&f.stack)W.stack=`${W.name}: ${W.message}
714
+ Caused by: ${f.stack}`;return W}async function uq(f){return await new Promise(($,J)=>{let Q=Iq.createServer();Q.once("error",J),Q.listen(0,f,()=>{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}$(W)})})})}function dq(f){return f instanceof Error&&"code"in f&&f.code==="EADDRINUSE"}var GZ=new Map,bY="cline-hub-auth.",lq=30000;function kY(f){return Array.isArray(f)?f.join(","):f??""}function pq(f){let $=kY(f).trim();return/^Bearer\s+(.+)$/i.exec($)?.[1]?.trim()||null}function rq(f){for(let $ of kY(f).split(",")){let J=$.trim();if(J.startsWith(bY))return J.slice(bY.length).trim()||null}return null}async function FZ(f){let $=f.owner??q$(),J=f.host??"127.0.0.1",Q=f.pathname??"/hub",Z=f.port??bJ(),W=Z===0?await uq(J):Z,j=W,H=Gf(J,W,Q),X=F1(),A=KH(),Y=new g4(f);await Y.start();let V=new KZ(new PZ(Y),f.telemetry),B=new Set,K=new Date().toISOString(),P={protocolVersion:"v1",coreVersion:y2.version,buildId:X,pid:process.pid,startedAt:K},R=new Set,G,F,U=async()=>{if(F)return F;return F=(async()=>{if(G)clearInterval(G),G=void 0;for(let D of R)D.terminate?.();R.clear();for(let D of B)D();if(B.clear(),await new Promise((D,M)=>{T.close((S)=>{if(S){M(S);return}D()})}),await new Promise((D,M)=>{_.close((S)=>{if(S){M(S);return}D()})}),await Y.stop(),(await P0($.discoveryPath))?.url===H)await $f($.discoveryPath)})(),F},_=kq.createServer((L,D)=>{if((L.url??"/")==="/health"){let S=JSON.stringify({hubId:Y.getHubId(),...P,authToken:"",host:J,port:j,url:H,updatedAt:new Date().toISOString()});D.statusCode=200,D.setHeader("content-type","application/json"),D.end(S);return}if((L.url??"/")==="/version"){D.statusCode=200,D.setHeader("content-type","application/json"),D.end(JSON.stringify(P));return}if(new SY(L.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&L.method==="POST"){if(!EY(pq(L.headers.authorization),A)){D.statusCode=401,D.end("Unauthorized");return}D.statusCode=202,D.setHeader("content-type","application/json"),D.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{U()});return}D.statusCode=404,D.end("Not found")}),T=new xq({noServer:!0});G=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)}}},lq),_.on("upgrade",(L,D,M)=>{if(new SY(L.url??"/",`http://${J}:${j}`).pathname!==Q){D.destroy();return}if(!EY(rq(L.headers["sec-websocket-protocol"]),A)){cq(D);return}try{T.handleUpgrade(L,D,M,(h)=>{let a=h;a.isAlive=!0,a.on("pong",()=>{a.isAlive=!0}),R.add(a);let W0=V.attach(mq(h));B.add(W0),h.once("close",()=>{R.delete(a),W0(),B.delete(W0)})})}catch{vq(D)}});try{await new Promise((L,D)=>{_.once("error",(M)=>{D(hY(M,{host:J,port:W,pathname:Q}))}),_.listen(W,J,()=>{let M=_.address();if(!M||typeof M==="string"){D(hY(Error("Failed to resolve hub port"),{host:J,port:W,pathname:Q}));return}j=M.port,H=Gf(J,j,Q),L()})})}catch(L){if(G)clearInterval(G),G=void 0;throw await Y.stop().catch(()=>{return}),L}return await PH($.discoveryPath,{hubId:Y.getHubId(),protocolVersion:"v1",coreVersion:y2.version,buildId:X,authToken:A,host:J,port:j,url:H,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:H,authToken:A,close:U}}async function IY(f){let $=f.owner??q$(),J=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=f.host??"127.0.0.1",Z=f.port??bJ(),W=f.pathname??"/hub",j=Gf(Q,Z,W),H=$.discoveryPath,X=(Y)=>{if(!J)U1(Y.url,Y.authToken);return Y},A=GZ.get(H);if(A){let Y=await A;if(Y.url===j)return X({server:Y,url:Y.url,authToken:Y.authToken,action:"reuse"})}return await GH($.discoveryPath,async()=>{let Y=await P0($.discoveryPath);if(Y?.url&&(Y.url===j||f.allowPortFallback===!0)){let P=await uf(Y.url);if(P?.url&&await lf(P.url,{authToken:Y.authToken}))return X({url:P.url,authToken:Y.authToken,action:"reuse"})}if((await uf(j))?.url||Y?.url)await $f($.discoveryPath);let K=async(P)=>{let R=FZ({...P,owner:$});GZ.set(H,R);try{let G=await R;return X({server:G,url:G.url,authToken:G.authToken,action:"started"})}catch(G){throw GZ.delete(H),G}};try{return await K(f)}catch(P){if(!f.allowPortFallback||!dq(P))throw P;return await K({...f,port:0})}})}async function qp(f){let $=df({host:f.host,port:f.port,pathname:f.pathname});return await FZ({...f,...$,owner:D0()})}async function yp(f){let $=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=df({host:f.host,port:f.port,pathname:f.pathname});return await IY({...f,...J,allowPortFallback:f.allowPortFallback??!$,owner:D0()})}UZ();import{buildRemoteConfigSessionBlobUploadMetadata as gY,clearRemoteConfigSessionBlobUpload as iq,createClineTelemetryServiceConfig as nq,createSessionId as aq,createRemoteConfigSessionMessagesArtifactUploader as tq,prepareRemoteConfigRuntime as sq,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as mY,readRemoteConfigSessionBlobUploadMetadata as oq,registerRemoteConfigSessionBlobUpload as vY}from"@cline/shared";function eq(f,$){let J=f.telemetry||$.telemetryService?{...$.telemetryService??{},...f.telemetry??{}}:void 0;if(!J)return;return m$(nq(J)).telemetry}function fy(){let f=tq();return{async uploadMessagesFile($){await f.uploadMessagesFile($)}}}async function $y(f){let $=await sq(f),J=eq($,f),Q=[$.pluginDefinition],Z=$.claims?.subject,W=gY($.bundle?.remoteConfig,Z),j;return{prepared:$,extensions:Q,telemetry:J,applyToStartSessionInput(H){let X=H.config.extensions??[],A=H.config.telemetry,Y=W?H.config.sessionId?.trim()||aq():H.config.sessionId;if(Y&&W)j=Y;let V=Y&&W?vY(Y,$.bundle?.remoteConfig,Z):void 0,B=V?{...H.sessionMetadata??{},[mY]:V}:H.sessionMetadata;return{...H,...B?{sessionMetadata:B}:{},config:{...H.config,...Y?{sessionId:Y}:{},extensions:[...X,...Q],telemetry:J??A}}},async dispose(){if(j)iq(j)}}}import{mkdir as Jy,readFile as Qy,unlink as Zy,writeFile as Wy}from"node:fs/promises";import{join as cY}from"node:path";function jy(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function Hy(f){return new Promise(($)=>setTimeout($,f))}async function RZ(f){try{await Zy(f)}catch{}}async function Xy(f,$={}){let J=$.approvalDir?.trim(),Q=$.sessionId?.trim();if(!J||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await Jy(J,{recursive:!0});let Z=jy(`${f.toolCallId}`),W=cY(J,`${Q}.request.${Z}.json`),j=cY(J,`${Q}.decision.${Z}.json`),H=$.nowIso??(()=>new Date().toISOString());await Wy(W,`${JSON.stringify({requestId:Z,sessionId:Q,createdAt:H(),toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,iteration:f.iteration,agentId:f.agentId,conversationId:f.conversationId},null,2)}
715
+ `,"utf8");let X=$.timeoutMs??300000,A=$.pollIntervalMs??200,Y=Date.now();while(Date.now()-Y<X){try{let V=await Qy(j,"utf8"),B=JSON.parse(V),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([RZ(j),RZ(W)]),K}catch{}await Hy(A)}return await RZ(W),{approved:!1,reason:"Tool approval request timed out"}}t0();t0();import{existsSync as C1,readdirSync as Ay,readFileSync as Yy,rmdirSync as Vy,rmSync as By,statSync as Ky}from"node:fs";import{basename as d0,dirname as Z$,extname as Py,isAbsolute as Gy,join as Of,relative as Fy,resolve as w1,sep as DZ}from"node:path";import{discoverPluginModulePaths as Uy,resolvePluginConfigSearchPaths as Ry}from"@cline/shared/storage";var zZ="_installed",Dy="package",Ly=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function LZ(f){return f.trim().toLowerCase()}function n0(f,$){let J=$?.trim();if(!J)return;f.add(J)}function Oy(f){return f.replace(/-[0-9a-f]{12}$/i,"")}function OZ(f){let $=Py(f);return $?f.slice(0,-$.length):f}function _Z(f){if(!C1(f))return;try{let $=JSON.parse(Yy(f,"utf8"));return typeof $.name==="string"?$.name.trim():void 0}catch{return}}function MZ(f,$){let J=Fy($,f);return J===""||!J.startsWith("..")&&!Gy(J)}function uY(f){let J=w1(f).split(DZ),Q=J.lastIndexOf(zZ);if(Q<0)return;let Z=J[Q+1];if(!Z)return;let W=Ly.get(Z)??1,j=Q+2+W;if(J.length<j)return;let H=J.slice(0,j).join(DZ)||DZ;return C1(H)?H:void 0}function m4(f){try{return Ay(f,{withFileTypes:!0})}catch{return[]}}function _y(f){let $=Of(f,zZ);if(!C1($))return[];let J=[];for(let Q of m4($)){if(!Q.isDirectory())continue;let Z=Of($,Q.name);if(Q.name==="git"){for(let W of m4(Z)){if(!W.isDirectory())continue;let j=Of(Z,W.name);for(let H of m4(j))if(H.isDirectory())J.push(Of(j,H.name))}continue}for(let W of m4(Z))if(W.isDirectory())J.push(Of(Z,W.name))}return J.sort((Q,Z)=>Q.localeCompare(Z))}function dY(f){try{return Uy(f)}catch{return[]}}function TZ(f){let $=dY(f),J=new Set;n0(J,d0(f)),n0(J,Oy(d0(f))),n0(J,_Z(Of(f,"package.json"))),n0(J,_Z(Of(f,Dy,"package.json")));for(let Q of $)n0(J,d0(Q)),n0(J,OZ(d0(Q)));return{installPath:f,entryPaths:$,names:[...J].sort((Q,Z)=>Q.localeCompare(Z)),installed:!0}}function Ty(f,$){let J=w1(f),Q=$.find((j)=>MZ(J,j));if(!Q)return;let Z=Z$(J);while(Z!==Q&&Z!==Z$(Z)){if(C1(Of(Z,"package.json")))return Z;Z=Z$(Z)}let W=d0(J);if((W==="index.ts"||W==="index.js")&&Z$(J)!==Q)return Z$(J);return J}function lY(f,$){let J=Ty(f,$);if(!J)return;let Q=new Set;return n0(Q,d0(f)),n0(Q,OZ(d0(f))),n0(Q,d0(J)),n0(Q,OZ(d0(J))),n0(Q,_Z(Of(J,"package.json"))),{installPath:J,entryPaths:[f],names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!1}}function zy(f){let $=f.workspaceRoot?.trim()||f.cwd?.trim()||process.cwd();return Ry($).filter((J)=>C1(J))}function My(f){let $=new Map;for(let J of f){for(let Q of _y(J))$.set(Q,TZ(Q));for(let Q of dY(J)){let Z=uY(Q);if(Z){if(!$.has(Z))$.set(Z,TZ(Z));continue}let W=lY(Q,f);if(W)$.set(W.installPath,W)}}return[...$.values()].sort((J,Q)=>J.installPath.localeCompare(Q.installPath))}function Ny(f,$){let J=LZ($);if(!J)return!1;if(LZ(f.installPath)===J)return!0;return f.names.some((Q)=>LZ(Q)===J)}function qy(f,$,J){let Q=w1(f);for(let W of $){if(MZ(Q,W.installPath))return W;if(W.entryPaths.some((j)=>w1(j)===Q))return W}let Z=uY(Q);if(Z)return TZ(Z);if(C1(Q))return lY(Q,J);return}function yy(f){let $=T0(),J=$.disabledPlugins;if(!J?.length)return;let Q=J.filter((Z)=>{let W=w1(Z);if(MZ(W,f.installPath))return!1;return!f.entryPaths.some((j)=>w1(j)===W)});if(Q.length===J.length)return;wf({...$,disabledPlugins:Q})}function wy(f){let $=Z$(f);while($!==Z$($)&&d0($)!==zZ){try{Vy($)}catch{return}$=Z$($)}}function Cy(f){return`${f.names[0]??d0(f.installPath)} at ${f.installPath}`}async function Sy(f){let $=zy(f),J=My($),Q=f.path?.trim(),Z=f.name?.trim(),W;if(Q){if(W=qy(Q,J,$),!W)throw Error(`No plugin found at ${Q}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let H=J.filter((X)=>Ny(X,Z));if(H.length===0)throw Error(`No plugin found matching "${Z}"`);if(H.length>1)throw Error(`Multiple plugins match "${Z}": ${H.map(Cy).join(", ")}`);W=H[0]}let j=Ky(W.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${W.installPath}`);if(By(W.installPath,{recursive:j.isDirectory(),force:!0}),yy(W),W.installed)wy(W.installPath);return{name:Z||W.names[0]||d0(W.installPath),installPath:W.installPath,removedPaths:[W.installPath],entryPaths:W.entryPaths}}import*as O0 from"@cline/llms";function Ey(f){return f.apiKey??f.auth?.apiKey}function hy(f){return(f.auth?.accessToken?.trim()??"").length>0}function rY(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function by(f){let $=f.split(/\s+/).filter(Boolean);if($.length===0)return"?";if($.length===1)return $[0].slice(0,2).toUpperCase();return`${$[0][0]}${$[1][0]}`.toUpperCase()}function ky(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of f)J=J*31+Q.charCodeAt(0)>>>0;return $[J%$.length]}function iY(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>$A($,J))}async function Iy(f,$){let J=await O0.getModelsForProvider(f);if(!$)return J;let Q=await h6(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return Q?.knownModels?{...J,...Q.knownModels}:J}function NZ(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function xy(f){if(!f?.length)return;return[...new Set(f)]}function gy(f,$){return xy([...f??[],...$??[]])}function my(f){let $=f?.popularRank;return typeof $==="number"&&Number.isFinite($)?$:Number.MAX_SAFE_INTEGER}function vy(f){if(!f||typeof f!=="object")return!1;let $=f;return typeof $.path==="string"&&$.path.trim().length>0&&typeof $.label==="string"&&$.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String($.type))}function cy(f){let $=f?.configFields;if(!Array.isArray($))return;return $.filter(vy)}var v4={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},pY={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function uy(f){if(!f)return[v4];if(f.source!=="system")return f.baseUrl?[v4,pY]:[v4];let $=[];if(f.env?.length)$.push(v4);if(f.baseUrl)$.push(pY);return $}function dy(f,$){return $.split(".").reduce((J,Q)=>{if(!J||typeof J!=="object")return;return J[Q]},f)}function ly(f){if(typeof f==="string"||typeof f==="number"||typeof f==="boolean"||f===null)return f;return}function py(f,$,J){if(!f?.length)return;let Q={};for(let Z of f){let j=ly(Z.path==="baseUrl"&&$?.baseUrl===void 0?J?.baseUrl:dy($,Z.path))??Z.defaultValue;if(j!==void 0)Q[Z.path]=j}return Q}function nY(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function qZ(f,$){let J=$?.includes("vision")??!1,Q=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function aY(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await G8(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function tY(f,$){let J=f.read(),Q=!1;if(J.providers[$])delete J.providers[$],Q=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,Q=!0;if(Q)f.write(J);O0.unregisterProvider($)}async function ry(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=$.baseUrl.trim(),Z=$.apiKey?.trim()??"";if(!Q&&!Z){let P=k$(f);if((await z1(P)).providers[J]){let G=await oY(f,{providerId:J});return{providerId:J,settingsPath:G.settingsPath,modelsPath:G.modelsPath,modelsCount:0}}return tY(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:P,modelsCount:0}}if(O0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=$.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=NZ($.models),H=$.modelsSourceUrl?.trim(),X=await aY({providerId:J,explicitModels:j,modelsSourceUrl:H,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=$.defaultModelId?.trim()&&X.includes($.defaultModelId.trim())?$.defaultModelId.trim():X[0],Y=$.capabilities?.length?[...new Set($.capabilities)]:void 0,V=nY($.headers);f.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:V,timeout:$.timeoutMs,model:A,protocol:$.protocol,client:$.client},{setLastUsed:!1});let B=k$(f),K=await z1(B);return K.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:A,protocol:$.protocol,client:$.client,capabilities:Y,modelsSourceUrl:H},models:qZ(X,Y)},await V4(B,K),p2(J,K.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:B,modelsCount:X.length}}async function sY(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=k$(f),Z=await z1(Q),W=Z.providers[J];if(!W){let T=f.getProviderSettings(J);if(!T)throw Error(`provider "${J}" does not exist`);let L=$.modelsSourceUrl?.trim(),D=NZ($.models)[0]??T.model?.trim();if(!D&&!L)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:$.name?.trim()||rY(J),baseUrl:$.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:D,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:D?qZ([D],T.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=$.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let H=$.baseUrl?.trim()??W.provider.baseUrl.trim();if(!H)throw Error("baseUrl is required");let X=$.capabilities===void 0?W.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],A=$.protocol===void 0?W.provider.protocol:$.protocol??void 0,Y=$.client===void 0?W.provider.client:$.client??void 0,V=NZ($.models),B=$.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,K=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!B,P=Object.keys(W.models??{}).map((T)=>T.trim()).filter(Boolean),R=await aY({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:P,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let G=$.defaultModelId===void 0?W.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=G&&R.includes(G)?G:R[0],_={...f.getProviderSettings(J)??{},provider:J,baseUrl:H,model:F};if(A)_.protocol=A;else delete _.protocol;if(Y)_.client=Y;else delete _.client;if($.apiKey!==void 0){let T=$.apiKey?.trim()??"";if(T)_.apiKey=T;else delete _.apiKey}if($.headers!==void 0){let T=nY($.headers);if(T)_.headers=T;else delete _.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")_.timeout=$.timeoutMs;else delete _.timeout;return f.saveProviderSettings(_,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:H,defaultModelId:F,protocol:A,client:Y,capabilities:X,modelsSourceUrl:B},models:qZ(R,X)},await V4(Q,Z),p2(J,Z.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Q,modelsCount:R.length}}async function oY(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=k$(f),Z=await z1(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await V4(Q,Z),O0.unregisterProvider(J),tY(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Q}}async function iy(f){let $=f.read(),J=O0.getProviderIds(),Q=await Promise.all(J.map(async(W)=>{let[j,H]=await Promise.all([O0.getProvider(W),O0.getModelsForProvider(W)]),X=iY(H),A=$.providers[W]?.settings,Y=j?.name??rY(W),V=gy(j?.capabilities,A?.capabilities),B=cy(j?.metadata)??uy(j);return{provider:{id:W,name:Y,models:X.length,color:ky(W),letter:by(Y),enabled:Boolean(A),apiKey:A?Ey(A):void 0,oauthAccessTokenPresent:A?hy(A):void 0,baseUrl:A?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:A?.protocol??j?.protocol,client:A?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:py(B,A,j),modelList:X},rank:my(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:f.getFilePath()}}async function ny(f,$){let J=f.trim(),Q=await Iy(J,$),Z=iY(Q);return{providerId:J,models:Z}}function c4(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function eY(f,$){if(!c4($))return c4(f)?{...f}:void 0;let J=c4(f)?{...f}:{};for(let[Q,Z]of Object.entries($)){if(Z==null||Z===""){delete J[Q];continue}if(c4(Z)){let W=eY(J[Q],Z);if(W&&Object.keys(W).length>0)J[Q]=W;else delete J[Q];continue}J[Q]=Z}return Object.keys(J).length>0?J:void 0}function ay(f,$){let J=$.providerId.trim();if($.enabled===!1){let W=f.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return f.write(W),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let Z={...f.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,W)&&typeof $[W]==="string")if($[W].trim().length===0)delete Z[W];else Z[W]=$[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,W))Z[W]=$[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,W)&&$[W]!=null){let j=eY(Z[W],$[W]);if(j)Z[W]=j;else delete Z[W]}return f.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function ty(f,$){let J=$.trim(),Q=f.getProviderSettings(J),W=O0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),H=F8(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!H)return{providerId:J,refreshed:!1};let X=await sY(f,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:H,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function sy(f){let $=f.trim().toLowerCase(),J=B0($);if(J)return J.providerId;throw Error(`provider "${f}" does not support OAuth login`)}async function oy(f,$,J,Q){let Z=B0(f);if(!Z)throw Error(`provider "${f}" does not support OAuth login`);let W=Z8({onPrompt:async(j)=>j.defaultValue??"",openUrl:J,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return Z.login({settings:$,callbacks:W,telemetry:Q})}function ey(f,$,J,Q,Z){return k1({manager:f,providerId:$,settings:J,credentials:Q,setLastUsed:Z?.setLastUsed})}async function fw(f,$,J,Q){let Z=Z8({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});return N6(f,$,{callbacks:Z,telemetry:Q})}function $w(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}import*as u4 from"@cline/llms";var Jw=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Qw={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function Zw(f,$){let J={};for(let Q of Jw){let Z=f[Q],W=$[Q];if(Z||W)J[Q]={...Z,...W}}return J}function Ww(f){let $=Qw[f.providerId];if(!$)return f;return{...f,description:$.description??f.description,fields:$.mode==="replace"?$.fields:Zw(f.fields,$.fields)}}var jw=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Hw(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return jw.has(f)}function Xw(f){let $=u4.normalizeProviderId(f);if(b1($))return{providerId:$,authMethod:"oauth",fields:{}};let J=u4.MODEL_COLLECTIONS_BY_PROVIDER_ID[$];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:$,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if(Hw($,J))Z.baseUrl={defaultValue:Q};return Ww({providerId:$,authMethod:"api-key",fields:Z})}V0();E4();import{appendFileSync as Aw,existsSync as yZ,mkdirSync as Yw,readFileSync as Vw,renameSync as Bw,unlinkSync as Kw,writeFileSync as Pw}from"node:fs";import{join as wZ}from"node:path";import{resolveTeamDataDir as Gw}from"@cline/shared/storage";function Fw(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class fV{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=Fw(f.teamName),J=f.baseDir?.trim()||Gw();this.dirPath=wZ(J,$),this.statePath=wZ(this.dirPath,"state.json"),this.taskHistoryPath=wZ(this.dirPath,"task-history.jsonl")}loadState(){if(!yZ(this.statePath))return;try{let f=Vw(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return jX($.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec(f){this.teammateSpecs.set(f.agentId,f)}removeTeammateSpec(f){this.teammateSpecs.delete(f)}persist(f){if(!this.hasPersistableState(f)){this.clearPersistedState();return}this.ensureDir();let $={version:1,updatedAt:new Date().toISOString(),teamState:f.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;Pw(J,`${JSON.stringify($,null,2)}
716
+ `,"utf8"),Bw(J,this.statePath)}appendTaskHistory(f){let $={};switch(f.type){case"team_task_updated":$=f.task;break;case"team_message":$={agentId:f.message.fromAgentId,toAgentId:f.message.toAgentId,subject:f.message.subject,taskId:f.message.taskId};break;case"team_mission_log":$={agentId:f.entry.agentId,kind:f.entry.kind,summary:f.entry.summary,taskId:f.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":$={agentId:f.agentId,message:"message"in f?f.message:void 0};break;case"task_end":$={agentId:f.agentId,finishReason:f.result?.finishReason,error:f.error?.message};break;case"agent_event":$={agentId:f.agentId,eventType:f.event.type};break}this.ensureDir(),Aw(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:f.type,task:$})}
717
+ `,"utf8")}ensureDir(){if(!yZ(this.dirPath))Yw(this.dirPath,{recursive:!0})}hasPersistableState(f){let $=f.exportState();if(this.teammateSpecs.size>0)return!0;if($.members.some((J)=>J.role==="teammate"))return!0;return $.tasks.length>0||$.mailbox.length>0||$.missionLog.length>0}clearPersistedState(){if(yZ(this.statePath))Kw(this.statePath)}}import{z as w}from"zod";var $V=w.object({workspaceRoot:w.string().min(1),cwd:w.string().optional(),provider:w.string().min(1),model:w.string().min(1),mode:w.enum(["act","plan"]).default("act"),apiKey:w.string(),systemPrompt:w.string().optional(),rules:w.string().optional(),maxIterations:w.number().int().positive().optional(),enableTools:w.boolean(),enableSpawn:w.boolean().optional(),enableTeams:w.boolean().optional(),autoApproveTools:w.boolean().optional(),missionStepInterval:w.number().int().positive().optional(),missionTimeIntervalMs:w.number().int().positive().optional()}),JV=w.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),QV=w.enum(["user","assistant","tool","system","status","error"]),ZV=w.object({id:w.string().min(1),sessionId:w.string().nullable(),role:QV,content:w.string(),createdAt:w.number().int().nonnegative(),meta:w.object({stream:w.enum(["stdout","stderr"]).optional(),toolName:w.string().optional(),iteration:w.number().int().nonnegative().optional(),agentId:w.string().optional(),conversationId:w.string().optional(),hookEventName:w.string().optional(),inputTokens:w.number().int().nonnegative().optional(),outputTokens:w.number().int().nonnegative().optional(),checkpoint:w.object({ref:w.string(),createdAt:w.number().int().nonnegative(),runCount:w.number().int().positive(),kind:w.enum(["stash","commit"]).optional()}).optional()}).optional()}),WV=w.object({toolCalls:w.number().int().nonnegative(),tokensIn:w.number().int().nonnegative(),tokensOut:w.number().int().nonnegative()}),Uw=w.object({sessionId:w.string().nullable(),status:JV,config:$V,messages:w.array(ZV),rawTranscript:w.string(),error:w.string().nullable(),summary:WV});var Rw=HH;import{Agent as fn,createAgentRuntime as $n}from"@cline/agents";import{getClineEnvironmentConfig as Dw}from"@cline/shared";var Lw=5000,HV={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 Ow(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function jV(f){if(!f||typeof f!=="object")return null;let $=f;if(typeof $.id!=="string"||$.id.length===0)return null;return{id:$.id,name:typeof $.name==="string"&&$.name.length>0?$.name:$.id,description:typeof $.description==="string"?$.description:"",tags:Array.isArray($.tags)?$.tags.filter((J)=>typeof J==="string"):[]}}function _w(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],Q=Array.isArray($.free)?$.free:[],Z=J.map(jV).filter((j)=>j!==null),W=Q.map(jV).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function Tw(f){let $=f.baseUrl?.trim();if($)return $;let J=Dw().apiBaseUrl;try{return(f.providerSettingsManager??new $$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function zw(f,$,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await f($,{signal:Q.signal})}finally{clearTimeout(Z)}}async function Mw(f={}){try{let $=Tw(f),J=f.fetchImpl??fetch,Q=await zw(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??Lw);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=_w(Z);if(W)return W}catch{}return Ow(HV)}import{readFile as Nw}from"node:fs/promises";import qw from"node:path";function yw(f){return f}async function ww(f){let $=qw.resolve(f),J=await Nw($,"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 "${$}": ${W}`)}return Cw(Q,$)}function Cw(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let Q=f.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}import{BUILT_IN_PROVIDER_IDS as YV,createHandler as hw,createHandlerAsync as bw,getProviderCollection as kw,hasProvider as VV,registerAsyncHandler as Iw,registerHandler as xw,registerModel as gw,registerProvider as BV}from"@cline/llms";function XV(f){return f?{...f}:{}}function Sw(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function Ew(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function AV(f){let $=Object.keys(f.collection.models);return{id:f.collection.provider.id,name:f.collection.provider.name,description:f.collection.provider.description,protocol:f.collection.provider.protocol,baseUrl:f.collection.provider.baseUrl,capabilities:f.collection.provider.capabilities,env:f.collection.provider.env,models:$,defaultModel:f.collection.provider.defaultModelId,modelCount:$.length}}class CZ{providers=new Map;register(f){Ew(f.id,f.models);let $=f.defaultModel??f.models[0];if(!$)throw Error(`Provider "${f.id}" must define a default model.`);if(!f.models.includes($))throw Error(`Default model "${$}" is not included in configured models for "${f.id}".`);let J=this.providers.get(f.id);this.providers.set(f.id,{id:f.id,models:new Set([...J?.models??[],...f.models]),defaultModel:$,defaults:{...J?.defaults??{},...XV(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:Sw(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...XV(f.settings)}})}registerModel(f,$){let J=this.providers.get(f);if(!J){this.providers.set(f,{id:f,models:new Set([$]),defaultModel:$,defaults:{}});return}J.models.add($)}createHandlerConfig(f){let $=this.require(f.providerId),J=f.modelId??$.defaultModel;if(!$.models.has(J))throw Error(`Model "${J}" is not configured for provider "${f.providerId}".`);return{providerId:f.providerId,modelId:J,...$.defaults,...f.overrides}}list(){return Array.from(this.providers.values()).map((f)=>({id:f.id,models:Array.from(f.models),defaultModel:f.defaultModel}))}getModels(f){return Array.from(this.require(f).models)}hasProvider(f){return this.providers.has(f)}hasModel(f,$){return this.providers.get(f)?.models.has($)??!1}require(f){let $=this.providers.get(f);if(!$)throw Error(`Provider "${f}" is not configured in this SDK instance.`);return $}}class SZ{configuredProviders=new CZ;constructor(f){this.applyConfig(f)}createHandler(f){return hw(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return bw(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(BV(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)xw(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)Iw(f.collection.provider.id,f.asyncHandlerFactory);this.configuredProviders.register({id:f.collection.provider.id,models:f.exposeModels??Object.keys(f.collection.models),defaultModel:f.defaultModel??f.collection.provider.defaultModelId,defaults:f.defaults})}registerBuiltinProvider(f){let $=f.exposeModels??Object.keys(f.models),J=f.defaultModel??$[0];if(!J)throw Error(`Provider "${f.id}" must define a default model.`);BV({provider:{id:f.id,name:f.name??f.id,description:f.description,protocol:f.protocol,baseUrl:f.baseUrl,defaultModelId:J,client:f.client??"openai-compatible",capabilities:f.capabilities,env:f.env,source:"system"},models:f.models}),this.configuredProviders.register({id:f.id,models:$,defaultModel:J,defaults:{routingProviderId:f.builtinProviderId,...f.defaults??{}}})}registerModel(f){gw(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...YV]}async getBuiltInProviders(){return(await Promise.all(YV.map(($)=>kw($)))).filter(($)=>$!==void 0).map(($)=>AV({collection:$}))}getModels(f){return this.configuredProviders.getModels(f)}isProviderConfigured(f){return this.configuredProviders.hasProvider(f)}isModelConfigured(f,$){return this.configuredProviders.hasModel(f,$)}applyConfig(f){for(let $ of f.providers)this.configuredProviders.registerSelectionConfig($);for(let $ of f.models??[])this.registerModel($);for(let $ of f.customProviders??[])this.registerProvider($);for(let $ of this.configuredProviders.list()){let J=VV($.id),Q=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,Z=typeof Q==="string"&&VV(Q);if(!J&&!Z)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function mw(f){return new SZ(f)}oQ();async function kr(){return Promise.resolve().then(() => (UZ(),xY))}export{PH as writeHubDiscovery,wf as writeGlobalSettings,GH as withHubStartupLock,lf as verifyHubConnection,X2 as updateMcpServerOAuthState,sY as updateLocalProvider,Sy as uninstallPlugin,QZ as truncateNotificationBody,m6 as toggleDisabledTool,nJ as toTeamProgressLifecycleEvent,Af as toProviderConfig,NL as toHubHealthUrl,_Q as toHookConfigFileName,eJ as summarizeUsageFromMessages,yO as stopLocalHubServerGracefully,Xf as startLocalOAuthServer,FZ as startHubWebSocketServer,qp as startHubServer,vV as startClineDeviceAuth,t5 as splitCoreSessionConfig,kJ as spawnDetachedHubServerWithRetry,HO as spawnDetachedHubServer,TK as setTelemetryOptOutGlobally,j2 as setMcpServerDisabled,xW as setDisabledTools,yK as setDisabledPlugin,MK as setAutoUpdateEnabledGlobally,Ld as sendHubCommand,k1 as saveProviderOAuthCredentials,ay as saveLocalProviderSettings,ey as saveLocalProviderOAuthCredentials,_2 as sanitizeSessionToken,yW as safeParseSettings,$K as safeCreateProviderConfig,_4 as runSubprocessEvent,z4 as runHook,u3 as reviveTeamStateDates,yH as restartLocalHubIfIdleAfterStartupTimeout,xI as resolveWorkspaceHubOwnerContext,F5 as resolveWorkflowsConfigSearchPaths,P5 as resolveSkillsConfigSearchPaths,D0 as resolveSharedHubOwnerContext,aM as resolveSessionBackend,G5 as resolveRulesConfigSearchPaths,h6 as resolveProviderConfig,OB as resolveProviderApiKeyFromSettings,d1 as resolvePluginSkillDirectoriesFromPaths,$5 as resolvePluginConfigSearchPaths,xf as resolveMcpServerRegistrations,$w as resolveLocalClineAuthToken,uN as resolveHubUrl,q$ as resolveHubOwnerContext,df as resolveHubEndpointOptions,F1 as resolveHubBuildId,LQ as resolveHooksConfigSearchPaths,Yf as resolveDisabledToolNames,y8 as resolveDisabledPluginPaths,b0 as resolveDefaultMcpSettingsPath,bJ as resolveDefaultHubPort,xL as resolveDefaultHubPathname,IL as resolveDefaultHubHost,r3 as resolveCoreSelectedToolIds,m9 as resolveCompatibleLocalHubUrl,yI as resolveClineDir,h9 as resolveClineDataDir,x8 as resolveAndLoadAgentPlugins,u1 as resolveAgentPluginPaths,b9 as requestHubShutdown,Xy as requestDesktopToolApproval,U1 as rememberRecoverableLocalHubUrl,vY as registerRemoteConfigSessionBlobUpload,A2 as registerMcpServersFromSettingsFile,er as registerDisposable,ty as refreshProviderModelsFromSource,sZ as refreshOpenAICodexToken,WW as refreshOcaToken,aZ as refreshClineToken,kQ as readSessionCheckpointHistory,oq as readRemoteConfigSessionBlobUploadMetadata,P0 as readHubDiscovery,T0 as readGlobalSettings,uf as probeHubServer,Dd as probeHubConnection,o7 as prewarmFileIndex,RH as prewarmDetachedHubServer,$y as prepareRemoteConfigCoreIntegration,K5 as parseWorkflowConfigFromMarkdown,or as parseUserCommandEnvelope,V5 as parseSkillConfigFromMarkdown,qW as parseSettings,B5 as parseRuleConfigFromMarkdown,T4 as parseHookEventPayload,i9 as parseConfiguredAgentConfig,_$ as normalizeWorkspacePath,sr as normalizeUserInput,tr as normalizeSdkError,R0 as normalizeRuntimeCapabilities,T8 as normalizeProviderId,sy as normalizeOAuthProvider,R1 as normalizeHubWebSocketUrl,ar as noopBasicLogger,EQ as migrateLegacyProviderSettings,l8 as mergeRulesForSystemPrompt,l2 as mergeAgentHooks,R9 as makeTeamTaskSubSessionId,wJ as makeSubSessionId,U6 as loginOpenAICodex,T6 as loginOcaOAuth,oy as loginLocalProvider,G6 as loginClineOAuth,N6 as loginAndSaveProviderOAuthCredentials,fw as loginAndSaveLocalProviderOAuthCredentials,kr as loadOpenTelemetryAdapter,W2 as loadMcpSettingsFile,ww as loadLlmsConfigFromFile,lJ as loadConfiguredAgentConfigs,v1 as loadAgentPluginsFromPathsWithDiagnostics,oW as loadAgentPluginsFromPaths,a6 as loadAgentPluginFromPath,VL as listSessionHistoryFromBackend,Dj as listPluginToolsWithDiagnostics,a5 as listPluginTools,p5 as listMcpServerOAuthStatuses,iy as listLocalProviders,_1 as listHookConfigFiles,NK as isToolDisabledGlobally,g6 as isTelemetryOptedOutGlobally,O$ as isSessionNotFoundError,U7 as isRuleEnabled,qK as isPluginDisabledGlobally,b1 as isOAuthProvider,OO as isHubReconnectableTransportError,NH as isHubCommandTimeoutError,SI as isDiscoveryFilePresent,IZ as isClineAccountActionRequest,sB as isBuiltInProviderId,zK as isAutoUpdateEnabledGlobally,Nf as identifyAccount,D$ as hasMcpSettingsFile,R6 as getValidOpenAICodexCredentials,z6 as getValidOcaCredentials,F6 as getValidClineCredentials,q6 as getProviderOAuthCredentialsFromSettings,Xw as getProviderConfigFields,FW as getProviderConfig,LB as getProviderAuthStorageId,B0 as getProviderAuthHandler,HW as getPersistedProviderApiKey,H2 as getMcpServerOAuthState,ny as getLocalProviderModels,_8 as getLiveModelsCatalog,P$ as getFileIndex,yT as getCurrentContextSize,v5 as getCoreHeadlessToolNames,p3 as getCoreDefaultEnabledToolIds,$2 as getCoreBuiltinToolCatalog,i3 as getCoreAcpToolNames,mr as getClineDefaultSystemPrompt,$9 as generateWorkspaceInfoWithDiagnostics,qJ as generateWorkspaceInfo,d8 as formatRulesForSystemPrompt,_B as formatProviderOAuthApiKey,nr as formatDisplayUserInput,c6 as filterExtensionToolRegistrations,o$ as filterDisabledTools,v6 as filterDisabledPluginPaths,Mw as fetchClineRecommendedModels,xZ as executeClineAccountAction,IY as ensureHubWebSocketServer,yp as ensureHubServer,nI as ensureDetachedHubServer,XA as ensureCustomProvidersLoaded,S2 as ensureCompatibleLocalHubUrl,WJ as enrichPromptWithMentions,ir as emptyWorkspaceManifest,T1 as emptyStoredProviderSettings,J5 as discoverPluginModulePaths,D9 as deriveSubsessionStatus,oY as deleteLocalProvider,yw as defineLlmsConfig,D5 as createWorkflowsConfigDefinition,B1 as createUserInstructionConfigService,J3 as createToolPoliciesWithPreset,rr as createTool,NA as createTeamName,vA as createSubprocessHooks,V1 as createSpawnAgentTool,U5 as createSkillsConfigDefinition,O4 as createSessionHost,O4 as createRuntimeHost,R5 as createRulesConfigDefinition,fy as createRemoteConfigSessionMessagesArtifactUploader,fK as createProviderConfig,C4 as createOpenTelemetryTelemetryService,Z8 as createOAuthClientCallbacks,_J as createMcpTools,Ed as createLocalHubScheduleRuntimeHandlers,mw as createLlmsSdk,G0 as createInitialAccumulatedUsage,CI as createInMemoryHubOwnerContext,Gf as createHubServerUrl,KH as createHubAuthToken,NQ as createHookConfigFileHooks,W4 as createHookConfigFileExtension,Z4 as createHookAuditHooks,n5 as createDisabledMcpToolPolicy,Uj as createDisabledMcpToolPolicies,A1 as createDelegatedAgentConfigProvider,Y1 as createDelegatedAgent,Q3 as createDefaultToolsWithPreset,j1 as createDefaultTools,LJ as createDefaultMcpServerClientFactory,AJ as createDefaultExecutors,B2 as createCoreSettingsService,pf as createCoreSessionSnapshot,pr as createContributionRegistry,UQ as createContextCompactionPrepareTurn,m$ as createConfiguredTelemetryService,S4 as createConfiguredTelemetryHandle,rJ as createConfiguredAgentTools,lr as createClineTelemetryServiceMetadata,dr as createClineTelemetryServiceConfig,J2 as createBuiltinTools,f2 as createAgentTeamsTools,$n as createAgentRuntime,f4 as createAgentHooksExtension,lA as connectToHub,cV as completeClineDeviceAuth,nB as clearPrivateModelsCatalogCache,iB as clearLiveModelsCatalogCache,$f as clearHubDiscovery,MV as captureWorkspacePathResolved,n4 as captureWorkspaceInitialized,a4 as captureWorkspaceInitError,f6 as captureToolUsage,o4 as captureTokenUsage,s4 as captureTaskRestarted,t4 as captureTaskCreated,j8 as captureTaskCompleted,X8 as captureSubagentExecution,$6 as captureSkillUsed,ur as captureSdkError,NV as captureProviderConfigured,H8 as captureProviderApiError,e4 as captureModeSwitch,Q6 as captureMentionUsed,W6 as captureMentionSearchResults,Z6 as captureMentionFailed,H6 as captureHookDiscovery,zV as captureExtensionActivated,J6 as captureDiffEditFailure,E1 as captureConversationTurnEvent,A6 as captureCompactionSkipped,X6 as captureCompactionExecuted,zf as captureAuthSucceeded,Tf as captureAuthStarted,H$ as captureAuthLoggedOut,Mf as captureAuthFailed,j6 as captureAgentTeamCreated,X$ as captureAgentCreated,J9 as buildWorkspaceMetadata,iJ as buildTeamProgressSummary,vr as buildSdkErrorProperties,gY as buildRemoteConfigSessionBlobUploadMetadata,o1 as buildDelegatedAgentConfig,a9 as buildConfiguredAgentToolName,t9 as buildConfiguredAgentToolDescriptors,PJ as bootstrapAgentTeams,Hj as authorizeMcpServerOAuth,ry as addLocalProvider,A0 as accumulateUsageTotals,H5 as WORKFLOWS_CONFIG_DIRECTORY_NAME,x1 as UnifiedConfigFileWatcher,e0 as ToolPresets,s2 as TelemetryService,w4 as TelemetryLoggerSink,KJ as TEAM_TOOL_NAMES,C8 as SubprocessSandbox,H4 as StoredProviderSettingsSchema,uX as StoredProviderSettingsEntrySchema,r2 as SqliteTeamStore,af as SqliteSessionStore,N1 as SessionVersioningService,i0 as SessionVersioningError,U0 as SessionSource,L$ as SessionNotFoundError,zW as SapSettingsSchema,j5 as SKILLS_CONFIG_DIRECTORY_NAME,I6 as SESSION_STATUSES,K2 as SESSION_NOT_FOUND_ERROR_CODE,fi as SDK_ERROR_TELEMETRY_EVENT,i4 as RpcClineAccountService,gJ as RemoteRuntimeHost,LW as ReasoningSettingsSchema,Y7 as RULES_CONFIG_DIRECTORY_NAME,mY as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,t$ as ProviderSettingsSchema,$$ as ProviderSettingsManager,UW as ProviderProtocolSchema,k6 as ProviderIdSchema,RW as ProviderClientSchema,o2 as OpenTelemetryProvider,MW as OcaSettingsSchema,E6 as OPENAI_COMPATIBLE_PROVIDERS,Ff as NodeHubClient,PZ as NativeHubTransportAdapter,NW as ModelCatalogSettingsSchema,J$ as LocalRuntimeHost,xr as Llms,X4 as InMemoryWorkspaceManager,Y2 as InMemoryMcpManager,iN as HubUIClient,g0 as HubTransportError,rN as HubSessionClient,g4 as HubServerTransport,y4 as HubScheduleService,M4 as HubScheduleCommandService,C$ as HubRuntimeHost,IJ as HubCommandError,gA as HookEventPayloadSchema,xA as HookEventNameSchema,$4 as HookConfigFileName,OQ as HOOK_CONFIG_FILE_EVENT_MAP,hX as HOOKS_CONFIG_DIRECTORY_NAME,q8 as GlobalSettingsSchema,_W as GcpSettingsSchema,fV as FileTeamPersistenceStore,HV as FALLBACK_CLINE_RECOMMENDED_MODELS,K0 as DefaultToolNames,R4 as DefaultRuntimeBuilder,SZ as DefaultLlmsSdk,KW as DEFAULT_MODELS_CATALOG_URL,bL as DEFAULT_HUB_PORT,kL as DEFAULT_HUB_PATHNAME,hL as DEFAULT_HUB_HOST,G1 as CoreSettingsService,tf as CoreSessionService,cr as ContributionRegistry,tQ as ClineCore,r4 as ClineAccountService,Uw as ChatViewStateSchema,WV as ChatSummarySchema,JV as ChatSessionStatusSchema,$V as ChatSessionConfigSchema,ZV as ChatMessageSchema,QV as ChatMessageRoleSchema,x as CORE_TELEMETRY_EVENTS,Rw as CORE_BUILD_VERSION,KZ as BrowserWebSocketHubAdapter,tB as BUILT_IN_PROVIDER_IDS,b6 as BUILT_IN_PROVIDER,TW as AzureSettingsSchema,OW as AwsSettingsSchema,DW as AuthSettingsSchema,I2 as AgentTeamsRuntime,o9 as AgentTeam,fn as Agent,Z1 as ALL_DEFAULT_TOOL_NAMES};