@cline/core 0.0.47-nightly.1781580004 → 0.0.48

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 _A}from"node:module";var RA=Object.defineProperty;var zA=($)=>$;function LA($,J){this[$]=zA.bind(null,J)}var V5=($,J)=>{for(var Q in J)RA($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:LA.bind(J,Q)})};var X$=($,J)=>()=>($&&(J=$($=0)),J);var VW=_A(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as TA}from"@cline/shared";function d($,J,Q){$?.capture({event:J,properties:Q})}function D4($){if(!$)return;return $.substring(0,MA)}function qA($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function PA($){return typeof $==="string"?$:$.message}function KW($,J){return $.some((Q)=>J.has(Q.trim().toLowerCase()))}function NA($){d($,k.CLIENT.EXTENSION_ACTIVATED)}function A5($,J){let Q=[...J.vcs_types],Z={root_count:J.root_count,vcs_types:Q,is_multi_root:J.root_count>1,has_git:KW(Q,new Set(["git"])),has_mercurial:KW(Q,new Set(["mercurial","hg"]))};if(J.init_duration_ms!==void 0)Z.init_duration_ms=J.init_duration_ms;if(J.feature_flag_enabled!==void 0)Z.feature_flag_enabled=J.feature_flag_enabled;if(J.is_remote_workspace!==void 0)Z.is_remote_workspace=J.is_remote_workspace;d($,k.WORKSPACE.INITIALIZED,Z)}function K5($,J,Q){d($,k.WORKSPACE.INIT_ERROR,{error_type:qA(J),error_message:D4(PA(J)),fallback_to_single_root:Q.fallback_to_single_root,workspace_count:Q.workspace_count??0})}function wA($,J){d($,k.WORKSPACE.PATH_RESOLVED,{...J})}function M1($,J){d($,k.USER.AUTH_STARTED,{provider:J})}function q1($,J){d($,k.USER.AUTH_SUCCEEDED,{provider:J})}function P1($,J,Q){d($,k.USER.AUTH_FAILED,{provider:J,errorMessage:D4(Q)})}function Y$($,J,Q){d($,k.USER.AUTH_LOGGED_OUT,{provider:J,reason:Q})}function SA($,J){d($,k.USER.PROVIDER_CONFIGURED,{provider:J})}function GW($,J){$?.captureRequired(k.USER.TELEMETRY_OPT_OUT,J)}function N1($,J){let Q=J.id?.trim();if(Q)$?.setDistinctId(Q);$?.updateCommonProperties({account_id:J.id,account_email:J.email,provider:J.provider,organization_id:J.organizationId,organization_name:J.organizationName,member_id:J.memberId})}function G5($,J){d($,k.TASK.CREATED,J)}function F5($,J){d($,k.TASK.RESTARTED,J)}function U4($,J){d($,k.TASK.COMPLETED,J)}function g2($,J){d($,k.TASK.CONVERSATION_TURN,{...J,timestamp:new Date().toISOString()})}function D5($,J){d($,k.TASK.TOKEN_USAGE,J)}function U5($,J,Q){d($,k.TASK.MODE_SWITCH,{ulid:J,mode:Q})}function R5($,J){d($,k.TASK.TOOL_USED,J)}function z5($,J){d($,k.TASK.SKILL_USED,J)}function L5($,J){d($,k.TASK.DIFF_EDIT_FAILED,J)}function R4($,J){d($,k.TASK.PROVIDER_API_ERROR,{...J,errorMessage:D4(J.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function FW($,J){d($,k.SDK.TOOL_TIMEOUT,CA(J))}function CA($){let J={};for(let[Q,Z]of Object.entries($))if(Z!==void 0)J[Q]=Z;return J}function _5($,J,Q){d($,k.TASK.MENTION_USED,{mentionType:J,contentLength:Q,timestamp:new Date().toISOString()})}function O5($,J,Q,Z){d($,k.TASK.MENTION_FAILED,{mentionType:J,errorType:Q,errorMessage:D4(Z),timestamp:new Date().toISOString()})}function T5($,J,Q,Z,W){d($,k.TASK.MENTION_SEARCH_RESULTS,{queryLength:J.length,resultCount:Q,searchType:Z,isEmpty:W,timestamp:new Date().toISOString()})}function V$($,J){d($,k.TASK.AGENT_CREATED,{...J,timestamp:new Date().toISOString()})}function M5($,J){d($,k.TASK.AGENT_TEAM_CREATED,{...J,timestamp:new Date().toISOString()})}function z4($,J){d($,J.event==="ended"?k.TASK.SUBAGENT_COMPLETED:k.TASK.SUBAGENT_STARTED,{...J,timestamp:new Date().toISOString()})}function q5($,J,Q,Z){d($,k.HOOKS.DISCOVERY_COMPLETED,{hookName:J,globalCount:Q,workspaceCount:Z,totalCount:Q+Z,timestamp:new Date().toISOString()})}function P5($,J){d($,k.TASK.COMPACTION_EXECUTED,{...J,timestamp:new Date().toISOString()})}function N5($,J){d($,k.TASK.COMPACTION_SKIPPED,{...J,timestamp:new Date().toISOString()})}var MA=500,k;var F0=X$(()=>{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:TA,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as UG,readFileSync as RG,statSync as zG,writeFileSync as LG}from"node:fs";import{dirname as _G}from"node:path";import{resolveGlobalSettingsPath as B3}from"@cline/shared/storage";import{z as $2}from"zod";function x4(){return m4.parse({})}function OG(){g4=void 0}function TG($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function MG($){let J;try{J=RG($,"utf8")}catch{return x4()}try{let Q=m4.safeParse(JSON.parse(J));return Q.success?Q.data:x4()}catch{return x4()}}function qG(){let $=B3(),J=zG($,{throwIfNoEntry:!1}),Q=J?.mtimeMs??0,Z=J?.size??0,W=g4;if(W&&W.path===$&&W.mtimeMs===Q&&W.size===Z)return W;let j=TG(J?MG($):x4());return g4={path:$,mtimeMs:Q,size:Z,value:j},g4}function M0(){return qG().value}function C1($,J={}){let Q=B3(),Z=M0();UG(_G(Q),{recursive:!0});let W=m4.parse($);if(!Z.telemetryOptOut&&W.telemetryOptOut)GW(J.telemetry);LG(Q,`${JSON.stringify(W,null,2)}
2
- `,"utf8"),OG()}function QQ(){return M0().telemetryOptOut}function PG($,J={}){C1({...M0(),telemetryOptOut:$},J)}function NG(){return M0().autoUpdateEnabled}function wG($,J={}){C1({...M0(),autoUpdateEnabled:$},J)}function H1($){return new Set($??M0().disabledTools??[])}function v4($){return new Set($??M0().disabledPlugins??[])}function SG($){return H1().has($)}function ZQ($){let J=M0(),Q=new Set(J.disabledTools??[]),Z=Q.has($);if(Z)Q.delete($);else Q.add($);return C1({...J,disabledTools:[...Q]}),!Z}function A3($,J){let Q=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Q.length===0)return;let Z=M0(),W=H1(Z.disabledTools);for(let j of Q)if(J)W.add(j);else W.delete(j);C1({...Z,disabledTools:[...W]})}function K3($,J){return A3([$],J),J}function CG($){return v4().has($)}function yG($,J){let Q=$.trim();if(!Q)return;let Z=M0(),W=v4(Z.disabledPlugins);if(J)W.add(Q);else W.delete(Q);C1({...Z,disabledPlugins:[...W]})}function WQ($,J){let Q=v4(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z))}function y1($,J){let Q=H1(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z.name))}function jQ($,J){if(!$||$.length===0)return $;let Q=H1(J);if(Q.size===0)return $;return $.map((Z)=>{if(!Z.setup)return Z;return{...Z,setup:(W,j)=>Z.setup?.({...W,registerTool:(f)=>{if(!Q.has(f.name))W.registerTool(f)}},j)}})}var H3,m4,g4;var p0=X$(()=>{F0();H3=$2.preprocess(($)=>Array.isArray($)?$.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter(Boolean):void 0,$2.array($2.string()).optional()).transform(($)=>{if(!$)return;let J=[...new Set($)].sort((Q,Z)=>Q.localeCompare(Z));return J.length>0?J:void 0}),m4=$2.object({telemetryOptOut:$2.boolean().default(!1).catch(!1),autoUpdateEnabled:$2.boolean().default(!0).catch(!0),disabledTools:H3.optional(),disabledPlugins:H3.optional()}).strip().transform(($)=>{let J={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)J.disabledTools=$.disabledTools;if($.disabledPlugins?.length)J.disabledPlugins=$.disabledPlugins;return J})});var sj={};V5(sj,{normalizeUserMessage:()=>nU,buildInitialUserContent:()=>iU});async function iU($,J,Q,Z){let W=aU(J),j=await oU(Q,Z);if(W.length===0&&!j)return $;let f=[{type:"text",text:$},...W];if(j)f.push(...j);return f}function nU($){if($==null)return"";if(typeof $==="string")return $;let J=$.content;if(typeof J==="string")return J;if(!Array.isArray(J))return"";let Q=[];for(let Z of J)if(Z&&typeof Z==="object"&&Z.type==="text"){let W=Z.text;if(typeof W==="string")Q.push(W)}return Q.join(`
3
- `)}function aU($){if(!$||$.length===0)return[];let J=[];for(let Q of $){let Z=sU(Q);if(Z)J.push(Z)}return J}function sU($){let J=$.trim();if(!J)return;let Q=J.match(/^data:([^;,]+);base64,(.+)$/);if(Q){let Z=Q[1],W=Q[2];if(!Z||!W)return;return{type:"image",mediaType:Z,data:W}}return{type:"image",mediaType:"image/png",data:J}}async function oU($,J){if(!$||$.length===0)return;let Q=J??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Z=await Promise.all($.map(async(W)=>{let j=W.replace(/\\/g,"/");try{let f=await Q(W);return{type:"file",path:j,content:f}}catch(f){let X=f instanceof Error?f.message:String(f);return{type:"file",path:j,content:`Error fetching content: ${X}`}}}));if(Z.length===0)return;return Z}var vf={};V5(vf,{updateMcpServerOAuthState:()=>D8,setMcpServerDisabled:()=>G8,resolveMcpServerRegistrations:()=>m1,resolveDefaultMcpSettingsPath:()=>H0,registerMcpServersFromSettingsFile:()=>U8,normalizeMcpServerOAuthState:()=>R2,loadMcpSettingsFile:()=>K8,listMcpServerOAuthStatuses:()=>F9,hasMcpSettingsFile:()=>L$,getMcpServerOAuthState:()=>F8});import{existsSync as cR,mkdirSync as hf,readFileSync as K9,writeFileSync as kf}from"node:fs";import{dirname as If}from"node:path";import{resolveMcpSettingsPath as uR}from"@cline/shared/storage";import{z as w}from"zod";function A9($){if(!$)return;if($==="http")return"streamableHttp";return $}function H0(){return uR()}function eR($){let J=K9($,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse MCP settings JSON at "${$}": ${W}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Q}function mf($,J){if(!Object.hasOwn($,J))return;let Q=$[J];if(!Q||typeof Q!=="object"||Array.isArray(Q))return;return Q}function $z($,J,Q){Object.defineProperty($,J,{value:Q,enumerable:!0,configurable:!0,writable:!0})}function K8($={}){let J=$.filePath??H0(),Q=K9(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${J}": ${f}`)}let W=tR.safeParse(Z);if(!W.success){let j=W.error.issues.map((f)=>{let X=f.path.join(".");return X?`${X}: ${f.message}`:f.message}).join("; ");throw Error(`Invalid MCP settings at "${J}": ${j}`)}return W.data}function Jz($){let J=K9($,"utf8"),Q;try{Q=JSON.parse(J)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${$}": ${f}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object`);let Z=Q,W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Z}function R2($){if(!$)return;let J={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(J).length>0?J:void 0}function Qz($){if($===void 0)return;let J=G9.safeParse($);if(!J.success)return;return R2(J.data)}function L$($={}){let J=$.filePath??H0();return cR(J)}function m1($={}){let J=K8($);return Object.entries(J.mcpServers).map(([Q,Z])=>({name:Q,transport:Z.transport,disabled:Z.disabled,metadata:Z.metadata,oauth:Z.oauth}))}function G8($){let J=$.filePath??H0(),Q=$.name.trim();if(!Q)throw Error("MCP server settings toggle requires a server name.");let Z=eR(J),W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${J}": mcpServers must be an object.`);let j={...W},f=mf(j,Q);if(!f)throw Error(`Unknown MCP server: ${Q}`);let X={...f};if($.disabled)X.disabled=!0;else delete X.disabled;$z(j,Q,X),hf(If(J),{recursive:!0}),kf(J,`${JSON.stringify({...Z,mcpServers:j},null,2)}
4
- `)}function F8($,J={}){let Q=K8(J);if(!Object.hasOwn(Q.mcpServers,$))return;return R2(Q.mcpServers[$]?.oauth)}function D8($,J,Q={}){let Z=Q.filePath??H0(),W=Jz(Z),j=W.mcpServers,f=mf(j,$);if(!f)throw Error(`Unknown MCP server: ${$}`);let X=Qz(f.oauth)??{},Y=R2(J(X));if(Y)f.oauth=Y;else delete f.oauth;return hf(If(Z),{recursive:!0}),kf(Z,`${JSON.stringify(W,null,2)}
5
- `,"utf8"),Y??{}}function F9($={}){return m1($).map((Q)=>{let Z=Q.transport.type!=="stdio",W=Q.oauth?.tokens?.access_token;return{serverName:Q.name,oauthSupported:Z,oauthConfigured:Z&&typeof W==="string"&&W.trim().length>0,lastError:Q.oauth?.lastError,lastAuthenticatedAt:Q.oauth?.lastAuthenticatedAt}}).sort((Q,Z)=>Q.serverName.localeCompare(Z.serverName))}async function U8($,J={}){let Q=m1(J);for(let Z of Q)await $.registerServer(Z);return Q}var A8,xf,G9,dR,lR,pR,rR,iR,nR,gf,aR,sR,oR,tR;var C6=X$(()=>{A8=w.record(w.string(),w.string()),xf=w.record(w.string(),w.unknown()),G9=w.object({clientInformation:w.record(w.string(),w.unknown()).optional(),tokens:w.record(w.string(),w.unknown()).optional(),codeVerifier:w.string().optional(),discoveryState:w.record(w.string(),w.unknown()).optional(),redirectUrl:w.string().url().optional(),lastError:w.string().optional(),lastAuthenticatedAt:w.number().int().positive().optional()}).strip(),dR=w.object({type:w.literal("stdio"),command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:A8.optional()}),lR=w.object({type:w.literal("sse"),url:w.string().url(),headers:A8.optional()}),pR=w.object({type:w.literal("streamableHttp"),url:w.string().url(),headers:A8.optional()}),rR=w.discriminatedUnion("type",[dR,lR,pR]),iR=w.object({transport:rR,disabled:w.boolean().optional(),metadata:xf.optional(),oauth:G9.optional()}),nR=w.enum(["stdio","sse","http","streamableHttp"]).optional(),gf=w.object({type:w.enum(["stdio","sse","streamableHttp"]).optional(),transportType:nR,disabled:w.boolean().optional(),metadata:xf.optional(),oauth:G9.optional()});aR=gf.extend({command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:A8.optional()}).superRefine(($,J)=>{let Q=$.type??A9($.transportType);if(Q&&Q!=="stdio")J.addIssue({code:w.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),sR=gf.extend({url:w.string().url(),headers:A8.optional()}).superRefine(($,J)=>{let Q=$.type??A9($.transportType)??"sse";if(Q!=="sse"&&Q!=="streamableHttp")J.addIssue({code:w.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??A9($.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}}),oR=w.union([iR,aR,sR]),tR=w.object({mcpServers:w.record(w.string(),oR)}).passthrough()});import{existsSync as CT,mkdirSync as yT,readFileSync as ET,writeFileSync as bT}from"node:fs";import{resolve as hT}from"node:path";import{resolveSessionDataDir as kT}from"@cline/shared/storage";import{nanoid as IT}from"nanoid";import*as xT from"node-machine-id";function g0($){let J=$?.trim();if(J)return J;let Q=vT();if(Q)return Q;return cT()}function mT(){let $=xT;return $.machineIdSync??$.default?.machineIdSync}function vT(){try{let $=mT();if(!$)return;return $().trim()||void 0}catch{return}}function cT(){let $=kT(),J=hT($,gT);try{if(CT(J)){let Z=ET(J,"utf8").trim();if(Z.length>0)return Z}}catch{}let Q=`cl-${IT()}`;try{yT($,{recursive:!0}),bT(J,Q,"utf8")}catch{}return Q}var gT="machine-id";var q2=()=>{};class X4{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,J){if(!this.isEnabled())return;this.emitLog($,J,!1)}emitRequired($,J){this.emitLog($,J,!0)}recordCounter($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Z?{description:Z}:void 0),this.counters.set($,j);j.add(J,this.flattenProperties(this.buildAttributes(Q)))}recordHistogram($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Z?{description:Z}:void 0),this.histograms.set($,j);j.record(J,this.flattenProperties(this.buildAttributes(Q)))}recordGauge($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.buildAttributes(Q),f=JSON.stringify(j),X=this.gaugeValues.get($);if(J===null){if(X){if(X.delete(f),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let Y=X;if(!Y)Y=new Map,this.gaugeValues.set($,Y);if(!this.gauges.has($)){let V=this.meter.createObservableGauge($,Z?{description:Z}:void 0);V.addCallback((H)=>{for(let B of this.snapshotGaugeSeries($))H.observe(B.value,this.flattenProperties(B.attributes))}),this.gauges.set($,V)}Y.set(f,{value:J,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,J,Q){if(!this.logger)return;let Z=this.flattenProperties(this.buildAttributes(J,Q));this.logger.emit({severityText:"INFO",body:$,attributes:Z})}buildAttributes($,J=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...J?{_required:!0}:{}}}snapshotGaugeSeries($){let J=this.gaugeValues.get($);if(!J)return[];return Array.from(J.values(),(Q)=>({value:Q.value,attributes:Q.attributes?{...Q.attributes}:void 0}))}flattenProperties($,J="",Q=new WeakSet,Z=0){if(!$)return{};let W={},j=100,f=10;for(let[X,Y]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let V=J?`${J}.${X}`:X;if(Y===null||Y===void 0){W[V]=String(Y);continue}if(Array.isArray(Y)){let H=Y.length>j?Y.slice(0,j):Y;try{W[V]=JSON.stringify(H)}catch{W[V]="[UnserializableArray]"}if(Y.length>j)W[`${V}_truncated`]=!0,W[`${V}_original_length`]=Y.length;continue}if(typeof Y==="object"){if(Y instanceof Date){W[V]=Y.toISOString();continue}if(Y instanceof Error){W[V]=Y.message;continue}if(Q.has(Y)){W[V]="[Circular]";continue}if(Z>=f){W[V]="[MaxDepthExceeded]";continue}Q.add(Y),Object.assign(W,this.flattenProperties(Y,V,Q,Z+1));continue}if($w(Y)){W[V]=Y;continue}try{W[V]=JSON.stringify(Y)}catch{W[V]=String(Y)}}return W}}function $w($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class dJ{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,J){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:J})}emitRequired($,J){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:J})}recordCounter($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordHistogram($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordGauge($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:J,attributes:Q,description:Z,required:W===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class Y4{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new dJ({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let J=this.buildAttributes($.properties);for(let Q of this.adapters)Q.emit($.event,J)}captureRequired($,J){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.emitRequired($,Q)}recordCounter($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordCounter($,J,j,Z,W)}recordHistogram($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordHistogram($,J,j,Z,W)}recordGauge($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordGauge($,J,j,Z,W)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var T7=()=>{};import{metrics as Jw,trace as Qw}from"@opentelemetry/api";import{logs as Zw}from"@opentelemetry/api-logs";import{OTLPLogExporter as Ww}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as jw}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as fw}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as Xw}from"@opentelemetry/resources";import{BatchLogRecordProcessor as Yw,ConsoleLogRecordExporter as Vw,LoggerProvider as Hw}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as Bw,MeterProvider as Aw,PeriodicExportingMetricReader as kH}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as Kw,ConsoleSpanExporter as Gw,SimpleSpanProcessor as Fw}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Dw}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as Uw,ATTR_SERVICE_VERSION as Rw}from"@opentelemetry/semantic-conventions";class IH{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,J){this.resolveProperties(J)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class V4{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let J=Xw({[Uw]:$.serviceName??"cline",...$.serviceVersion?{[Rw]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(J),this.loggerProvider=this.createLoggerProvider(J),this.tracerProvider=this.createTracerProvider(J),this.meterProvider)Jw.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)Zw.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",J){return Qw.getTracer($,J??this.options.serviceVersion)}createAdapter($){return new X4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let J=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new Y4({...$,adapters:[J],distinctId:g0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let J=M7(this.options.metricsExporter);if(J.length===0)return null;let Q=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Z=Math.min(30000,Math.floor(Q*0.8)),W=J.map((j)=>_w(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Q,timeout:Z})).filter((j)=>j!==null);if(W.length===0)return null;return new Aw({resource:$,readers:W})}createTracerProvider($){let J=M7(this.options.tracesExporter);if(J.length===0)return null;let Q=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Z=this.options.otlpTracesHeaders??this.options.otlpHeaders,W=[];for(let j of J){let f=Lw(j,{endpoint:Q,headers:Z,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(f)W.push(f)}if(W.length===0)return null;return new Dw({resource:$,spanProcessors:W})}createLoggerProvider($){let J=M7(this.options.logsExporter);if(J.length===0)return null;let Q=J.map((Z)=>{let W=zw(Z,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!W)return null;return new Yw(W,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Z)=>Z!==null);if(Q.length===0)return null;return new Hw({resource:$,processors:Q})}}function lJ($){let J=new V4($),Q=J.createTelemetryService($);return Q.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:J,telemetry:Q}}function c$($){if(QQ())return{telemetry:new IH($)};if($.enabled!==!0)return{telemetry:new Y4({...$,distinctId:g0($.distinctId)})};return lJ($)}function pJ($){let{telemetry:J,provider:Q}=c$($);return{telemetry:J,provider:Q,flush:async()=>{let j=Q;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([J.dispose(),Q?.dispose()])}}}function M7($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Q)=>Q.trim()).filter((Q)=>Q==="console"||Q==="otlp")}function zw($,J){if($==="console")return new Vw;if(!J.endpoint)return null;let Q=q7(J.endpoint,"/v1/logs");return new Ww({url:Q,headers:J.headers})}function Lw($,J){if($==="console")return new Fw(new Gw);if(!J.endpoint)return null;let Q=q7(J.endpoint,"/v1/traces");return new Kw(new fw({url:Q,headers:J.headers}))}function _w($,J){if($==="console")return new kH({exporter:new Bw,exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout});if(!J.endpoint)return null;let Q=q7(J.endpoint,"/v1/metrics");return new kH({exporter:new jw({url:Q,headers:J.headers}),exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout})}function q7($,J){let Q=new URL($),Z=Q.pathname.endsWith("/")?Q.pathname.slice(0,-1):Q.pathname;return Q.pathname=Z.endsWith(J)?Z:`${Z}${J}`,Q.toString()}var rJ=X$(()=>{p0();q2();T7()});var xB={};V5(xB,{resolveCoreDistinctId:()=>g0,createOpenTelemetryTelemetryService:()=>lJ,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>pJ,OpenTelemetryProvider:()=>V4,OpenTelemetryAdapter:()=>X4});var eJ=X$(()=>{q2();rJ()});import*as La from"@cline/llms";import{buildClineSystemPrompt as Oa,buildSdkErrorProperties as Ta,ContributionRegistry as Ma,captureSdkError as qa,createClineTelemetryServiceConfig as Pa,createClineTelemetryServiceMetadata as Na,createContributionRegistry as wa,createTool as Sa,emptyWorkspaceManifest as Ca,FEATURE_FLAGS as ya,FeatureFlagDefaultValue as Ea,formatDisplayUserInput as ba,noopBasicLogger as ha,normalizeSdkError as ka,normalizeUserInput as Ia,parseUserCommandEnvelope as xa,registerDisposable as ga,SDK_ERROR_TELEMETRY_EVENT as ma}from"@cline/shared";export*from"@cline/shared/storage";function OA($){if(typeof $!=="object"||$===null||!("error"in $))return;let J=$.error;return typeof J==="string"&&J.trim()?J:void 0}function HW($,J,Q){let Z=OA(Q);if(Z)return Z;let W=J.trim();if(W){let j=W.length>200?`${W.slice(0,200)}...`:W;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class H5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let J=$.apiBaseUrl.trim();if(!J)throw Error("apiBaseUrl is required");this.apiBaseUrl=J,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let J=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(J)}/balance`)}async fetchUsageTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/usages`)).items??[]}async fetchPaymentTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}`)}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}/balance`)}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");let Q=await this.resolveOrganizationMemberId(J,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(J)}/members/${encodeURIComponent(Q)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let J=$?.trim();if(J)return J;let Z=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Z)return Z;let W=await this.fetchMe();if(!W.id?.trim())throw Error("Unable to resolve current user id");return W.id}async resolveOrganizationMemberId($,J){let Q=J?.trim();if(Q)return Q;let W=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(W)return W;let f=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!f?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return f}async request($,J){let Q=(await this.getAuthTokenFn())?.trim();if(!Q)throw Error("No Cline account auth token found");let Z=this.getHeadersFn?await this.getHeadersFn():{},W=new AbortController,j=setTimeout(()=>W.abort(),this.requestTimeoutMs);try{let f=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:J?.method??"GET",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",...Z??{}},body:J?.body!==void 0?JSON.stringify(J.body):void 0,signal:W.signal});if(f.status===204||J?.expectNoContent){if(!f.ok)throw Error(`Cline account request failed with status ${f.status}`);return}let X=await f.text(),Y;if(X.trim())try{Y=JSON.parse(X)}catch{if(!f.ok)throw Error(HW(f.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!f.ok)throw Error(HW(f.status,X,Y));if(typeof Y==="object"&&Y!==null){let V=Y;if(typeof V.success==="boolean"){if(!V.success)throw Error(V.error||"Cline account request failed");if(V.data!==void 0)return V.data}}if(Y===void 0||Y===null)throw Error("Cline account response payload was empty");return Y}finally{clearTimeout(j)}}}function BW($){return $.action==="clineAccount"}async function AW($,J){switch($.operation){case"fetchMe":return J.fetchMe();case"fetchBalance":return J.fetchBalance($.userId);case"fetchUsageTransactions":return J.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return J.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return J.fetchUserOrganizations();case"fetchOrganizationBalance":return J.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return J.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await J.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return J.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class B5{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:J})}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:J,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}function F4($){return{onAuth:({url:J,instructions:Q})=>{if($.onOutput?.(Q??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(J)).catch((Z)=>{$.onOpenUrlError?.({url:J,error:Z})})}catch(Z){$.onOpenUrlError?.({url:J,error:Z})}$.onOutput?.(J)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}F0();import{getClineEnvironmentConfig as w5}from"@cline/shared";function yA(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function Y1($){let J=await import("node:http"),Q=$.host??"127.0.0.1",Z=$.timeoutMs??300000,W=$.successHtml??EA,j=yA(),f=!1,X=null,Y=null,V=null,H=(K)=>{if(f)return;f=!0,j.resolve(K)},B=()=>{if(X)clearTimeout(X),X=null;let K=V;if(V=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:K})).catch(()=>{})},A=async()=>{return X=setTimeout(()=>{B(),H(null)},Z),j.promise};for(let K of $.ports){let G=J.createServer((D,U)=>{try{let F=new URL(D.url||"",`http://${Q}:${K}`);if(F.pathname!==$.callbackPath){U.statusCode=404,U.end("Not found");return}let O={url:F,code:F.searchParams.get("code")??void 0,state:F.searchParams.get("state")??void 0,provider:F.searchParams.get("provider")??void 0,error:F.searchParams.get("error")??void 0};if(O.error){U.statusCode=400,U.end(`Authentication failed: ${O.error}`),B(),H(O);return}if(!O.code){U.statusCode=400,U.end("Missing authorization code");return}if($.expectedState&&O.state!==$.expectedState){U.statusCode=400,U.end("State mismatch");return}U.statusCode=200,U.setHeader("Content-Type","text/html; charset=utf-8"),U.end(W),B(),H(O)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((D)=>{let U=(F)=>{G.off("error",U),D({bound:!1,error:F})};G.once("error",U),G.listen(K,Q,()=>{G.off("error",U),Y=G,D({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw B(),R.error}if(R.bound){V=K;let D=`http://${Q}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:K,callbackUrl:D})).catch(()=>{});return{callbackUrl:D,waitForCallback:A,cancelWait:()=>{B(),H(null)},close:()=>{B(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var EA=`<!DOCTYPE html>
1
+ import{createRequire as OA}from"node:module";var zA=Object.defineProperty;var LA=($)=>$;function _A($,J){this[$]=LA.bind(null,J)}var V5=($,J)=>{for(var Q in J)zA($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:_A.bind(J,Q)})};var X$=($,J)=>()=>($&&(J=$($=0)),J);var HW=OA(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as MA}from"@cline/shared";function d($,J,Q){$?.capture({event:J,properties:Q})}function D4($){if(!$)return;return $.substring(0,qA)}function PA($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function NA($){return typeof $==="string"?$:$.message}function GW($,J){return $.some((Q)=>J.has(Q.trim().toLowerCase()))}function wA($){d($,k.CLIENT.EXTENSION_ACTIVATED)}function A5($,J){let Q=[...J.vcs_types],Z={root_count:J.root_count,vcs_types:Q,is_multi_root:J.root_count>1,has_git:GW(Q,new Set(["git"])),has_mercurial:GW(Q,new Set(["mercurial","hg"]))};if(J.init_duration_ms!==void 0)Z.init_duration_ms=J.init_duration_ms;if(J.feature_flag_enabled!==void 0)Z.feature_flag_enabled=J.feature_flag_enabled;if(J.is_remote_workspace!==void 0)Z.is_remote_workspace=J.is_remote_workspace;d($,k.WORKSPACE.INITIALIZED,Z)}function K5($,J,Q){d($,k.WORKSPACE.INIT_ERROR,{error_type:PA(J),error_message:D4(NA(J)),fallback_to_single_root:Q.fallback_to_single_root,workspace_count:Q.workspace_count??0})}function SA($,J){d($,k.WORKSPACE.PATH_RESOLVED,{...J})}function M1($,J){d($,k.USER.AUTH_STARTED,{provider:J})}function q1($,J){d($,k.USER.AUTH_SUCCEEDED,{provider:J})}function P1($,J,Q){d($,k.USER.AUTH_FAILED,{provider:J,errorMessage:D4(Q)})}function Y$($,J,Q){d($,k.USER.AUTH_LOGGED_OUT,{provider:J,reason:Q})}function CA($,J){d($,k.USER.PROVIDER_CONFIGURED,{provider:J})}function FW($,J){$?.captureRequired(k.USER.TELEMETRY_OPT_OUT,J)}function N1($,J){let Q=J.id?.trim();if(Q)$?.setDistinctId(Q);$?.updateCommonProperties({account_id:J.id,account_email:J.email,provider:J.provider,organization_id:J.organizationId,organization_name:J.organizationName,member_id:J.memberId})}function G5($,J){d($,k.TASK.CREATED,J)}function F5($,J){d($,k.TASK.RESTARTED,J)}function U4($,J){d($,k.TASK.COMPLETED,J)}function g2($,J){d($,k.TASK.CONVERSATION_TURN,{...J,timestamp:new Date().toISOString()})}function D5($,J){d($,k.TASK.TOKEN_USAGE,J)}function U5($,J,Q){d($,k.TASK.MODE_SWITCH,{ulid:J,mode:Q})}function R5($,J){d($,k.TASK.TOOL_USED,J)}function z5($,J){d($,k.TASK.SKILL_USED,J)}function L5($,J){d($,k.TASK.DIFF_EDIT_FAILED,J)}function R4($,J){d($,k.TASK.PROVIDER_API_ERROR,{...J,errorMessage:D4(J.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function DW($,J){d($,k.SDK.TOOL_TIMEOUT,yA(J))}function yA($){let J={};for(let[Q,Z]of Object.entries($))if(Z!==void 0)J[Q]=Z;return J}function _5($,J,Q){d($,k.TASK.MENTION_USED,{mentionType:J,contentLength:Q,timestamp:new Date().toISOString()})}function O5($,J,Q,Z){d($,k.TASK.MENTION_FAILED,{mentionType:J,errorType:Q,errorMessage:D4(Z),timestamp:new Date().toISOString()})}function T5($,J,Q,Z,W){d($,k.TASK.MENTION_SEARCH_RESULTS,{queryLength:J.length,resultCount:Q,searchType:Z,isEmpty:W,timestamp:new Date().toISOString()})}function V$($,J){d($,k.TASK.AGENT_CREATED,{...J,timestamp:new Date().toISOString()})}function M5($,J){d($,k.TASK.AGENT_TEAM_CREATED,{...J,timestamp:new Date().toISOString()})}function z4($,J){d($,J.event==="ended"?k.TASK.SUBAGENT_COMPLETED:k.TASK.SUBAGENT_STARTED,{...J,timestamp:new Date().toISOString()})}function q5($,J,Q,Z){d($,k.HOOKS.DISCOVERY_COMPLETED,{hookName:J,globalCount:Q,workspaceCount:Z,totalCount:Q+Z,timestamp:new Date().toISOString()})}function P5($,J){d($,k.TASK.COMPACTION_EXECUTED,{...J,timestamp:new Date().toISOString()})}function N5($,J){d($,k.TASK.COMPACTION_SKIPPED,{...J,timestamp:new Date().toISOString()})}var qA=500,k;var F0=X$(()=>{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:MA,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as RG,readFileSync as zG,statSync as LG,writeFileSync as _G}from"node:fs";import{dirname as OG}from"node:path";import{resolveGlobalSettingsPath as A3}from"@cline/shared/storage";import{z as $2}from"zod";function x4(){return m4.parse({})}function TG(){g4=void 0}function MG($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function qG($){let J;try{J=zG($,"utf8")}catch{return x4()}try{let Q=m4.safeParse(JSON.parse(J));return Q.success?Q.data:x4()}catch{return x4()}}function PG(){let $=A3(),J=LG($,{throwIfNoEntry:!1}),Q=J?.mtimeMs??0,Z=J?.size??0,W=g4;if(W&&W.path===$&&W.mtimeMs===Q&&W.size===Z)return W;let j=MG(J?qG($):x4());return g4={path:$,mtimeMs:Q,size:Z,value:j},g4}function M0(){return PG().value}function C1($,J={}){let Q=A3(),Z=M0();RG(OG(Q),{recursive:!0});let W=m4.parse($);if(!Z.telemetryOptOut&&W.telemetryOptOut)FW(J.telemetry);_G(Q,`${JSON.stringify(W,null,2)}
2
+ `,"utf8"),TG()}function QQ(){return M0().telemetryOptOut}function NG($,J={}){C1({...M0(),telemetryOptOut:$},J)}function wG(){return M0().autoUpdateEnabled}function SG($,J={}){C1({...M0(),autoUpdateEnabled:$},J)}function H1($){return new Set($??M0().disabledTools??[])}function v4($){return new Set($??M0().disabledPlugins??[])}function CG($){return H1().has($)}function ZQ($){let J=M0(),Q=new Set(J.disabledTools??[]),Z=Q.has($);if(Z)Q.delete($);else Q.add($);return C1({...J,disabledTools:[...Q]}),!Z}function K3($,J){let Q=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Q.length===0)return;let Z=M0(),W=H1(Z.disabledTools);for(let j of Q)if(J)W.add(j);else W.delete(j);C1({...Z,disabledTools:[...W]})}function G3($,J){return K3([$],J),J}function yG($){return v4().has($)}function EG($,J){let Q=$.trim();if(!Q)return;let Z=M0(),W=v4(Z.disabledPlugins);if(J)W.add(Q);else W.delete(Q);C1({...Z,disabledPlugins:[...W]})}function WQ($,J){let Q=v4(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z))}function y1($,J){let Q=H1(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z.name))}function jQ($,J){if(!$||$.length===0)return $;let Q=H1(J);if(Q.size===0)return $;return $.map((Z)=>{if(!Z.setup)return Z;return{...Z,setup:(W,j)=>Z.setup?.({...W,registerTool:(f)=>{if(!Q.has(f.name))W.registerTool(f)}},j)}})}var B3,m4,g4;var p0=X$(()=>{F0();B3=$2.preprocess(($)=>Array.isArray($)?$.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter(Boolean):void 0,$2.array($2.string()).optional()).transform(($)=>{if(!$)return;let J=[...new Set($)].sort((Q,Z)=>Q.localeCompare(Z));return J.length>0?J:void 0}),m4=$2.object({telemetryOptOut:$2.boolean().default(!1).catch(!1),autoUpdateEnabled:$2.boolean().default(!0).catch(!0),disabledTools:B3.optional(),disabledPlugins:B3.optional()}).strip().transform(($)=>{let J={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)J.disabledTools=$.disabledTools;if($.disabledPlugins?.length)J.disabledPlugins=$.disabledPlugins;return J})});var oj={};V5(oj,{normalizeUserMessage:()=>aU,buildInitialUserContent:()=>nU});async function nU($,J,Q,Z){let W=sU(J),j=await tU(Q,Z);if(W.length===0&&!j)return $;let f=[{type:"text",text:$},...W];if(j)f.push(...j);return f}function aU($){if($==null)return"";if(typeof $==="string")return $;let J=$.content;if(typeof J==="string")return J;if(!Array.isArray(J))return"";let Q=[];for(let Z of J)if(Z&&typeof Z==="object"&&Z.type==="text"){let W=Z.text;if(typeof W==="string")Q.push(W)}return Q.join(`
3
+ `)}function sU($){if(!$||$.length===0)return[];let J=[];for(let Q of $){let Z=oU(Q);if(Z)J.push(Z)}return J}function oU($){let J=$.trim();if(!J)return;let Q=J.match(/^data:([^;,]+);base64,(.+)$/);if(Q){let Z=Q[1],W=Q[2];if(!Z||!W)return;return{type:"image",mediaType:Z,data:W}}return{type:"image",mediaType:"image/png",data:J}}async function tU($,J){if(!$||$.length===0)return;let Q=J??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Z=await Promise.all($.map(async(W)=>{let j=W.replace(/\\/g,"/");try{let f=await Q(W);return{type:"file",path:j,content:f}}catch(f){let X=f instanceof Error?f.message:String(f);return{type:"file",path:j,content:`Error fetching content: ${X}`}}}));if(Z.length===0)return;return Z}var uf={};V5(uf,{updateMcpServerOAuthState:()=>D8,setMcpServerDisabled:()=>G8,resolveMcpServerRegistrations:()=>m1,resolveDefaultMcpSettingsPath:()=>H0,registerMcpServersFromSettingsFile:()=>U8,normalizeMcpServerOAuthState:()=>R2,loadMcpSettingsFile:()=>K8,listMcpServerOAuthStatuses:()=>F9,hasMcpSettingsFile:()=>L$,getMcpServerOAuthState:()=>F8});import{existsSync as uR,mkdirSync as If,readFileSync as K9,writeFileSync as xf}from"node:fs";import{dirname as gf}from"node:path";import{resolveMcpSettingsPath as dR}from"@cline/shared/storage";import{z as w}from"zod";function A9($){if(!$)return;if($==="http")return"streamableHttp";return $}function H0(){return dR()}function $z($){let J=K9($,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse MCP settings JSON at "${$}": ${W}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Q}function cf($,J){if(!Object.hasOwn($,J))return;let Q=$[J];if(!Q||typeof Q!=="object"||Array.isArray(Q))return;return Q}function Jz($,J,Q){Object.defineProperty($,J,{value:Q,enumerable:!0,configurable:!0,writable:!0})}function K8($={}){let J=$.filePath??H0(),Q=K9(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${J}": ${f}`)}let W=eR.safeParse(Z);if(!W.success){let j=W.error.issues.map((f)=>{let X=f.path.join(".");return X?`${X}: ${f.message}`:f.message}).join("; ");throw Error(`Invalid MCP settings at "${J}": ${j}`)}return W.data}function Qz($){let J=K9($,"utf8"),Q;try{Q=JSON.parse(J)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${$}": ${f}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object`);let Z=Q,W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Z}function R2($){if(!$)return;let J={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(J).length>0?J:void 0}function Zz($){if($===void 0)return;let J=G9.safeParse($);if(!J.success)return;return R2(J.data)}function L$($={}){let J=$.filePath??H0();return uR(J)}function m1($={}){let J=K8($);return Object.entries(J.mcpServers).map(([Q,Z])=>({name:Q,transport:Z.transport,disabled:Z.disabled,metadata:Z.metadata,oauth:Z.oauth}))}function G8($){let J=$.filePath??H0(),Q=$.name.trim();if(!Q)throw Error("MCP server settings toggle requires a server name.");let Z=$z(J),W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${J}": mcpServers must be an object.`);let j={...W},f=cf(j,Q);if(!f)throw Error(`Unknown MCP server: ${Q}`);let X={...f};if($.disabled)X.disabled=!0;else delete X.disabled;Jz(j,Q,X),If(gf(J),{recursive:!0}),xf(J,`${JSON.stringify({...Z,mcpServers:j},null,2)}
4
+ `)}function F8($,J={}){let Q=K8(J);if(!Object.hasOwn(Q.mcpServers,$))return;return R2(Q.mcpServers[$]?.oauth)}function D8($,J,Q={}){let Z=Q.filePath??H0(),W=Qz(Z),j=W.mcpServers,f=cf(j,$);if(!f)throw Error(`Unknown MCP server: ${$}`);let X=Zz(f.oauth)??{},Y=R2(J(X));if(Y)f.oauth=Y;else delete f.oauth;return If(gf(Z),{recursive:!0}),xf(Z,`${JSON.stringify(W,null,2)}
5
+ `,"utf8"),Y??{}}function F9($={}){return m1($).map((Q)=>{let Z=Q.transport.type!=="stdio",W=Q.oauth?.tokens?.access_token;return{serverName:Q.name,oauthSupported:Z,oauthConfigured:Z&&typeof W==="string"&&W.trim().length>0,lastError:Q.oauth?.lastError,lastAuthenticatedAt:Q.oauth?.lastAuthenticatedAt}}).sort((Q,Z)=>Q.serverName.localeCompare(Z.serverName))}async function U8($,J={}){let Q=m1(J);for(let Z of Q)await $.registerServer(Z);return Q}var A8,mf,G9,lR,pR,rR,iR,nR,aR,vf,sR,oR,tR,eR;var C6=X$(()=>{A8=w.record(w.string(),w.string()),mf=w.record(w.string(),w.unknown()),G9=w.object({clientInformation:w.record(w.string(),w.unknown()).optional(),tokens:w.record(w.string(),w.unknown()).optional(),codeVerifier:w.string().optional(),discoveryState:w.record(w.string(),w.unknown()).optional(),redirectUrl:w.string().url().optional(),lastError:w.string().optional(),lastAuthenticatedAt:w.number().int().positive().optional()}).strip(),lR=w.object({type:w.literal("stdio"),command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:A8.optional()}),pR=w.object({type:w.literal("sse"),url:w.string().url(),headers:A8.optional()}),rR=w.object({type:w.literal("streamableHttp"),url:w.string().url(),headers:A8.optional()}),iR=w.discriminatedUnion("type",[lR,pR,rR]),nR=w.object({transport:iR,disabled:w.boolean().optional(),metadata:mf.optional(),oauth:G9.optional()}),aR=w.enum(["stdio","sse","http","streamableHttp"]).optional(),vf=w.object({type:w.enum(["stdio","sse","streamableHttp"]).optional(),transportType:aR,disabled:w.boolean().optional(),metadata:mf.optional(),oauth:G9.optional()});sR=vf.extend({command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:A8.optional()}).superRefine(($,J)=>{let Q=$.type??A9($.transportType);if(Q&&Q!=="stdio")J.addIssue({code:w.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),oR=vf.extend({url:w.string().url(),headers:A8.optional()}).superRefine(($,J)=>{let Q=$.type??A9($.transportType)??"sse";if(Q!=="sse"&&Q!=="streamableHttp")J.addIssue({code:w.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??A9($.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}}),tR=w.union([nR,sR,oR]),eR=w.object({mcpServers:w.record(w.string(),tR)}).passthrough()});import{existsSync as yT,mkdirSync as ET,readFileSync as bT,writeFileSync as hT}from"node:fs";import{resolve as kT}from"node:path";import{resolveSessionDataDir as IT}from"@cline/shared/storage";import{nanoid as xT}from"nanoid";import*as gT from"node-machine-id";function g0($){let J=$?.trim();if(J)return J;let Q=cT();if(Q)return Q;return uT()}function vT(){let $=gT;return $.machineIdSync??$.default?.machineIdSync}function cT(){try{let $=vT();if(!$)return;return $().trim()||void 0}catch{return}}function uT(){let $=IT(),J=kT($,mT);try{if(yT(J)){let Z=bT(J,"utf8").trim();if(Z.length>0)return Z}}catch{}let Q=`cl-${xT()}`;try{ET($,{recursive:!0}),hT(J,Q,"utf8")}catch{}return Q}var mT="machine-id";var q2=()=>{};class X4{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,J){if(!this.isEnabled())return;this.emitLog($,J,!1)}emitRequired($,J){this.emitLog($,J,!0)}recordCounter($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Z?{description:Z}:void 0),this.counters.set($,j);j.add(J,this.flattenProperties(this.buildAttributes(Q)))}recordHistogram($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Z?{description:Z}:void 0),this.histograms.set($,j);j.record(J,this.flattenProperties(this.buildAttributes(Q)))}recordGauge($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.buildAttributes(Q),f=JSON.stringify(j),X=this.gaugeValues.get($);if(J===null){if(X){if(X.delete(f),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let Y=X;if(!Y)Y=new Map,this.gaugeValues.set($,Y);if(!this.gauges.has($)){let V=this.meter.createObservableGauge($,Z?{description:Z}:void 0);V.addCallback((H)=>{for(let B of this.snapshotGaugeSeries($))H.observe(B.value,this.flattenProperties(B.attributes))}),this.gauges.set($,V)}Y.set(f,{value:J,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,J,Q){if(!this.logger)return;let Z=this.flattenProperties(this.buildAttributes(J,Q));this.logger.emit({severityText:"INFO",body:$,attributes:Z})}buildAttributes($,J=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...J?{_required:!0}:{}}}snapshotGaugeSeries($){let J=this.gaugeValues.get($);if(!J)return[];return Array.from(J.values(),(Q)=>({value:Q.value,attributes:Q.attributes?{...Q.attributes}:void 0}))}flattenProperties($,J="",Q=new WeakSet,Z=0){if(!$)return{};let W={},j=100,f=10;for(let[X,Y]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let V=J?`${J}.${X}`:X;if(Y===null||Y===void 0){W[V]=String(Y);continue}if(Array.isArray(Y)){let H=Y.length>j?Y.slice(0,j):Y;try{W[V]=JSON.stringify(H)}catch{W[V]="[UnserializableArray]"}if(Y.length>j)W[`${V}_truncated`]=!0,W[`${V}_original_length`]=Y.length;continue}if(typeof Y==="object"){if(Y instanceof Date){W[V]=Y.toISOString();continue}if(Y instanceof Error){W[V]=Y.message;continue}if(Q.has(Y)){W[V]="[Circular]";continue}if(Z>=f){W[V]="[MaxDepthExceeded]";continue}Q.add(Y),Object.assign(W,this.flattenProperties(Y,V,Q,Z+1));continue}if(Jw(Y)){W[V]=Y;continue}try{W[V]=JSON.stringify(Y)}catch{W[V]=String(Y)}}return W}}function Jw($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class dJ{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,J){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:J})}emitRequired($,J){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:J})}recordCounter($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordHistogram($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordGauge($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:J,attributes:Q,description:Z,required:W===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class Y4{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new dJ({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let J=this.buildAttributes($.properties);for(let Q of this.adapters)Q.emit($.event,J)}captureRequired($,J){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.emitRequired($,Q)}recordCounter($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordCounter($,J,j,Z,W)}recordHistogram($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordHistogram($,J,j,Z,W)}recordGauge($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordGauge($,J,j,Z,W)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var T7=()=>{};import{metrics as Qw,trace as Zw}from"@opentelemetry/api";import{logs as Ww}from"@opentelemetry/api-logs";import{OTLPLogExporter as jw}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as fw}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as Xw}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as Yw}from"@opentelemetry/resources";import{BatchLogRecordProcessor as Vw,ConsoleLogRecordExporter as Hw,LoggerProvider as Bw}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as Aw,MeterProvider as Kw,PeriodicExportingMetricReader as xH}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as Gw,ConsoleSpanExporter as Fw,SimpleSpanProcessor as Dw}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Uw}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as Rw,ATTR_SERVICE_VERSION as zw}from"@opentelemetry/semantic-conventions";class gH{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,J){this.resolveProperties(J)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class V4{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let J=Yw({[Rw]:$.serviceName??"cline",...$.serviceVersion?{[zw]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(J),this.loggerProvider=this.createLoggerProvider(J),this.tracerProvider=this.createTracerProvider(J),this.meterProvider)Qw.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)Ww.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",J){return Zw.getTracer($,J??this.options.serviceVersion)}createAdapter($){return new X4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let J=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new Y4({...$,adapters:[J],distinctId:g0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let J=M7(this.options.metricsExporter);if(J.length===0)return null;let Q=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Z=Math.min(30000,Math.floor(Q*0.8)),W=J.map((j)=>Ow(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Q,timeout:Z})).filter((j)=>j!==null);if(W.length===0)return null;return new Kw({resource:$,readers:W})}createTracerProvider($){let J=M7(this.options.tracesExporter);if(J.length===0)return null;let Q=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Z=this.options.otlpTracesHeaders??this.options.otlpHeaders,W=[];for(let j of J){let f=_w(j,{endpoint:Q,headers:Z,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(f)W.push(f)}if(W.length===0)return null;return new Uw({resource:$,spanProcessors:W})}createLoggerProvider($){let J=M7(this.options.logsExporter);if(J.length===0)return null;let Q=J.map((Z)=>{let W=Lw(Z,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!W)return null;return new Vw(W,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Z)=>Z!==null);if(Q.length===0)return null;return new Bw({resource:$,processors:Q})}}function lJ($){let J=new V4($),Q=J.createTelemetryService($);return Q.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:J,telemetry:Q}}function c$($){if(QQ())return{telemetry:new gH($)};if($.enabled!==!0)return{telemetry:new Y4({...$,distinctId:g0($.distinctId)})};return lJ($)}function pJ($){let{telemetry:J,provider:Q}=c$($);return{telemetry:J,provider:Q,flush:async()=>{let j=Q;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([J.dispose(),Q?.dispose()])}}}function M7($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Q)=>Q.trim()).filter((Q)=>Q==="console"||Q==="otlp")}function Lw($,J){if($==="console")return new Hw;if(!J.endpoint)return null;let Q=q7(J.endpoint,"/v1/logs");return new jw({url:Q,headers:J.headers})}function _w($,J){if($==="console")return new Dw(new Fw);if(!J.endpoint)return null;let Q=q7(J.endpoint,"/v1/traces");return new Gw(new Xw({url:Q,headers:J.headers}))}function Ow($,J){if($==="console")return new xH({exporter:new Aw,exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout});if(!J.endpoint)return null;let Q=q7(J.endpoint,"/v1/metrics");return new xH({exporter:new fw({url:Q,headers:J.headers}),exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout})}function q7($,J){let Q=new URL($),Z=Q.pathname.endsWith("/")?Q.pathname.slice(0,-1):Q.pathname;return Q.pathname=Z.endsWith(J)?Z:`${Z}${J}`,Q.toString()}var rJ=X$(()=>{p0();q2();T7()});var mB={};V5(mB,{resolveCoreDistinctId:()=>g0,createOpenTelemetryTelemetryService:()=>lJ,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>pJ,OpenTelemetryProvider:()=>V4,OpenTelemetryAdapter:()=>X4});var eJ=X$(()=>{q2();rJ()});import*as _a from"@cline/llms";import{buildClineSystemPrompt as Ta,buildSdkErrorProperties as Ma,ContributionRegistry as qa,captureSdkError as Pa,createClineTelemetryServiceConfig as Na,createClineTelemetryServiceMetadata as wa,createContributionRegistry as Sa,createTool as Ca,emptyWorkspaceManifest as ya,FEATURE_FLAGS as Ea,FeatureFlagDefaultValue as ba,formatDisplayUserInput as ha,noopBasicLogger as ka,normalizeSdkError as Ia,normalizeUserInput as xa,parseUserCommandEnvelope as ga,registerDisposable as ma,SDK_ERROR_TELEMETRY_EVENT as va}from"@cline/shared";export*from"@cline/shared/storage";function TA($){if(typeof $!=="object"||$===null||!("error"in $))return;let J=$.error;return typeof J==="string"&&J.trim()?J:void 0}function BW($,J,Q){let Z=TA(Q);if(Z)return Z;let W=J.trim();if(W){let j=W.length>200?`${W.slice(0,200)}...`:W;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class H5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let J=$.apiBaseUrl.trim();if(!J)throw Error("apiBaseUrl is required");this.apiBaseUrl=J,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let J=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(J)}/balance`)}async fetchUsageTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/usages`)).items??[]}async fetchPaymentTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}`)}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}/balance`)}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");let Q=await this.resolveOrganizationMemberId(J,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(J)}/members/${encodeURIComponent(Q)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let J=$?.trim();if(J)return J;let Z=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Z)return Z;let W=await this.fetchMe();if(!W.id?.trim())throw Error("Unable to resolve current user id");return W.id}async resolveOrganizationMemberId($,J){let Q=J?.trim();if(Q)return Q;let W=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(W)return W;let f=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!f?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return f}async request($,J){let Q=(await this.getAuthTokenFn())?.trim();if(!Q)throw Error("No Cline account auth token found");let Z=this.getHeadersFn?await this.getHeadersFn():{},W=new AbortController,j=setTimeout(()=>W.abort(),this.requestTimeoutMs);try{let f=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:J?.method??"GET",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",...Z??{}},body:J?.body!==void 0?JSON.stringify(J.body):void 0,signal:W.signal});if(f.status===204||J?.expectNoContent){if(!f.ok)throw Error(`Cline account request failed with status ${f.status}`);return}let X=await f.text(),Y;if(X.trim())try{Y=JSON.parse(X)}catch{if(!f.ok)throw Error(BW(f.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!f.ok)throw Error(BW(f.status,X,Y));if(typeof Y==="object"&&Y!==null){let V=Y;if(typeof V.success==="boolean"){if(!V.success)throw Error(V.error||"Cline account request failed");if(V.data!==void 0)return V.data}}if(Y===void 0||Y===null)throw Error("Cline account response payload was empty");return Y}finally{clearTimeout(j)}}}function AW($){return $.action==="clineAccount"}async function KW($,J){switch($.operation){case"fetchMe":return J.fetchMe();case"fetchBalance":return J.fetchBalance($.userId);case"fetchUsageTransactions":return J.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return J.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return J.fetchUserOrganizations();case"fetchOrganizationBalance":return J.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return J.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await J.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return J.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class B5{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:J})}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:J,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}function F4($){return{onAuth:({url:J,instructions:Q})=>{if($.onOutput?.(Q??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(J)).catch((Z)=>{$.onOpenUrlError?.({url:J,error:Z})})}catch(Z){$.onOpenUrlError?.({url:J,error:Z})}$.onOutput?.(J)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}F0();import{getClineEnvironmentConfig as w5}from"@cline/shared";function EA(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function Y1($){let J=await import("node:http"),Q=$.host??"127.0.0.1",Z=$.timeoutMs??300000,W=$.successHtml??bA,j=EA(),f=!1,X=null,Y=null,V=null,H=(K)=>{if(f)return;f=!0,j.resolve(K)},B=()=>{if(X)clearTimeout(X),X=null;let K=V;if(V=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:K})).catch(()=>{})},A=async()=>{return X=setTimeout(()=>{B(),H(null)},Z),j.promise};for(let K of $.ports){let G=J.createServer((D,U)=>{try{let F=new URL(D.url||"",`http://${Q}:${K}`);if(F.pathname!==$.callbackPath){U.statusCode=404,U.end("Not found");return}let O={url:F,code:F.searchParams.get("code")??void 0,state:F.searchParams.get("state")??void 0,provider:F.searchParams.get("provider")??void 0,error:F.searchParams.get("error")??void 0};if(O.error){U.statusCode=400,U.end(`Authentication failed: ${O.error}`),B(),H(O);return}if(!O.code){U.statusCode=400,U.end("Missing authorization code");return}if($.expectedState&&O.state!==$.expectedState){U.statusCode=400,U.end("State mismatch");return}U.statusCode=200,U.setHeader("Content-Type","text/html; charset=utf-8"),U.end(W),B(),H(O)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((D)=>{let U=(F)=>{G.off("error",U),D({bound:!1,error:F})};G.once("error",U),G.listen(K,Q,()=>{G.off("error",U),Y=G,D({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw B(),R.error}if(R.bound){V=K;let D=`http://${Q}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:K,callbackUrl:D})).catch(()=>{});return{callbackUrl:D,waitForCallback:A,cancelWait:()=>{B(),H(null)},close:()=>{B(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var bA=`<!DOCTYPE html>
6
6
  <html lang="en">
7
7
  <head>
8
8
  <meta charset="utf-8">
@@ -43,8 +43,8 @@ import{createRequire as _A}from"node:module";var RA=Object.defineProperty;var zA
43
43
  </div>
44
44
  <script>setTimeout(() => window.close(), 3000);</script>
45
45
  </body>
46
- </html>`;function DW($){let J="";for(let Q=0;Q<$.length;Q+=1)J+=String.fromCharCode($[Q]??0);return btoa(J).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function bA($){let Q=new TextEncoder().encode($),Z=await crypto.subtle.digest("SHA-256",Q);return new Uint8Array(Z)}function hA($=32){let J=new Uint8Array($);return crypto.getRandomValues(J),DW(J)}async function L4(){let $=hA(),J=DW(await bA($));return{verifier:$,challenge:J}}function _4($){return $.endsWith("/")?$.slice(0,-1):$}function H$($,J){return new URL(J,`${_4($)}/`).toString()}function n$($,J={}){let Q=$.trim();if(!Q)return{};try{let Z=new URL(Q);return{code:Z.searchParams.get("code")??void 0,state:Z.searchParams.get("state")??void 0,provider:J.includeProvider?Z.searchParams.get("provider")??void 0:void 0}}catch{}if(J.allowHashCodeState&&Q.includes("#")){let[Z,W]=Q.split("#",2);return{code:Z||void 0,state:W||void 0}}if(Q.includes("code=")){let Z=new URLSearchParams(Q);return{code:Z.get("code")??void 0,state:Z.get("state")??void 0,provider:J.includeProvider?Z.get("provider")??void 0:void 0}}return{code:Q}}function kA($){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 R0($){if(!$)return null;try{let J=$.split(".");if(J.length!==3)return null;let Q=J[1];if(!Q)return null;let Z=Q.replace(/-/g,"+").replace(/_/g,"/"),W=Z.padEnd(Z.length+(4-Z.length%4)%4,"="),j=kA(W);if(!j)return null;return JSON.parse(j)}catch{return null}}function a$($){try{let J=JSON.parse($),Q=J.error,Z=typeof Q==="string"?Q:Q&&typeof Q==="object"&&typeof Q.type==="string"?Q.type:void 0,W=typeof J.error_description==="string"?J.error_description:typeof J.message==="string"?J.message:Q&&typeof Q==="object"&&typeof Q.message==="string"?Q.message:void 0;return{code:Z,message:W}}catch{return{}}}function s$($,J){return Date.now()>=$.expires-J}async function o$($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let J,Q,Z=$.onManualCodeInput().then((j)=>{J=j,$.cancelWait()}).catch((j)=>{Q=j instanceof Error?j:Error(String(j)),$.cancelWait()}),W=await $.waitForCallback();if(Q)throw Q;if(W?.code||W?.error)return{code:W.code,state:W.state,provider:W.provider,error:W.error};if(J)return n$(J,$.parseOptions);if(await Z,Q)throw Q;if(J)return n$(J,$.parseOptions);return{}}var O4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},LW={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},S5="https://api.workos.com",IA="/auth",UW=Array.from({length:11},($,J)=>48801+J),xA=300000,gA=30000,t$=30000,mA=300,vA=5;class w1 extends Error{status;errorCode;constructor($,J){super($);this.name="ClineOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function cA($){let J=Date.parse($);if(Number.isNaN(J))throw Error(`Invalid expiresAt value: ${$}`);return J}function C5($,J,Q={}){let Z=$.userInfo.clineUserId??Q.accountId,W=$.refreshToken??Q.refresh;if(!W)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:W,expires:cA($.expiresAt),accountId:Z??void 0,email:$.userInfo.email||Q.email,metadata:{provider:J,tokenType:$.tokenType,userInfo:$.userInfo}}}async function y5($){if(!$)return{};return typeof $==="function"?await $():$}function RW($,J){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return J;return Math.floor($)}async function zW($){await new Promise((J)=>setTimeout(J,$))}function E5($,J){if(!$.success||!$.data?.accessToken)throw Error(J);return $.data}async function _W($,J){let Q=await fetch(H$(S5,LW.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(J?.requestTimeoutMs??t$)}),Z=await Q.json().catch(()=>({}));if(!Q.ok)throw new w1(`Device authorization failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error});if(!Z.device_code||!Z.user_code||!Z.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Z.device_code,userCode:Z.user_code,verificationUri:Z.verification_uri,verificationUriComplete:Z.verification_uri_complete,expiresInSeconds:RW(Z.expires_in,mA),pollIntervalSeconds:RW(Z.interval,vA)}}async function OW($){let J=Date.now()+$.expiresInSeconds*1000,Q=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=J){let Z=await fetch(H$($.workosApiBaseUrl,LW.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),W=await Z.json().catch(()=>({}));if(Z.ok){if(!W.access_token||!W.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:W.access_token,refreshToken:W.refresh_token,tokenType:W.token_type??"Bearer"}}switch(W.error){case"authorization_pending":{await zW(Q*1000);break}case"slow_down":{Q+=1,await zW(Q*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new w1(W.error_description||"WorkOS authorization failed",{status:Z.status,errorCode:W.error});default:throw new w1(`WorkOS token polling failed: ${Z.status}${W.error_description?` - ${W.error_description}`:""}`,{status:Z.status,errorCode:W.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function TW($,J,Q){let Z={accessToken:$.accessToken,refreshToken:$.refreshToken},W=await fetch(H$(J.apiBaseUrl,O4.register),{method:"POST",headers:{"Content-Type":"application/json",...await y5(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??t$)});if(!W.ok){let f=await W.text().catch(()=>""),X=a$(f);throw new w1(`Token registration failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return C5(E5(j,"Invalid token exchange response"),Q??J.provider)}async function uA($,J,Q,Z){let W={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:J,provider:Z??Q.provider},j=await fetch(H$(Q.apiBaseUrl,O4.token),{method:"POST",headers:{"Content-Type":"application/json",...await y5(Q.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(Q.requestTimeoutMs??t$)});if(!j.ok){let X=await j.text().catch(()=>""),Y=a$(X);throw new w1(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let f=await j.json();return C5(E5(f,"Invalid token exchange response"),Z??Q.provider)}async function b5($){M1($.telemetry,$.provider??"cline");let J=$.useWorkOSDeviceAuth??!0,Q=$.callbackPorts?.length?$.callbackPorts:UW,Z=$.callbackPath??IA,W=J?null:await Y1({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=W?.callbackUrl||`http://127.0.0.1:${Q[0]??UW[0]}${Z}`;try{let f;if(J){let X=w5().workOsClientId,Y=await _W(X,$);$.callbacks.onAuth({url:Y.verificationUriComplete??Y.verificationUri,instructions:`Enter this code in your browser: ${Y.userCode}`});let V=await OW({clientId:X,deviceCode:Y.deviceCode,expiresInSeconds:Y.expiresInSeconds,initialPollIntervalSeconds:Y.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??t$,workosApiBaseUrl:S5,onProgress:$.callbacks.onProgress});f=await TW(V,$,$.provider)}else{let X=new URL(H$($.apiBaseUrl,O4.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",j),X.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let Y,V=$.provider,H=await o$({waitForCallback:W?.waitForCallback??(async()=>null),cancelWait:W?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(Y=H.code,V=H.provider??V,!Y){let B=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=n$(B,{includeProvider:!0});Y=A.code,V=A.provider??V}if(!Y)throw Error("Missing authorization code");f=await uA(Y,j,$,V)}return q1($.telemetry,$.provider??"cline"),N1($.telemetry,{id:f.accountId,email:f.email,provider:$.provider??"cline"}),f}catch(f){throw P1($.telemetry,$.provider??"cline",f instanceof Error?f.message:String(f)),f}finally{W?.close()}}async function dA($){return await _W(w5().workOsClientId,$)}async function lA($){let J=$.provider??"cline";M1($.telemetry,J);try{let Q=await OW({clientId:w5().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??t$,workosApiBaseUrl:S5}),Z=await TW(Q,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return q1($.telemetry,J),N1($.telemetry,{id:Z.accountId,email:Z.email,provider:J}),Z}catch(Q){throw P1($.telemetry,J,Q instanceof Error?Q.message:String(Q)),Q}}async function MW($,J){let Q=await fetch(H$(J.apiBaseUrl,O4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await y5(J.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(J.requestTimeoutMs??t$)});if(!Q.ok){let j=await Q.text().catch(()=>""),f=a$(j);throw new w1(`Token refresh failed: ${Q.status}${f.message?` - ${f.message}`:""}`,{status:Q.status,errorCode:f.code})}let Z=await Q.json(),W=$.metadata?.provider??J.provider;return C5(E5(Z,"Invalid token refresh response"),W,$)}async function h5($,J,Q){if(!$)return null;let Z=Q?.refreshBufferMs??xA,W=Q?.retryableTokenGraceMs??gA;if(Q?.forceRefresh!==!0&&!s$($,Z))return $;try{return await MW($,J)}catch(f){if(f instanceof w1&&f.isLikelyInvalidGrant())return Y$(J.telemetry,J.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}F0();import{nanoid as pA}from"nanoid";var e={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class T4 extends Error{status;errorCode;constructor($,J){super($);this.name="OpenAICodexOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function rA($,J,Q=e.redirectUri){let Z=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:$,code_verifier:J,redirect_uri:Q}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!Z.ok)return{type:"failed"};let W=await Z.json();if(!W.access_token||!W.refresh_token||typeof W.expires_in!=="number")return{type:"failed"};return{type:"success",access:W.access_token,refresh:W.refresh_token,expires:Date.now()+W.expires_in*1000,email:W.email,idToken:W.id_token}}async function iA($){try{let J=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!J.ok){let Z=await J.text().catch(()=>""),W=a$(Z);throw new T4(`Token refresh failed: ${J.status}${W.message?` - ${W.message}`:""}`,{status:J.status,errorCode:W.code})}let Q=await J.json();if(!Q.access_token||!Q.refresh_token||typeof Q.expires_in!=="number")return{type:"failed"};return{type:"success",access:Q.access_token,refresh:Q.refresh_token,expires:Date.now()+Q.expires_in*1000,email:Q.email,idToken:Q.id_token}}catch(J){if(J instanceof T4)throw J;return{type:"failed"}}}async function nA($="pi"){let{verifier:J,challenge:Q}=await L4(),Z=pA(32),W=new URL(e.authorizationEndpoint);return W.searchParams.set("response_type","code"),W.searchParams.set("client_id",e.clientId),W.searchParams.set("redirect_uri",e.redirectUri),W.searchParams.set("scope",e.scopes),W.searchParams.set("code_challenge",Q),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("state",Z),W.searchParams.set("id_token_add_organizations","true"),W.searchParams.set("codex_cli_simplified_flow","true"),W.searchParams.set("originator",$),{verifier:J,state:Z,url:W.toString()}}function aA(){try{let $=new URL(e.redirectUri),J=$.port.length>0?Number.parseInt($.port,10):e.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(J)?J:e.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function sA($,J){let Q=J?R0(J):R0($),Z=Q?Q:R0($),j=Z?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let f=Z?.organizations;if(Array.isArray(f)&&f.length>0){let Y=f[0];if(typeof Y?.id==="string"&&Y.id.length>0)return Y.id}let X=Z?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function qW($,J){let Q=sA($.access,$.idToken)??J?.accountId;if(!Q)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||J?.refresh||"",expires:$.expires,accountId:Q,email:$.email??J?.email,metadata:{...J?.metadata??{},provider:"openai-codex"}}}async function k5($){M1($.telemetry,"openai-codex");let J=aA(),{verifier:Q,state:Z,url:W}=await nA($.originator),j=await Y1({host:J.host,ports:[J.port],callbackPath:J.callbackPath,expectedState:Z});$.onAuth({url:W,instructions:"Continue the authentication process in your browser."});let f;try{let X=await o$({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Z)throw Error("State mismatch");if(f=X.code,!f){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=n$(H,{allowHashCodeState:!0});if(B.state&&B.state!==Z)throw Error("State mismatch");f=B.code}if(!f)throw Error("Missing authorization code");let Y=await rA(f,Q,J.redirectUri);if(Y.type!=="success")throw Error("Token exchange failed");let V=qW(Y);return q1($.telemetry,"openai-codex"),N1($.telemetry,{id:V.accountId,email:V.email,provider:"openai-codex"}),V}catch(X){throw P1($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{j.close()}}async function PW($,J){let Q=await iA($);if(Q.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Z=qW(Q,J);if(!Z.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Z}async function I5($,J){if(!$)return null;let Q=J?.refreshBufferMs??e.refreshBufferMs,Z=J?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(J?.forceRefresh!==!0&&!s$($,Q))return $;try{return await PW($.refresh,$)}catch(j){if(j instanceof T4&&j.isLikelyInvalidGrant())return Y$(J?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}F0();import{nanoid as NW}from"nanoid";class x5{ttlMs;maxEntries;entries=new Map;constructor($,J){this.ttlMs=$;this.maxEntries=J}get($,J=Date.now()){this.pruneExpired(J);let Q=this.entries.get($);if(!Q)return;return this.entries.delete($),this.entries.set($,Q),Q.value}set($,J,Q=Date.now(),Z=this.ttlMs){this.pruneExpired(Q),this.entries.delete($);while(this.entries.size>=this.maxEntries){let W=this.entries.keys().next().value;if(W===void 0)break;this.entries.delete(W)}this.entries.set($,{value:J,expiresAt:Q+Z})}pruneExpired($){for(let[J,Q]of this.entries)if(Q.expiresAt<=$)this.entries.delete(J)}}var oA="a8331954c0cf48ba99b5dd223a14c6ea",tA="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",eA="openid offline_access",m5="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",$K="c1aba3deed5740659981a752714eba33",JK="https://login-ext.identity.oraclecloud.com",QK="openid offline_access",v5="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm";var ZK="/auth/oca",WK=Array.from({length:11},($,J)=>48801+J),jK=300000,fK=30000,wW=30000,XK=600000;class M4 extends Error{status;errorCode;constructor($,J){super($);this.name="OcaOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var S1={internal:{clientId:oA,idcsUrl:tA,scopes:eA,baseUrl:m5},external:{clientId:$K,idcsUrl:JK,scopes:QK,baseUrl:v5}},m2=new Map,YK=86400000,VK=300000,HK=32,g5=new x5(YK,HK);function SW($){if(typeof $==="function")return $();return $??"internal"}function CW($){return{internal:{clientId:$?.internal?.clientId??S1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??S1.internal.idcsUrl,scopes:$?.internal?.scopes??S1.internal.scopes,baseUrl:$?.internal?.baseUrl??S1.internal.baseUrl},external:{clientId:$?.external?.clientId??S1.external.clientId,idcsUrl:$?.external?.idcsUrl??S1.external.idcsUrl,scopes:$?.external?.scopes??S1.external.scopes,baseUrl:$?.external?.baseUrl??S1.external.baseUrl}}}function BK($=Date.now()){let J=$-XK;for(let[Q,Z]of m2.entries())if(Z.createdAt<J)m2.delete(Q)}function AK($,J,Q){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let W=R0(J)?.exp;if(typeof W==="number"&&W>0)return W*1000;let f=R0(Q)?.exp;if(typeof f==="number"&&f>0)return f*1000;return Date.now()+3600000}function yW($,J,Q){let Z=$.access_token;if(!Z)throw Error("Token response did not include an access token");let W=$.refresh_token??Q?.refresh;if(!W)throw Error("Token response did not include a refresh token");let j=R0($.id_token),f=R0(Z),X=j?.sub??f?.sub,Y=j?.email??f?.email;return{access:Z,refresh:W,expires:AK($,Z,$.id_token),accountId:X??Q?.accountId,email:Y??Q?.email,metadata:{...Q?.metadata??{},provider:"oca",mode:J,subject:X,idToken:$.id_token}}}async function EW($,J){let Q=_4($),Z=g5.get(Q);if(Z)return Z;let W=`${Q}/.well-known/openid-configuration`,j=await fetch(W,{method:"GET",signal:AbortSignal.timeout(J)});if(!j.ok){let Y=`${Q}/oauth2/v1/token`;return g5.set(Q,Y,Date.now(),VK),Y}let X=(await j.json()).token_endpoint||`${Q}/oauth2/v1/token`;return g5.set(Q,X),X}function bW($){return{code:$.error,message:$.error_description}}async function KK($){let J=m2.get($.state);if(!J)throw Error("No PKCE verifier found for this state");m2.delete($.state);let Q=$.mode==="external"?$.config.external:$.config.internal,Z=await EW(Q.idcsUrl,$.requestTimeoutMs),W=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:J.redirectUri,client_id:Q.clientId,code_verifier:J.verifier}),j=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,signal:AbortSignal.timeout($.requestTimeoutMs)}),f=await j.json();if(!j.ok){let Y=bW(f);throw new M4(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let X=R0(f.id_token);if(!f.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==J.nonce)throw Error("OIDC nonce verification failed");return yW(f,$.mode)}function GK($){let J=$.mode==="external"?$.config.external:$.config.internal,Q=new URL(`${_4(J.idcsUrl)}/oauth2/v1/authorize`);return Q.searchParams.set("client_id",J.clientId),Q.searchParams.set("response_type","code"),Q.searchParams.set("scope",J.scopes),Q.searchParams.set("code_challenge",$.challenge),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",$.callbackUrl),Q.searchParams.set("state",$.state),Q.searchParams.set("nonce",$.nonce),Q.toString()}async function c5($){M1($.telemetry,"oca");let J=CW($.config),Q=SW($.mode),Z=$.callbackPorts?.length?$.callbackPorts:WK,W=$.callbackPath??ZK,j=$.requestTimeoutMs??wW,f=await Y1({ports:Z,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=f.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let Y=NW(16),V=NW(16),{verifier:H,challenge:B}=await L4();BK(),m2.set(Y,{verifier:H,nonce:V,mode:Q,redirectUri:X,createdAt:Date.now()});let A=GK({callbackUrl:X,mode:Q,state:Y,nonce:V,challenge:B,config:J});$.callbacks.onAuth({url:A,instructions:"Continue the authentication process in your browser."});try{let K=await o$({waitForCallback:f.waitForCallback,cancelWait:f.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==Y)throw Error("State mismatch");let D=await KK({code:G,state:R,mode:Q,config:J,requestTimeoutMs:j});return q1($.telemetry,"oca"),N1($.telemetry,{id:D.accountId,email:D.email,provider:"oca"}),D}catch(K){throw P1($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{f.close()}}async function hW($,J={}){let Q=CW(J.config),Z=J.requestTimeoutMs??wW,W=$.metadata?.mode,j=W==="internal"||W==="external"?W:SW(J.mode),f=j==="external"?Q.external:Q.internal,X=await EW(f.idcsUrl,Z),Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:f.clientId}),V=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,signal:AbortSignal.timeout(Z)}),H=await V.json();if(!V.ok){let B=bW(H);throw new M4(`Token refresh failed: ${V.status}${B.message?` - ${B.message}`:""}`,{status:V.status,errorCode:B.code})}return yW(H,j,$)}async function u5($,J,Q){if(!$)return null;let Z=J?.refreshBufferMs??Q?.refreshBufferMs??jK,W=J?.retryableTokenGraceMs??Q?.retryableTokenGraceMs??fK;if(J?.forceRefresh!==!0&&!s$($,Z))return $;try{return await hW($,Q)}catch(f){if(f instanceof M4&&f.isLikelyInvalidGrant())return Y$(Q?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}import{getClineEnvironmentConfig as kW}from"@cline/shared";var q4="workos:";function FK($){let J=$.trim();return J.toLowerCase().startsWith(q4)?J:`${q4}${J}`}function DK($){let J=$.trim();return J.toLowerCase().startsWith(q4)?J.slice(q4.length):J}function UK($){let Q=R0($)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return null}function RK($,J){let Q=$.auth?.expiresAt;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>0)return Q;let Z=UK(J);if(Z)return Z;return Date.now()-1}function zK($,J){let Q=$.auth?.accessToken?.trim(),Z=$.auth?.refreshToken?.trim();if(!Q||!Z)return null;let W=J?.normalizeAccessToken?.(Q)??Q;if(!W)return null;return{access:W,refresh:Z,expires:RK($,W),accountId:$.auth?.accountId}}function LK($){let J=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Q={...$.settings?.auth??{},accessToken:J,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Z={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Q};if($.save!==!1)$.manager.saveProviderSettings(Z,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return Z}function d5($){let J=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:J,getApiKey(Q){let Z=Q?.auth?.accessToken?.trim();if(Z)return $.formatAccessToken?.(Z)??Z;return Q?.apiKey?.trim()||Q?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Q){return LK({...Q,storageProviderId:J,formatAccessToken:$.formatAccessToken})},isConfigured(Q){return!!Q?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function IW($){return d5({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:FK,normalizeStoredAccessToken:DK,login:({settings:J,callbacks:Q,telemetry:Z})=>b5({apiBaseUrl:J?.baseUrl?.trim()||kW().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q,telemetry:Z}),refresh:({settings:J,credentials:Q,forceRefresh:Z,telemetry:W})=>h5(Q,{apiBaseUrl:J.baseUrl?.trim()||kW().apiBaseUrl,telemetry:W},{forceRefresh:Z})})}var _K=[IW({providerId:"cline"}),IW({providerId:"cline-pass",storageProviderId:"cline"}),d5({providerId:"oca",login:({settings:$,callbacks:J,telemetry:Q})=>c5({mode:$?.oca?.mode,callbacks:J,telemetry:Q}),refresh:({settings:$,credentials:J,forceRefresh:Q,telemetry:Z})=>u5(J,{forceRefresh:Q,telemetry:Z},{mode:$.oca?.mode,telemetry:Z})}),d5({providerId:"openai-codex",login:({callbacks:$,telemetry:J})=>k5({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:J}),refresh:({credentials:$,forceRefresh:J,telemetry:Q})=>I5($,{forceRefresh:J,telemetry:Q})})],OK=new Map(_K.map(($)=>[$.providerId,$]));function f0($){return OK.get($.trim().toLowerCase())}function v2($){return f0($)!==void 0}function TK($){return f0($)?.storageProviderId}function MK($,J){let Q=f0(J),Z=Q?.storageProviderId??J,W=$.getProviderSettings(Z);return Q?.getApiKey(W)??P4(J,W)}async function l5($,J,Q){let Z=f0(J);if(!Z)throw Error(`Provider "${J}" does not support OAuth login`);let W=$.getProviderSettings(Z.storageProviderId),j=await Z.login({settings:W,callbacks:Q.callbacks,telemetry:Q.telemetry});return Z.saveCredentials({manager:$,settings:W,credentials:j})}function p5($,J){let Q=f0($);if(!Q)return null;return zK(J,{normalizeAccessToken:Q.normalizeStoredAccessToken})}function c2($){let J=f0($.providerId);if(!J)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return J.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function P4($,J){let Q=f0($);if(Q)return Q.getApiKey(J);return J?.auth?.accessToken?.trim()||J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0}function qK($,J){let Q=f0($);if(!Q)return J.access;return Q.getApiKey({provider:Q.storageProviderId,auth:{accessToken:J.access}})??J.access}import*as C0 from"@cline/llms";import{z as q}from"zod";import*as Q0 from"@cline/llms";function r5($){if(!Array.isArray($))return[];return $.map((J)=>{if(typeof J==="string")return J.trim();if(J&&typeof J==="object"){let Q=J;for(let Z of[Q.id,Q.name,Q.model])if(typeof Z==="string"&&Z.trim())return Z.trim()}return""}).filter((J)=>J.length>0)}function PK($,J){let Q=r5($);if(Q.length>0)return Q;if(!$||typeof $!=="object")return[];let Z=$,W=r5(Z.data??Z.models);if(W.length>0)return W;if(Z.models&&typeof Z.models==="object"&&!Array.isArray(Z.models)){let f=Object.keys(Z.models).filter((X)=>X.trim().length>0);if(f.length>0)return f}let j=Z.providers?.[J];if(j&&typeof j==="object"){let X=r5(j.models??j);if(X.length>0)return X}return[]}async function N4($,J){let Q=await fetch($,{method:"GET"});if(!Q.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Q.status}`);return PK(await Q.json(),J)}function xW($){return $.replace(/\/+$/,"")}function w4($,J,Q){let Z=Q?.trim();if(!Z)return;let W=$?.trim();if(!W||!J?.trim())return Z;try{let j=new URL(Z),f=new URL(J),X=new URL(W);if(j.origin!==f.origin)return Z;let Y=xW(f.pathname),V=xW(X.pathname);if(Y&&j.pathname.startsWith(`${Y}/`)){let H=j.pathname.slice(Y.length);X.pathname=`${V}${H}`}else X.pathname=j.pathname;return X.search=j.search,X.hash=j.hash,X.toString()}catch{return Z}}function NK($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{...Q}]))}function wK($){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 SK=Object.values(Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:NK($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),vW=Object.fromEntries(SK.map(($)=>[$.id,$]));function CK($){return vW[$]}function yK(){return Object.fromEntries(Object.entries(vW).filter(([,$])=>wK($)))}function cW($=[]){let J=$.flatMap((Q)=>{switch(Q){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Q];default:return[]}});return J.length>0?J:void 0}var uW="https://models.dev/api.json",EK=600000,dW=300000,bK=5000,C4=new Map,u2=new Map,n5=new Map,S4=new Map;async function hK(){return Q0.getGeneratedProviderModels()}async function kK($,J={},Q={},Z={},W={},j={}){let f=await hK(),X=Q0.resolveProviderModelCatalogKeys($),Y=Object.assign({},...X.map((B)=>f[B]??{})),V=Boolean(Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),H=Object.keys(W).length>0;if(V&&H)return Q0.sortModelsByReleaseDate({...W,...j});if($==="openai-codex")return Q0.sortModelsByReleaseDate({...J,...Q0.filterOpenAICodexModels(Q),...W,...j});return Q0.sortModelsByReleaseDate({...Y,...J,...Q,...Z,...W,...j})}function IK($,J){let Q=Q0.resolveProviderModelCatalogKeys($);return Object.assign({},...Q.map((Z)=>J[Z]??{}))}function y4($){let J=$?.trim();return J&&J.length>0?J:""}function a5($){let J=$.apiKey?.trim()||$.accessToken?.trim();return J&&J.length>0?J:void 0}function xK($){let J=2166136261;for(let Q=0;Q<$.length;Q+=1)J^=$.charCodeAt(Q),J+=(J<<1)+(J<<4)+(J<<7)+(J<<8)+(J<<24);return(J>>>0).toString(16)}function gK($,J){return`${$}:${y4(J.baseUrl)}:${xK(a5(J)??"")}`}async function E4($,J,Q=bK){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await fetch($,{...J,signal:Z.signal})}finally{clearTimeout(W)}}function B$($,J,Q){if(Q&&!$.includes(J))$.push(J)}function b4($,J){let Q=["streaming","tools"];return B$(Q,"images",Boolean(J.supportsImages)),B$(Q,"prompt-cache",Boolean(J.supportsPromptCache)),B$(Q,"reasoning",Boolean(J.supportsReasoning)),{id:$,name:J.name??$,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxTokens:J.maxTokens,capabilities:Q,releaseDate:J.releaseDate,status:"active"}}async function mK($,J){let Q=await E4("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"}});if(!Q.ok)throw Error(`Baseten model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let Y=f.supported_features??[];j[X]=b4(X,{name:X,contextWindow:f.context_length,maxInputTokens:f.context_length,maxTokens:f.max_completion_tokens,supportsReasoning:Y.includes("reasoning")||Y.includes("reasoning_effort"),supportsImages:!1})}return j}function gW($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let J=Number($);return Number.isFinite(J)?J:void 0}return}async function vK($,J){let Q=await E4("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":J}});if(!Q.ok)throw Error(`Hicap model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;j[X]=b4(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function cK($,J){let Z=`${(y4($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,W=await E4(Z,{method:"GET",headers:{Authorization:`Bearer ${J}`,accept:"application/json"}});if(!W.ok)throw Error(`Poolside model refresh failed: HTTP ${W.status}`);let f=(await W.json())?.data??[],X={};for(let Y of f){let V=Y.id?.trim();if(!V)continue;let H=Y.supported_features??[],B=Y.supported_sampling_parameters??[],A=Y.input_modalities??[],K=["streaming"];B$(K,"tools",H.includes("tools")),B$(K,"reasoning",H.includes("reasoning")),B$(K,"temperature",B.includes("temperature")),B$(K,"images",A.includes("image"));let G={input:gW(Y.pricing?.prompt),output:gW(Y.pricing?.completion)};X[V]={id:V,name:Y.name??V,description:Y.description,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function uK($){let J=y4($);if(!J)return"http://localhost:4000";return J.endsWith("/v1")?J.slice(0,-3):J}async function dK($,J){let Z=`${uK($.baseUrl)}/v1/model/info`,W=async(V)=>E4(Z,{method:"GET",headers:{accept:"application/json",...V}}),j=await W({"x-litellm-api-key":J});if(!j.ok)j=await W({Authorization:`Bearer ${J}`});if(!j.ok)throw Error(`LiteLLM model refresh failed: HTTP ${j.status}`);let X=(await j.json())?.data??[],Y={};for(let V of X){let H=V.model_name?.trim(),A=V.litellm_params?.model?.trim()||H;if(!A)continue;let K=V.model_info,G=b4(A,{name:H??A,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(Y[A]=G,H)Y[H]={...G,id:H,name:H}}return Y}var lW={baseten:mK,hicap:vK,litellm:dK,poolside:cK},mW=new Map,i5=new Map;function lK($,J){return`${$}:${y4(J.baseUrl)}`}async function pK($,J,Q){let Z=Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=w4(Q.baseUrl,Z?.provider.baseUrl,Z?.provider.modelsSourceUrl);if(!W)return{};let j=J?.cacheTtlMs??dW,f=lK($,Q),X=Date.now(),Y=mW.get(f);if(Y&&Y.expiresAt>X)return Y.data;let V=i5.get(f);if(V)return V;let H=N4(W,$).then((B)=>{let A=Object.fromEntries(B.map((K)=>[K,b4(K,{name:K})]));return mW.set(f,{data:A,expiresAt:X+j}),A}).finally(()=>{i5.delete(f)});return i5.set(f,H),H}async function rK($,J){let Q=a5(J);if(!Q)return{};let Z=lW[$];if(!Z)return{};return Z(J,Q)}function iK($,J,Q){if(!Q)return!1;if(!lW[$])return!1;if(J?.loadPrivateOnAuth===!1)return!1;return Boolean(a5(Q))}async function nK($,J,Q){let Z=J?.cacheTtlMs??dW,W=gK($,Q),j=Date.now(),f=n5.get(W);if(f&&f.expiresAt>j)return f.data;let X=S4.get(W);if(X)return X;let Y=rK($,Q).then((V)=>{return n5.set(W,{data:V,expiresAt:j+Z}),V}).finally(()=>{S4.delete(W)});return S4.set(W,Y),Y}async function aK($){return Q0.fetchModelsDevProviderModels($,globalThis.fetch)}async function h4($={}){let J=$.url??uW,Q=$.cacheTtlMs??EK,Z=Date.now(),W=C4.get(J);if(W&&W.expiresAt>Z)return W.data;let j=u2.get(J);if(j)return j;let f=aK(J).then((X)=>{return C4.set(J,{data:X,expiresAt:Z+Q}),X}).finally(()=>{u2.delete(J)});return u2.set(J,f),f}function sK($){if($){C4.delete($),u2.delete($);return}C4.clear(),u2.clear()}function oK(){n5.clear(),S4.clear()}function tK($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{baseUrl:Q.baseUrl,modelId:Q.modelId,capabilities:cW(Q.capabilities)}]))}var s5=tK(yK());function pW($){let J=CK($);if(!J)return;return{baseUrl:J.baseUrl||void 0,modelId:J.modelId,knownModels:J.knownModels,capabilities:cW(J.capabilities)}}async function o5($,J,Q){let Z=pW($);if(!Z)return;try{let W=J?.loadLatestOnInit?await h4(J):void 0,j=W?IK($,W):{},f=Q&&iK($,J,Q)?await nK($,J,Q):{},Y=Boolean(Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Q??{providerId:$,modelId:Z.modelId,baseUrl:Z.baseUrl}:Q,V=Y?await pK($,J,Y).catch(()=>({})):{},H=await kK($,Z.knownModels,j,f,V,Q?.knownModels);return{...Z,knownModels:H}}catch(W){if(J?.failOnError)throw W;return Z}}var t5=C0.BUILT_IN_PROVIDER,eK=C0.BUILT_IN_PROVIDER_IDS,$G=C0.isBuiltInProviderId,k4=C0.normalizeProviderId,e5=q.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),rW=q.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),iW=q.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),nW=q.object({apiKey:q.string().optional(),accessToken:q.string().optional(),refreshToken:q.string().optional(),expiresAt:q.number().int().positive().optional(),accountId:q.string().optional()}),JG=q.enum(["none","low","medium","high","xhigh"]),aW=q.object({enabled:q.boolean().optional(),effort:JG.optional(),budgetTokens:q.number().int().positive().optional()}),sW=q.object({accessKey:q.string().optional(),secretKey:q.string().optional(),sessionToken:q.string().optional(),region:q.string().optional(),profile:q.string().optional(),authentication:q.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:q.boolean().optional(),useCrossRegionInference:q.boolean().optional(),useGlobalInference:q.boolean().optional(),endpoint:q.string().url().optional(),customModelBaseId:q.string().optional()}),oW=q.object({projectId:q.string().optional(),region:q.string().optional()}),tW=q.object({apiVersion:q.string().optional(),useIdentity:q.boolean().optional()}),eW=q.object({clientId:q.string().optional(),clientSecret:q.string().optional(),tokenUrl:q.string().url().optional(),resourceGroup:q.string().optional(),deploymentId:q.string().optional(),useOrchestrationMode:q.boolean().optional(),api:q.enum(["orchestration","foundation-models"]).optional(),defaultSettings:q.record(q.string(),q.unknown()).optional()}),$3=q.object({mode:q.enum(["internal","external"]).optional(),usePromptCache:q.boolean().optional()}),J3=q.object({loadLatestOnInit:q.boolean().optional(),loadPrivateOnAuth:q.boolean().optional(),url:q.string().url().optional(),cacheTtlMs:q.number().int().positive().optional(),failOnError:q.boolean().optional()}),e$=q.object({provider:e5,apiKey:q.string().optional(),auth:nW.optional(),model:q.string().optional(),protocol:rW.optional(),client:iW.optional(),routingProviderId:e5.optional(),maxTokens:q.number().int().positive().optional(),contextWindow:q.number().int().positive().optional(),baseUrl:q.string().url().optional(),headers:q.record(q.string(),q.string()).optional(),timeout:q.number().int().positive().optional(),reasoning:aW.optional(),aws:sW.optional(),gcp:oW.optional(),azure:tW.optional(),sap:eW.optional(),oca:$3.optional(),region:q.string().optional(),apiLine:q.enum(["china","international"]).optional(),capabilities:q.array(q.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:J3.optional()});function Q3($){return e$.parse($)}function Z3($){return e$.safeParse($)}function QG($){return $.protocol==="openai-responses"||$.client==="openai"}function V1($,J={}){let Q=$.provider,Z=k4(Q),W=J.includeKnownModels!==!1,j=$.reasoning?.effort||"none",f=j==="none"?void 0:j,X=s5[Z],Y=Object.assign({},...C0.resolveProviderModelCatalogKeys(Z).map((R)=>C0.getGeneratedModelsForProvider(R))),V=Object.keys(Y)[0],H=P4(Z,$),B=$.baseUrl??(Z==="oca"?$.oca?.mode==="internal"?m5:v5:X?.baseUrl),A=$.routingProviderId??(QG($)&&Z!==t5.OPENAI_NATIVE?t5.OPENAI_NATIVE:void 0),K=W?X?.knownModels??(Object.keys(Y).length>0?Y:void 0):void 0,G={providerId:Q,clientType:$.client,routingProviderId:A,modelId:$.model??X?.modelId??V??"default",...W?{knownModels:K}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:B,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:f,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,D])=>D!==void 0))}function ZG($){let J=Q3($);return V1(J)}function WG($){let J=Z3($);if(J.success)return{success:!0,config:V1(J.data)};return{success:!1,error:J.error}}import{SESSION_STATUS_VALUES as jG}from"@cline/shared";var $Q=jG,fG=["idle","running","pending"];function XG($){return!fG.includes($)}function Z0($){return!XG($)}var z0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function W3($){if($===!0)return{};if(!$)return;return $}function j3($){if($==="user")return"global";return $}class JQ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let J=this.getService().ingestEvent($);return{event:J.event,duplicate:J.duplicate,matchedSpecIds:J.matchedSpecs.map((Q)=>Q.specId),queuedRuns:J.queuedRuns,suppressions:J.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function f3($){let{host:J}=$;return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||z0.CLI,interactive:!1,config:{providerId:k4(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:HG(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content),delivery:Z.delivery});if(!W)throw Error("ClineCore automation runtime returned no result");return{result:VG(W)}},async abortSession(Q){return await J.abort(Q,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}function I4($){let J=YG($.automationService,$.automation),Q=$.context?.client??($.clientName?{name:$.clientName}:void 0),Z=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),W=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!J&&!Q&&!Z&&!W&&!j)return $.context;return{...$.context??{},...Q?{client:Q}:{},...Z?{user:Z}:{},...W?{logger:W}:{},...j?{telemetry:j}:{},...J?{automation:J}:{}}}function YG($,J){if(!$)return;return{ingestEvent:(Q)=>{J.ingestEvent(Q)}}}function VG($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function HG($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}import{existsSync as x6}from"node:fs";import{basename as jX,isAbsolute as mz,relative as vz}from"node:path";import{createHash as BG}from"node:crypto";import{watch as AG}from"node:fs";import{readdir as KG,readFile as GG}from"node:fs/promises";import{join as FG}from"node:path";function DG($){return BG("sha1").update($).digest("hex")}function V3($){return Boolean($&&typeof $==="object"&&"code"in $)}function X3($){return V3($)&&$.code==="ENOENT"}function Y3($){return V3($)&&($.code==="EACCES"||$.code==="EPERM")}class d2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,J){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=J?.debounceMs??75,this.emitParseErrors=J?.emitParseErrors??!1;for(let Q of $){if(this.definitionsByType.has(Q.type))throw Error(`Duplicate unified config definition type '${Q.type}'.`);this.definitionsByType.set(Q.type,Q),this.recordsByType.set(Q.type,new Map),this.discoveredDirectoriesByType.set(Q.type,new Set);for(let Z of Q.directories){let W=this.baseTypesByDirectory.get(Z);if(W)W.add(Q.type);else this.baseTypesByDirectory.set(Z,new Set([Q.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let J=this.definitionsByType.get($);if(!J)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(J)})}getSnapshot($){let J=this.recordsByType.get($);return new Map([...J?.entries()??[]].map(([Q,Z])=>[Q,{...Z}]))}getAllSnapshots(){let $=new Map;for(let[J,Q]of this.recordsByType.entries())$.set(J,new Map([...Q.entries()].map(([Z,W])=>[Z,{...W}])));return $}emit($){for(let J of this.listeners)J($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[J,Q]of this.watchersByDirectory.entries()){if($.has(J))continue;Q.close(),this.watchersByDirectory.delete(J)}this.watchedTypesByDirectory=$;for(let J of $.keys()){if(this.watchersByDirectory.has(J))continue;try{let Q=AG(J,()=>{let Z=this.watchedTypesByDirectory.get(J);if(!Z)return;for(let W of Z)this.pendingTypes.add(W);this.scheduleFlush()});this.watchersByDirectory.set(J,Q),Q.on("error",(Z)=>{let W=this.watchedTypesByDirectory.get(J);if(!W)return;for(let j of W)this.emit({kind:"error",type:j,error:Z,filePath:J})})}catch(Q){if(!X3(Q)&&!Y3(Q)){let Z=$.get(J);if(!Z)continue;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:J})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let J of $){let Q=this.definitionsByType.get(J);if(!Q)continue;await this.refreshTypeInternal(Q)}})},this.debounceMs)}async refreshTypeInternal($){let{records:J,discoveredDirectories:Q}=await this.loadDefinition($),Z=this.recordsByType.get($.type)??new Map;for(let[W,j]of Z.entries()){if(J.has(W))continue;this.emit({kind:"remove",type:$.type,id:W,filePath:j.filePath})}for(let[W,j]of J.entries()){let f=Z.get(W);if(f&&f.filePath===j.filePath&&f.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:W,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,J),this.discoveredDirectoriesByType.set($.type,Q),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let J=new Map,Q=new Set;for(let Z of $.directories){Q.add(Z);let W=$.discoverFiles?await $.discoverFiles(Z):await this.readDirectoryFileCandidates(Z);for(let j of W){let{fileName:f,filePath:X}=j;if(Q.add(j.directoryPath),$.includeFile&&!$.includeFile(f,X))continue;try{let Y=await GG(X,"utf8"),V={type:$.type,directoryPath:j.directoryPath,fileName:f,filePath:X,content:Y},H=$.parseFile(V),B=$.resolveId(H,V).trim();if(!B)continue;J.set(B,{type:$.type,id:B,item:H,filePath:X,fingerprint:DG(Y)})}catch(Y){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Y,filePath:X})}}}return{records:J,discoveredDirectories:Q}}buildDesiredTypesByDirectory(){let $=new Map;for(let[J,Q]of this.baseTypesByDirectory.entries())$.set(J,new Set(Q));for(let[J,Q]of this.discoveredDirectoriesByType.entries())for(let Z of Q){let W=$.get(Z);if(W)W.add(J);else $.set(Z,new Set([J]))}return $}async readDirectoryFileCandidates($){try{return(await KG($,{withFileTypes:!0})).filter((Q)=>Q.isFile()).map((Q)=>({directoryPath:$,fileName:Q.name,filePath:FG($,Q.name)})).sort((Q,Z)=>Q.fileName.localeCompare(Z.fileName))}catch(J){if(X3(J)||Y3(J))return[];throw J}}}import{readdir as TQ,readFile as bF,stat as OQ}from"node:fs/promises";import{basename as B1,dirname as hF,extname as s4,join as q0,resolve as s2}from"node:path";import{AGENTS_RULES_FILE_NAME as g3,RULES_CONFIG_DIRECTORY_NAME as m3,resolveGlobalAgentsRulesPath as kF,resolveRulesConfigSearchPaths as IF,resolveSkillsConfigSearchPaths as xF,resolveWorkflowsConfigSearchPaths as gF,SKILLS_CONFIG_DIRECTORY_NAME as MQ,WORKFLOWS_CONFIG_DIRECTORY_NAME as qQ}from"@cline/shared/storage";import mF from"yaml";p0();import{existsSync as r4,readFileSync as LF,statSync as _F}from"node:fs";import{basename as OF,dirname as l4,join as i4,resolve as p4}from"node:path";import{discoverPluginModulePaths as TF,resolveConfiguredPluginModulePaths as b3,resolvePluginConfigSearchPaths as MF,SKILLS_CONFIG_DIRECTORY_NAME as qF}from"@cline/shared/storage";import{resolve as oG}from"node:path";import{normalizePluginManifest as tG}from"@cline/shared";import{existsSync as Y0,readFileSync as Q2}from"node:fs";import{builtinModules as EG,createRequire as VQ}from"node:module";import{dirname as E1,extname as p2,isAbsolute as bG,resolve as u}from"node:path";import{fileURLToPath as F3}from"node:url";import{PLUGIN_FILE_EXTENSIONS as hG}from"@cline/shared";var D3=E1(F3(import.meta.url)),kG=VQ(import.meta.url),IG=u(D3,"..","..","..","..",".."),fQ=mG(IG),xG=["@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"],HQ=new Set(EG.flatMap(($)=>[$,$.replace(/^node:/,"")])),l2=new Set(hG),gG=["development","node","import","require","default"];function mG($){let J={},Q={"@cline/sdk":u($,"packages/sdk/src/index.ts"),"@cline/agents":u($,"packages/agents/src/index.ts"),"@cline/core":u($,"packages/core/src/index.ts"),"@cline/llms":u($,"packages/llms/src/index.ts"),"@cline/shared":u($,"packages/shared/src/index.ts"),"@cline/shared/storage":u($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":u($,"packages/shared/src/db/index.ts")};for(let[Z,W]of Object.entries(Q))if(Y0(W))J[Z]=W;for(let Z of["agents","core","llms","shared"]){let W=u($,"packages",Z),j=u(W,"package.json");if(!Y0(j))continue;try{let f=JSON.parse(Q2(j,"utf8"));if(typeof f.name!=="string"||!f.exports)continue;if(typeof f.exports==="string"){let X=u(W,f.exports);if(Y0(X))J[f.name]=X;continue}if(typeof f.exports!=="object")continue;for(let[X,Y]of Object.entries(f.exports)){let V=vG(W,Y);if(!V)continue;let H=X==="."?f.name:`${f.name}/${X.replace(/^\.\//,"")}`;J[H]=V}}catch{}}return J}function vG($,J){let Q=BQ(J);if(!Q)return null;let Z=U3($,Q);for(let W of Z)if(Y0(W))return W;return null}function BQ($,J=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(J.has($))return null;J.add($);let Q=$;for(let Z of gG){let W=BQ(Q[Z],J);if(W)return W}return null}function U3($,J){let Q=J.replace(/^\.\//,""),Z=[u($,J)];if(Q.startsWith("dist/")){let W=Q.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[u($,`${W}.ts`),u($,`${W}.tsx`),u($,`${W}.mts`),u($,`${W}.cts`),...Z]}return Z}function cG($){return Object.fromEntries(Object.entries($).sort(([J],[Q])=>Q.length-J.length))}function c4($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function J2($){if($.startsWith("@")){let[J,Q]=$.split("/",3);return Q?`${J}/${Q}`:$}return $.split("/",1)[0]??$}function uG($){let J=J2($);if($===J)return".";return`.${$.slice(J.length)}`}function R3($){return J2($).startsWith("@cline/")}function XQ($,J){let Q=J2(J),Z=E1($);while(!0){let W=u(Z,"node_modules",Q);if(Y0(W)||Y0(u(W,"package.json")))return!0;let j=u(Z,"..");if(j===Z)return!1;Z=j}}function G3($){return YQ($)!==null}function YQ($){try{return kG.resolve($)}catch{}return dG($)}function dG($){let J=J2($),Q=z3(J);if(!Q)return null;let Z=u(Q,"package.json");try{let W=JSON.parse(Q2(Z,"utf8")),j=uG($),f=j==="."&&typeof W.exports==="string"?W.exports:W.exports&&typeof W.exports==="object"&&Object.hasOwn(W.exports,j)?W.exports[j]:void 0,X=BQ(f)??(j==="."&&typeof W.main==="string"?W.main:null);if(!X)return null;let Y=u(Q,X),V=[Y,...U3(Q,X).filter((H)=>H!==Y)];for(let H of V)if(Y0(H))return H;return null}catch{return null}}function lG(){let $=[D3],J=process.env.CLINE_WRAPPER_PATH?.trim();if(J)$.push(E1(E1(J)));let Q=process.execPath?.trim();if(Q)$.push(E1(Q));return[...new Set($.map((Z)=>u(Z)))]}function pG($,J){let Q=$;while(!0){let Z=u(Q,"package.json");if(Y0(Z))try{if(JSON.parse(Q2(Z,"utf8")).name===J)return Q}catch{}let W=u(Q,"node_modules",J,"package.json");if(Y0(W))return E1(W);let j=u(Q,"..");if(j===Q)return null;Q=j}}function z3($){for(let J of lG()){let Q=pG(J,$);if(Q)return Q}return null}function rG($){let Q=E1($);for(let Z=0;Z<4;Z++){let W=u(Q,"package.json");if(Y0(W))try{let f=JSON.parse(Q2(W,"utf8"));return f!=null&&typeof f==="object"&&"cline"in f}catch{return!1}let j=u(Q,"..");if(j===Q)return!1;Q=j}return!1}function L3($,J){let Q=J.startsWith("file:")?F3(J):bG(J)?J:u(E1($),J);if(Y0(Q)&&l2.has(p2(Q)))return Q;for(let Z of l2){let W=`${Q}${Z}`;if(Y0(W))return W}for(let Z of l2){let W=u(Q,`index${Z}`);if(Y0(W))return W}return null}function _3($){let J=new Set,Q=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Z of Q)for(let W of $.matchAll(Z)){let j=W[1];if(j)J.add(j)}return[...J]}function iG($){return p2($)!==".ts"}function O3($,J,Q=new Set){if(Q.has($)||!Y0($))return;if(Q.add($),!l2.has(p2($)))return;let Z=Q2($,"utf8"),W=iG($);for(let j of _3(Z)){if(j.startsWith("node:")||HQ.has(j))continue;if(c4(j)){if(!W)continue;if(Object.hasOwn(fQ,j)||Object.hasOwn(fQ,J2(j))||XQ($,j)||R3(j)&&G3(j)||J&&G3(j))continue;throw Error(`Cannot find module '${J2(j)}'`)}let f=L3($,j);if(f)O3(f,J,Q)}}function T3($,J=new Set,Q=new Set){if(J.has($)||!Y0($))return Q;if(J.add($),!l2.has(p2($)))return Q;let Z=Q2($,"utf8");for(let W of _3(Z)){if(Q.add(W),c4(W))continue;let j=L3($,W);if(j)T3(j,J,Q)}return Q}function nG($,J){let Q=VQ($),Z={},W=T3($),j=new Set(xG);for(let[f,X]of Object.entries(fQ)){try{Q.resolve(f);continue}catch{}Z[f]=X}for(let f of W)if(c4(f)&&(R3(f)||J))j.add(f);for(let f of j){if(Object.hasOwn(Z,f)||XQ($,f))continue;let X=YQ(f);if(X)Z[f]=X}if(!J)return Z;for(let f of W){if(!c4(f)||Object.hasOwn(Z,f)||XQ($,f)||f.startsWith("node:")||HQ.has(f))continue;let X=YQ(f);if(X)Z[f]=X}return Z}function aG($){let J=p2($);return J===".ts"||J===".tsx"||J===".mts"||J===".cts"}var A$;function sG(){if(A$!==void 0)return A$;let $=z3("jiti");if(!$)return A$=null,null;let J=u($,"dist","babel.cjs");if(!Y0(J))return A$=null,null;try{let Z=VQ(J)(J);A$=typeof Z==="function"?Z:null}catch{A$=null}return A$}async function M3($,J={}){let Q=!rG($);O3($,Q);let Z=nG($,Q),W=cG(Z),j=await import("jiti"),f=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!f)throw Error("Unable to load jiti");let X=Object.entries(W).filter(([,B])=>aG(B)).map(([B])=>B),Y=sG(),V=Y?(B)=>Y({...B,interopDefault:!0}):void 0;return await f($,{alias:W,cache:J.useCache,requireCache:J.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...HQ],transformModules:X,tryNative:!1,...V?{transform:V}:{}}).import($,{})}function q3($,J){if(!$)return!0;if($.providerIds?.length){if(!J?.providerId||!$.providerIds.includes(J.providerId))return!1}if($.modelIds?.length){if(!J?.modelId||!$.modelIds.includes(J.modelId))return!1}return!0}function P3($){return typeof $==="object"&&$!==null}function AQ($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function eG($,J){if(!P3($.manifest))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);if(!AQ($.manifest.capabilities))throw Error(`Invalid plugin module at ${J}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${J}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!AQ($.manifest.providerIds))throw Error(`Invalid plugin module at ${J}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!AQ($.manifest.modelIds))throw Error(`Invalid plugin module at ${J}: manifest.modelIds must be a string array when provided`)}function $F($,J){if(!P3($))throw Error(`Invalid plugin module at ${J}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${J}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);eG($,J)}async function KQ($,J={}){let Q=oG(J.cwd??process.cwd(),$),Z=await M3(Q,{useCache:J.useCache}),W=J.exportName??"plugin",j=Z.default??Z[W];$F(j,Q);let f=j,X=f.setup,Y=X?(V,H)=>{let B={...J.session,...H.session},A={...H,session:Object.keys(B).length>0?B:void 0,client:J.client??H.client,user:J.user??H.user,workspaceInfo:J.workspaceInfo??H.workspaceInfo,automation:J.automation??H.automation,logger:J.logger??H.logger,telemetry:J.telemetry??H.telemetry};return X(V,A)}:void 0;return{...f,manifest:tG(f.manifest),setup:Y}}async function N3($,J={}){return(await r2($,J)).plugins}async function r2($,J={}){let Q=[],Z=[],W=new Map,j=0;for(let X of $)try{let Y=await KQ(X,J);if(!q3(Y.manifest,J))continue;let V=W.get(Y.name);if(V)Z.push({type:"duplicate_plugin_override",pluginName:Y.name,pluginPath:X,overriddenPluginPath:V.pluginPath,message:`Plugin "${Y.name}" from ${X} overrides ${V.pluginPath}`});W.set(Y.name,{plugin:Y,pluginPath:X,order:j++})}catch(Y){let V=Y instanceof Error?Y.message:String(Y);Q.push({pluginPath:X,phase:"load",message:V,stack:Y instanceof Error?Y.stack:void 0})}let f=[...W.values()].sort((X,Y)=>X.order-Y.order);return{plugins:f.map((X)=>X.plugin),pluginPaths:f.map((X)=>X.pluginPath),failures:Q,warnings:Z}}import{existsSync as DQ}from"node:fs";import{createRequire as E3}from"node:module";import{dirname as d4,join as Z2}from"node:path";import{fileURLToPath as XF}from"node:url";import{spawn as JF}from"node:child_process";import{basename as QF}from"node:path";import{augmentNodeCommandForDebug as ZF,withResolvedClineBuildEnv as WF}from"@cline/shared";function w3($){if($ instanceof Error)return $;return Error(String($))}var jF="CLINE_JS_RUNTIME_PATH";function S3($){let J=$?.trim();if(!J)return!1;let Q=QF(J).toLowerCase();return Q==="node"||Q==="node.exe"||Q==="bun"||Q==="bun.exe"}function C3($={}){let J=$.env??process.env,Q=$.runtimeExecutable?.trim()||J[jF]?.trim();if(Q)return Q;let Z=$.execPath?.trim()||process.execPath;if(S3(Z))return Z;for(let W of[J.BUN_EXEC_PATH,J.npm_node_execpath,J.NODE]){let j=W?.trim();if(j&&S3(j))return j}return"node"}function fF($,J={}){let Q=C3({env:J.env,execPath:J.execPath,runtimeExecutable:J.runtimeExecutable});return ZF([Q,...$],{env:J.env,execArgv:J.execArgv,debugRole:J.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class u4{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let J=this.pending.get($);if(!J)return;if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);return J}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],J=fF($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Q=JF(J[0]??C3(this.options),J.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:WF(process.env),windowsHide:!0});this.process=Q;let Z="",W=(j)=>{let f=Z+j;Z=f.length>4000?f.slice(-4000):f};Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(j)=>{W(j)}),Q.on("message",(j)=>{this.onMessage(j)}),Q.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${w3(j).message}`))}),Q.on("exit",(j,f)=>{this.process=null;let X=Z.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(f)})${X?`: ${X}`:""}`))})}async call($,J,Q={}){this.start();let Z=this.process;if(!Z||Z.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let W=`req_${++this.requestCounter}`,j={type:"call",id:W,method:$,args:J};return await new Promise((f,X)=>{let Y={resolve:(V)=>f(V),reject:X};if((Q.timeoutMs??0)>0)Y.timeout=setTimeout(()=>{this.clearPendingRequest(W),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${Q.timeoutMs}ms: ${$}`))},Q.timeoutMs);this.pending.set(W,Y),Z.send(j,(V)=>{if(!V)return;let H=this.clearPendingRequest(W);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${w3(V).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((J)=>{let Q=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}J()},300);$.once("exit",()=>{clearTimeout(Q),J()});try{$.kill("SIGTERM")}catch{clearTimeout(Q),J()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let J=this.clearPendingRequest($.id);if(!J)return;if($.ok){J.resolve($.result);return}J.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[J,Q]of this.pending.entries()){if(this.pending.delete(J),Q.timeout)clearTimeout(Q.timeout);Q.reject($)}}}function YF($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function i2($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function VF(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function HF(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Q=E3($).resolve(`${VF()}/package.json`),Z=Z2(d4(Q),"extensions","plugin-sandbox-bootstrap.js");return DQ(Z)?Z:void 0}catch{return}}function BF(){let $=process.execPath?.trim();if(!$)return;let J=Z2(d4(d4($)),"extensions","plugin-sandbox-bootstrap.js");return DQ(J)?J:void 0}function AF(){let $=d4(XF(import.meta.url)),J=E3(import.meta.url),Q=[Z2($,"plugin-sandbox-bootstrap.js"),Z2($,"extensions","plugin-sandbox-bootstrap.js"),Z2($,"agents","plugin-sandbox-bootstrap.js"),HF(),BF()];for(let j of Q.filter((f)=>typeof f==="string"))if(DQ(j))return{file:j};let Z=Z2($,"plugin-sandbox-bootstrap.ts"),W="jiti";try{W=J.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(W)});`,`const jiti = createJiti(${JSON.stringify(Z)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Z)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
47
- `)}}var GQ=AF();function FQ($,J,Q){if(typeof $==="number"&&$>0)return $;if(Q){let Z=process.env[Q];if(Z){let W=Number(Z);if(Number.isInteger(W)&&W>0)return W}}return J}async function W2($){let J=new u4({name:"plugin-sandbox",..."file"in GQ?{bootstrapFile:GQ.file}:{bootstrapScript:GQ.script},onEvent:$.onEvent}),Q=FQ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Z=FQ($.hookTimeoutMs,3000),W=FQ($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},f,X=()=>{return f??=J.call("initialize",j,{timeoutMs:Q}).finally(()=>{f=void 0}),f},Y;try{Y=await J.call("initialize",j,{timeoutMs:Q})}catch(B){throw await J.shutdown().catch(()=>{}),B}let V=Y.plugins.map(YF);return{extensions:V.map((B)=>{let A={name:B.name,__clinePluginPath:B.pluginPath,manifest:B.manifest,setup:(K)=>{KF(K,J,B,W,X),GF(K,J,B,W,X),FF(K,J,B,W,X),UF(K,J,B,W,X),DF(K,B)}};return A.hooks=zF(J,B,Z,X),A}),failures:Y.failures,pluginPaths:V.map((B)=>B.pluginPath),shutdown:async()=>{await J.shutdown()},warnings:Y.warnings}}function KF($,J,Q,Z,W){for(let j of Q.contributions?.tools??[]){let f={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(X,Y)=>{try{return await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}catch(V){if(!i2(V))throw V;return await W(),await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}}};$.registerTool(f)}}function GF($,J,Q,Z,W){for(let j of Q.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(f)=>{try{return await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}catch(X){if(!i2(X))throw X;return await W(),await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}}})}function FF($,J,Q,Z,W){for(let j of Q.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}catch(f){if(!i2(f))throw f;return await W(),await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}}:j.content??""})}function DF($,J){for(let Q of J.contributions?.providers??[])$.registerProvider({name:Q.name,description:Q.description,metadata:Q.metadata});for(let Q of J.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Q.eventType,source:Q.source,description:Q.description,attributesSchema:Q.attributesSchema,payloadSchema:Q.payloadSchema,examples:Q.examples,metadata:Q.metadata});for(let Q of J.contributions?.mcpServers??[])$.registerMcpServer(Q)}function UF($,J,Q,Z,W){for(let j of Q.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(f){try{let X=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return y3(X)?X:f}catch(X){if(!i2(X))throw X;await W();let Y=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return y3(Y)?Y:f}}})}function y3($){return Array.isArray($)&&$.every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&("content"in J))}function RF($,J,Q,Z,W){return async(j)=>{try{return await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}catch(f){if(!i2(f))throw f;return await W(),await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}}}function zF($,J,Q,Z){let W={};for(let j of J.hooks??[])W[j]=RF($,J.pluginId,j,Q,Z);return Object.keys(W).length>0?W:void 0}var RQ="package.json",PF="package";function zQ($){return MF($)}function LQ($){return TF($)}function NF($){try{return r4($)&&_F($).isDirectory()}catch{return!1}}function _Q($){let J=[],Q=new Set;for(let Z of $){let W=p4(Z);if(Q.has(W))continue;Q.add(W),J.push(W)}return J}function h3($){let J=_Q($);return WQ(J)}function k3($){return zQ($).flatMap((J)=>LQ(J)).filter((J)=>r4(J))}function wF($,J){let Q=[];for(let Z of $)try{Q.push(...b3([Z],J))}catch{}return Q}function UQ($){return typeof $==="object"&&$!==null}function SF($){try{let J=JSON.parse(LF(i4($,RQ),"utf8"));if(!UQ(J)||!UQ(J.cline))return[];let Q=J.cline.plugins;if(!Array.isArray(Q))return[];let Z=[];for(let W of Q){if(typeof W==="string"){Z.push(W);continue}if(!UQ(W)||!Array.isArray(W.paths))continue;for(let j of W.paths)if(typeof j==="string")Z.push(j)}return Z}catch{return[]}}function I3($,J){let Q=p4(J);return SF($).some((Z)=>p4($,Z)===Q)}function CF($,J){return OF($)===PF&&r4(i4(l4($),RQ))&&I3(l4($),J)}function yF($){let J=p4($),Q=[],Z=l4(J);while(!0){if(CF(Z,J)){Q.push(Z);break}if(r4(i4(Z,RQ))){if(I3(Z,J))Q.push(Z);break}let W=l4(Z);if(W===Z)break;Z=W}return _Q(Q)}function n2($={}){let J=$.cwd??process.cwd(),Q=k3($.workspacePath),Z=b3($.pluginPaths??[],J);return h3([...Z,...Q])}function EF($={}){let J=$.cwd??process.cwd(),Q=k3($.workspacePath),Z=wF($.pluginPaths??[],J);return h3([...Z,...Q])}function a2($){let J=[];for(let Q of $)for(let Z of yF(Q)){let W=i4(Z,qF);if(NF(W))J.push(W)}return _Q(J)}function x3($={}){return a2(EF($))}async function n4($={}){let J=n2($);if(J.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Z=await r2(J,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Z.plugins,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}let Q=await W2({pluginPaths:J,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Q.extensions??[],shutdown:Q.shutdown,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}var a4="SKILL.md",vF="managed.json",cF=new Set([".md",".markdown",".txt"]);function PQ($){return $.trim().toLowerCase()}function j2($){let J=$;return J?.code==="ENOENT"||J?.code==="EACCES"||J?.code==="EPERM"||J?.code==="ELOOP"}function o4($){return cF.has(s4($).toLowerCase())}function v3($){let J=[],Q=new Set;for(let Z of $){let W=s2(Z);if(Q.has(W))continue;Q.add(W),J.push(Z)}return J}function uF($){let J=[...$?.directories??EQ($?.workspacePath)];if($?.pluginSkillDirectories)J.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)J.push(...x3({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return v3(J)}async function NQ($){try{let J=await TQ($,{withFileTypes:!0}),Q=[];for(let Z of J){if(!Z.isDirectory())continue;let W=q0($,Z.name),j=q0(W,vF);try{let f=await bF(j,"utf8"),X=JSON.parse(f);if(X&&typeof X==="object")Q.push(W)}catch(f){if(j2(f))continue;if(f?.name==="SyntaxError")continue;throw f}}return Q.sort((Z,W)=>Z.localeCompare(W))}catch(J){if(j2(J))return[];throw J}}function wQ($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q;try{let j=mF.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}catch(j){let f=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:f}}}function t4($,J,Q){if($===void 0||$===null){if(Q)throw Error(`Missing required frontmatter field '${J}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${J}' must be a string.`);let Z=$.trim();if(!Z&&Q)throw Error(`Frontmatter field '${J}' cannot be empty.`);return Z||void 0}function f2($,J){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${J}' must be a boolean.`);return $}function dF($,J){if(B1($.filePath).toLowerCase()!==g3.toLowerCase())return B1($.filePath,s4($.filePath));if(J&&s2($.filePath)===s2(J,g3))return"Workspace AGENTS.md";if(s2($.filePath)===s2(kF()))return"Global AGENTS.md";return B1($.filePath,s4($.filePath))}function SQ($,J){let{data:Q,body:Z,parseError:W}=wQ($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in skill file.");let X=t4(Q.name,"name",!1)??J.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:t4(Q.description,"description",!1),disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function CQ($,J){let{data:Q,body:Z,parseError:W}=wQ($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in rule file.");let f=t4(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing rule name.");return{name:f,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function yQ($,J){let{data:Q,body:Z,parseError:W}=wQ($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in workflow file.");let f=t4(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing workflow name.");return{name:f,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function EQ($){return xF($)}function bQ($){return IF($)}function hQ($){return gF($)}async function c3($){if(B1($)===".cline"){let J=await NQ($);return(await Promise.all(J.map((Z)=>c3(q0(Z,MQ))))).flat()}try{let J=await TQ($,{withFileTypes:!0}),Q=[];for(let Z of J){if(Z.isFile()&&Z.name===a4){Q.push({directoryPath:$,fileName:Z.name,filePath:q0($,Z.name)});continue}let W=q0($,Z.name);if(Z.isDirectory()||Z.isSymbolicLink()&&await OQ(W).then((f)=>f.isDirectory()).catch((f)=>{if(j2(f))return!1;throw f}))Q.push({directoryPath:W,fileName:a4,filePath:q0(W,a4)})}return Q}catch(J){if(j2(J))return[];throw J}}async function e4($){if(B1($)===".cline"){let J=await NQ($);return(await Promise.all(J.map((Z)=>e4(q0(Z,"rules.md"))))).flat()}try{if((await OQ($)).isFile())return[{directoryPath:hF($),fileName:B1($),filePath:$}]}catch(J){if(!j2(J))throw J}try{let Q=(await TQ($,{withFileTypes:!0})).filter((W)=>W.isFile()&&o4(W.name)).map((W)=>({directoryPath:$,fileName:W.name,filePath:q0($,W.name)})),Z=q0($,"AGENTS.md");try{if((await OQ(Z)).isFile()){if(!Q.some((f)=>f.fileName==="AGENTS.md"))Q.push({directoryPath:$,fileName:"AGENTS.md",filePath:Z})}}catch{}return Q}catch(J){if(j2(J))return[];throw J}}async function lF($){if(B1($)===".cline"){let J=await NQ($);return(await Promise.all(J.map((Z)=>e4(q0(Z,qQ))))).flat()}return e4($)}function kQ($){let J=uF($),Q=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Q?v3([...J,Q]):J,discoverFiles:c3,includeFile:(Z)=>Z===a4,parseFile:(Z)=>SQ(Z.content,B1(Z.directoryPath)),resolveId:(Z)=>PQ(Z.name)}}function IQ($){let J=$?.directories??bQ($?.workspacePath),Q=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Q?[...J,Q]:J,discoverFiles:e4,includeFile:(Z,W)=>Z===".clinerules"||o4(Z)||o4(W),parseFile:(Z)=>CQ(Z.content,dF(Z,$?.workspacePath)),resolveId:(Z)=>PQ(Z.name)}}function xQ($){let J=$?.directories??hQ($?.workspacePath),Q=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Q?[...J,Q]:J,discoverFiles:lF,includeFile:(Z)=>o4(Z),parseFile:(Z)=>yQ(Z.content,B1(Z.filePath,s4(Z.filePath))),resolveId:(Z)=>PQ(Z.name)}}function u3($){let J=[kQ($?.skills),IQ($?.rules),xQ($?.workflows)];return new d2(J,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as d3}from"@cline/shared";function pF($,J){if($.description?.trim())return d3($.description,".");if(J==="workflow")return;return d3($.instructions,".")}function rF($){return $.disabled!==!0}function l3($,J){return[...$.getSnapshot(J).entries()].map(([Q,Z])=>({id:Q,record:Z})).filter(({record:Q})=>rF(Q.item)).map(({id:Q,record:Z})=>({id:Q,name:Z.item.name,instructions:Z.item.instructions,description:pF(Z.item,J),kind:J})).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function o2($){let J=new Map;for(let Q of[...l3($,"workflow"),...l3($,"skill")])if(!J.has(Q.name))J.set(Q.name,Q);return[...J.values()].sort((Q,Z)=>Q.name.localeCompare(Z.name))}function p3($,J){if(!$.startsWith("/")||$.length<2)return $;let Q=$.match(/^\/(\S+)/);if(!Q)return $;let Z=Q[1];if(!Z)return $;let W=Z.length+1,j=$.slice(W),f=o2(J).find((X)=>X.name===Z);return f?`${f.instructions}${j}`:$}function r3($){return $.disabled!==!0}function $6($){if($.length===0)return"";return`
46
+ </html>`;function UW($){let J="";for(let Q=0;Q<$.length;Q+=1)J+=String.fromCharCode($[Q]??0);return btoa(J).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function hA($){let Q=new TextEncoder().encode($),Z=await crypto.subtle.digest("SHA-256",Q);return new Uint8Array(Z)}function kA($=32){let J=new Uint8Array($);return crypto.getRandomValues(J),UW(J)}async function L4(){let $=kA(),J=UW(await hA($));return{verifier:$,challenge:J}}function _4($){return $.endsWith("/")?$.slice(0,-1):$}function H$($,J){return new URL(J,`${_4($)}/`).toString()}function n$($,J={}){let Q=$.trim();if(!Q)return{};try{let Z=new URL(Q);return{code:Z.searchParams.get("code")??void 0,state:Z.searchParams.get("state")??void 0,provider:J.includeProvider?Z.searchParams.get("provider")??void 0:void 0}}catch{}if(J.allowHashCodeState&&Q.includes("#")){let[Z,W]=Q.split("#",2);return{code:Z||void 0,state:W||void 0}}if(Q.includes("code=")){let Z=new URLSearchParams(Q);return{code:Z.get("code")??void 0,state:Z.get("state")??void 0,provider:J.includeProvider?Z.get("provider")??void 0:void 0}}return{code:Q}}function IA($){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 R0($){if(!$)return null;try{let J=$.split(".");if(J.length!==3)return null;let Q=J[1];if(!Q)return null;let Z=Q.replace(/-/g,"+").replace(/_/g,"/"),W=Z.padEnd(Z.length+(4-Z.length%4)%4,"="),j=IA(W);if(!j)return null;return JSON.parse(j)}catch{return null}}function a$($){try{let J=JSON.parse($),Q=J.error,Z=typeof Q==="string"?Q:Q&&typeof Q==="object"&&typeof Q.type==="string"?Q.type:void 0,W=typeof J.error_description==="string"?J.error_description:typeof J.message==="string"?J.message:Q&&typeof Q==="object"&&typeof Q.message==="string"?Q.message:void 0;return{code:Z,message:W}}catch{return{}}}function s$($,J){return Date.now()>=$.expires-J}async function o$($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let J,Q,Z=$.onManualCodeInput().then((j)=>{J=j,$.cancelWait()}).catch((j)=>{Q=j instanceof Error?j:Error(String(j)),$.cancelWait()}),W=await $.waitForCallback();if(Q)throw Q;if(W?.code||W?.error)return{code:W.code,state:W.state,provider:W.provider,error:W.error};if(J)return n$(J,$.parseOptions);if(await Z,Q)throw Q;if(J)return n$(J,$.parseOptions);return{}}var O4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},_W={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},S5="https://api.workos.com",xA="/auth",RW=Array.from({length:11},($,J)=>48801+J),gA=300000,mA=30000,t$=30000,vA=300,cA=5;class w1 extends Error{status;errorCode;constructor($,J){super($);this.name="ClineOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function uA($){let J=Date.parse($);if(Number.isNaN(J))throw Error(`Invalid expiresAt value: ${$}`);return J}function C5($,J,Q={}){let Z=$.userInfo.clineUserId??Q.accountId,W=$.refreshToken??Q.refresh;if(!W)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:W,expires:uA($.expiresAt),accountId:Z??void 0,email:$.userInfo.email||Q.email,metadata:{provider:J,tokenType:$.tokenType,userInfo:$.userInfo}}}async function y5($){if(!$)return{};return typeof $==="function"?await $():$}function zW($,J){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return J;return Math.floor($)}async function LW($){await new Promise((J)=>setTimeout(J,$))}function E5($,J){if(!$.success||!$.data?.accessToken)throw Error(J);return $.data}async function OW($,J){let Q=await fetch(H$(S5,_W.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(J?.requestTimeoutMs??t$)}),Z=await Q.json().catch(()=>({}));if(!Q.ok)throw new w1(`Device authorization failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error});if(!Z.device_code||!Z.user_code||!Z.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Z.device_code,userCode:Z.user_code,verificationUri:Z.verification_uri,verificationUriComplete:Z.verification_uri_complete,expiresInSeconds:zW(Z.expires_in,vA),pollIntervalSeconds:zW(Z.interval,cA)}}async function TW($){let J=Date.now()+$.expiresInSeconds*1000,Q=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=J){let Z=await fetch(H$($.workosApiBaseUrl,_W.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),W=await Z.json().catch(()=>({}));if(Z.ok){if(!W.access_token||!W.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:W.access_token,refreshToken:W.refresh_token,tokenType:W.token_type??"Bearer"}}switch(W.error){case"authorization_pending":{await LW(Q*1000);break}case"slow_down":{Q+=1,await LW(Q*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new w1(W.error_description||"WorkOS authorization failed",{status:Z.status,errorCode:W.error});default:throw new w1(`WorkOS token polling failed: ${Z.status}${W.error_description?` - ${W.error_description}`:""}`,{status:Z.status,errorCode:W.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function MW($,J,Q){let Z={accessToken:$.accessToken,refreshToken:$.refreshToken},W=await fetch(H$(J.apiBaseUrl,O4.register),{method:"POST",headers:{"Content-Type":"application/json",...await y5(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??t$)});if(!W.ok){let f=await W.text().catch(()=>""),X=a$(f);throw new w1(`Token registration failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return C5(E5(j,"Invalid token exchange response"),Q??J.provider)}async function dA($,J,Q,Z){let W={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:J,provider:Z??Q.provider},j=await fetch(H$(Q.apiBaseUrl,O4.token),{method:"POST",headers:{"Content-Type":"application/json",...await y5(Q.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(Q.requestTimeoutMs??t$)});if(!j.ok){let X=await j.text().catch(()=>""),Y=a$(X);throw new w1(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let f=await j.json();return C5(E5(f,"Invalid token exchange response"),Z??Q.provider)}async function b5($){M1($.telemetry,$.provider??"cline");let J=$.useWorkOSDeviceAuth??!0,Q=$.callbackPorts?.length?$.callbackPorts:RW,Z=$.callbackPath??xA,W=J?null:await Y1({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=W?.callbackUrl||`http://127.0.0.1:${Q[0]??RW[0]}${Z}`;try{let f;if(J){let X=w5().workOsClientId,Y=await OW(X,$);$.callbacks.onAuth({url:Y.verificationUriComplete??Y.verificationUri,instructions:`Enter this code in your browser: ${Y.userCode}`});let V=await TW({clientId:X,deviceCode:Y.deviceCode,expiresInSeconds:Y.expiresInSeconds,initialPollIntervalSeconds:Y.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??t$,workosApiBaseUrl:S5,onProgress:$.callbacks.onProgress});f=await MW(V,$,$.provider)}else{let X=new URL(H$($.apiBaseUrl,O4.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",j),X.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let Y,V=$.provider,H=await o$({waitForCallback:W?.waitForCallback??(async()=>null),cancelWait:W?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(Y=H.code,V=H.provider??V,!Y){let B=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=n$(B,{includeProvider:!0});Y=A.code,V=A.provider??V}if(!Y)throw Error("Missing authorization code");f=await dA(Y,j,$,V)}return q1($.telemetry,$.provider??"cline"),N1($.telemetry,{id:f.accountId,email:f.email,provider:$.provider??"cline"}),f}catch(f){throw P1($.telemetry,$.provider??"cline",f instanceof Error?f.message:String(f)),f}finally{W?.close()}}async function lA($){return await OW(w5().workOsClientId,$)}async function pA($){let J=$.provider??"cline";M1($.telemetry,J);try{let Q=await TW({clientId:w5().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??t$,workosApiBaseUrl:S5}),Z=await MW(Q,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return q1($.telemetry,J),N1($.telemetry,{id:Z.accountId,email:Z.email,provider:J}),Z}catch(Q){throw P1($.telemetry,J,Q instanceof Error?Q.message:String(Q)),Q}}async function qW($,J){let Q=await fetch(H$(J.apiBaseUrl,O4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await y5(J.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(J.requestTimeoutMs??t$)});if(!Q.ok){let j=await Q.text().catch(()=>""),f=a$(j);throw new w1(`Token refresh failed: ${Q.status}${f.message?` - ${f.message}`:""}`,{status:Q.status,errorCode:f.code})}let Z=await Q.json(),W=$.metadata?.provider??J.provider;return C5(E5(Z,"Invalid token refresh response"),W,$)}async function h5($,J,Q){if(!$)return null;let Z=Q?.refreshBufferMs??gA,W=Q?.retryableTokenGraceMs??mA;if(Q?.forceRefresh!==!0&&!s$($,Z))return $;try{return await qW($,J)}catch(f){if(f instanceof w1&&f.isLikelyInvalidGrant())return Y$(J.telemetry,J.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}F0();import{nanoid as rA}from"nanoid";var e={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class T4 extends Error{status;errorCode;constructor($,J){super($);this.name="OpenAICodexOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function iA($,J,Q=e.redirectUri){let Z=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:$,code_verifier:J,redirect_uri:Q}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!Z.ok)return{type:"failed"};let W=await Z.json();if(!W.access_token||!W.refresh_token||typeof W.expires_in!=="number")return{type:"failed"};return{type:"success",access:W.access_token,refresh:W.refresh_token,expires:Date.now()+W.expires_in*1000,email:W.email,idToken:W.id_token}}async function nA($){try{let J=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!J.ok){let Z=await J.text().catch(()=>""),W=a$(Z);throw new T4(`Token refresh failed: ${J.status}${W.message?` - ${W.message}`:""}`,{status:J.status,errorCode:W.code})}let Q=await J.json();if(!Q.access_token||!Q.refresh_token||typeof Q.expires_in!=="number")return{type:"failed"};return{type:"success",access:Q.access_token,refresh:Q.refresh_token,expires:Date.now()+Q.expires_in*1000,email:Q.email,idToken:Q.id_token}}catch(J){if(J instanceof T4)throw J;return{type:"failed"}}}async function aA($="pi"){let{verifier:J,challenge:Q}=await L4(),Z=rA(32),W=new URL(e.authorizationEndpoint);return W.searchParams.set("response_type","code"),W.searchParams.set("client_id",e.clientId),W.searchParams.set("redirect_uri",e.redirectUri),W.searchParams.set("scope",e.scopes),W.searchParams.set("code_challenge",Q),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("state",Z),W.searchParams.set("id_token_add_organizations","true"),W.searchParams.set("codex_cli_simplified_flow","true"),W.searchParams.set("originator",$),{verifier:J,state:Z,url:W.toString()}}function sA(){try{let $=new URL(e.redirectUri),J=$.port.length>0?Number.parseInt($.port,10):e.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(J)?J:e.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function oA($,J){let Q=J?R0(J):R0($),Z=Q?Q:R0($),j=Z?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let f=Z?.organizations;if(Array.isArray(f)&&f.length>0){let Y=f[0];if(typeof Y?.id==="string"&&Y.id.length>0)return Y.id}let X=Z?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function PW($,J){let Q=oA($.access,$.idToken)??J?.accountId;if(!Q)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||J?.refresh||"",expires:$.expires,accountId:Q,email:$.email??J?.email,metadata:{...J?.metadata??{},provider:"openai-codex"}}}async function k5($){M1($.telemetry,"openai-codex");let J=sA(),{verifier:Q,state:Z,url:W}=await aA($.originator),j=await Y1({host:J.host,ports:[J.port],callbackPath:J.callbackPath,expectedState:Z});$.onAuth({url:W,instructions:"Continue the authentication process in your browser."});let f;try{let X=await o$({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Z)throw Error("State mismatch");if(f=X.code,!f){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=n$(H,{allowHashCodeState:!0});if(B.state&&B.state!==Z)throw Error("State mismatch");f=B.code}if(!f)throw Error("Missing authorization code");let Y=await iA(f,Q,J.redirectUri);if(Y.type!=="success")throw Error("Token exchange failed");let V=PW(Y);return q1($.telemetry,"openai-codex"),N1($.telemetry,{id:V.accountId,email:V.email,provider:"openai-codex"}),V}catch(X){throw P1($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{j.close()}}async function NW($,J){let Q=await nA($);if(Q.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Z=PW(Q,J);if(!Z.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Z}async function I5($,J){if(!$)return null;let Q=J?.refreshBufferMs??e.refreshBufferMs,Z=J?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(J?.forceRefresh!==!0&&!s$($,Q))return $;try{return await NW($.refresh,$)}catch(j){if(j instanceof T4&&j.isLikelyInvalidGrant())return Y$(J?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}F0();import{nanoid as wW}from"nanoid";class x5{ttlMs;maxEntries;entries=new Map;constructor($,J){this.ttlMs=$;this.maxEntries=J}get($,J=Date.now()){this.pruneExpired(J);let Q=this.entries.get($);if(!Q)return;return this.entries.delete($),this.entries.set($,Q),Q.value}set($,J,Q=Date.now(),Z=this.ttlMs){this.pruneExpired(Q),this.entries.delete($);while(this.entries.size>=this.maxEntries){let W=this.entries.keys().next().value;if(W===void 0)break;this.entries.delete(W)}this.entries.set($,{value:J,expiresAt:Q+Z})}pruneExpired($){for(let[J,Q]of this.entries)if(Q.expiresAt<=$)this.entries.delete(J)}}var tA="a8331954c0cf48ba99b5dd223a14c6ea",eA="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",$K="openid offline_access",m5="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",JK="c1aba3deed5740659981a752714eba33",QK="https://login-ext.identity.oraclecloud.com",ZK="openid offline_access",v5="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm";var WK="/auth/oca",jK=Array.from({length:11},($,J)=>48801+J),fK=300000,XK=30000,SW=30000,YK=600000;class M4 extends Error{status;errorCode;constructor($,J){super($);this.name="OcaOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var S1={internal:{clientId:tA,idcsUrl:eA,scopes:$K,baseUrl:m5},external:{clientId:JK,idcsUrl:QK,scopes:ZK,baseUrl:v5}},m2=new Map,VK=86400000,HK=300000,BK=32,g5=new x5(VK,BK);function CW($){if(typeof $==="function")return $();return $??"internal"}function yW($){return{internal:{clientId:$?.internal?.clientId??S1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??S1.internal.idcsUrl,scopes:$?.internal?.scopes??S1.internal.scopes,baseUrl:$?.internal?.baseUrl??S1.internal.baseUrl},external:{clientId:$?.external?.clientId??S1.external.clientId,idcsUrl:$?.external?.idcsUrl??S1.external.idcsUrl,scopes:$?.external?.scopes??S1.external.scopes,baseUrl:$?.external?.baseUrl??S1.external.baseUrl}}}function AK($=Date.now()){let J=$-YK;for(let[Q,Z]of m2.entries())if(Z.createdAt<J)m2.delete(Q)}function KK($,J,Q){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let W=R0(J)?.exp;if(typeof W==="number"&&W>0)return W*1000;let f=R0(Q)?.exp;if(typeof f==="number"&&f>0)return f*1000;return Date.now()+3600000}function EW($,J,Q){let Z=$.access_token;if(!Z)throw Error("Token response did not include an access token");let W=$.refresh_token??Q?.refresh;if(!W)throw Error("Token response did not include a refresh token");let j=R0($.id_token),f=R0(Z),X=j?.sub??f?.sub,Y=j?.email??f?.email;return{access:Z,refresh:W,expires:KK($,Z,$.id_token),accountId:X??Q?.accountId,email:Y??Q?.email,metadata:{...Q?.metadata??{},provider:"oca",mode:J,subject:X,idToken:$.id_token}}}async function bW($,J){let Q=_4($),Z=g5.get(Q);if(Z)return Z;let W=`${Q}/.well-known/openid-configuration`,j=await fetch(W,{method:"GET",signal:AbortSignal.timeout(J)});if(!j.ok){let Y=`${Q}/oauth2/v1/token`;return g5.set(Q,Y,Date.now(),HK),Y}let X=(await j.json()).token_endpoint||`${Q}/oauth2/v1/token`;return g5.set(Q,X),X}function hW($){return{code:$.error,message:$.error_description}}async function GK($){let J=m2.get($.state);if(!J)throw Error("No PKCE verifier found for this state");m2.delete($.state);let Q=$.mode==="external"?$.config.external:$.config.internal,Z=await bW(Q.idcsUrl,$.requestTimeoutMs),W=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:J.redirectUri,client_id:Q.clientId,code_verifier:J.verifier}),j=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,signal:AbortSignal.timeout($.requestTimeoutMs)}),f=await j.json();if(!j.ok){let Y=hW(f);throw new M4(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let X=R0(f.id_token);if(!f.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==J.nonce)throw Error("OIDC nonce verification failed");return EW(f,$.mode)}function FK($){let J=$.mode==="external"?$.config.external:$.config.internal,Q=new URL(`${_4(J.idcsUrl)}/oauth2/v1/authorize`);return Q.searchParams.set("client_id",J.clientId),Q.searchParams.set("response_type","code"),Q.searchParams.set("scope",J.scopes),Q.searchParams.set("code_challenge",$.challenge),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",$.callbackUrl),Q.searchParams.set("state",$.state),Q.searchParams.set("nonce",$.nonce),Q.toString()}async function c5($){M1($.telemetry,"oca");let J=yW($.config),Q=CW($.mode),Z=$.callbackPorts?.length?$.callbackPorts:jK,W=$.callbackPath??WK,j=$.requestTimeoutMs??SW,f=await Y1({ports:Z,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=f.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let Y=wW(16),V=wW(16),{verifier:H,challenge:B}=await L4();AK(),m2.set(Y,{verifier:H,nonce:V,mode:Q,redirectUri:X,createdAt:Date.now()});let A=FK({callbackUrl:X,mode:Q,state:Y,nonce:V,challenge:B,config:J});$.callbacks.onAuth({url:A,instructions:"Continue the authentication process in your browser."});try{let K=await o$({waitForCallback:f.waitForCallback,cancelWait:f.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==Y)throw Error("State mismatch");let D=await GK({code:G,state:R,mode:Q,config:J,requestTimeoutMs:j});return q1($.telemetry,"oca"),N1($.telemetry,{id:D.accountId,email:D.email,provider:"oca"}),D}catch(K){throw P1($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{f.close()}}async function kW($,J={}){let Q=yW(J.config),Z=J.requestTimeoutMs??SW,W=$.metadata?.mode,j=W==="internal"||W==="external"?W:CW(J.mode),f=j==="external"?Q.external:Q.internal,X=await bW(f.idcsUrl,Z),Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:f.clientId}),V=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,signal:AbortSignal.timeout(Z)}),H=await V.json();if(!V.ok){let B=hW(H);throw new M4(`Token refresh failed: ${V.status}${B.message?` - ${B.message}`:""}`,{status:V.status,errorCode:B.code})}return EW(H,j,$)}async function u5($,J,Q){if(!$)return null;let Z=J?.refreshBufferMs??Q?.refreshBufferMs??fK,W=J?.retryableTokenGraceMs??Q?.retryableTokenGraceMs??XK;if(J?.forceRefresh!==!0&&!s$($,Z))return $;try{return await kW($,Q)}catch(f){if(f instanceof M4&&f.isLikelyInvalidGrant())return Y$(Q?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}import{getClineEnvironmentConfig as IW}from"@cline/shared";var q4="workos:";function DK($){let J=$.trim();return J.toLowerCase().startsWith(q4)?J:`${q4}${J}`}function UK($){let J=$.trim();return J.toLowerCase().startsWith(q4)?J.slice(q4.length):J}function RK($){let Q=R0($)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return null}function zK($,J){let Q=$.auth?.expiresAt;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>0)return Q;let Z=RK(J);if(Z)return Z;return Date.now()-1}function LK($,J){let Q=$.auth?.accessToken?.trim(),Z=$.auth?.refreshToken?.trim();if(!Q||!Z)return null;let W=J?.normalizeAccessToken?.(Q)??Q;if(!W)return null;return{access:W,refresh:Z,expires:zK($,W),accountId:$.auth?.accountId}}function _K($){let J=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Q={...$.settings?.auth??{},accessToken:J,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Z={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Q};if($.save!==!1)$.manager.saveProviderSettings(Z,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return Z}function d5($){let J=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:J,getApiKey(Q){let Z=Q?.auth?.accessToken?.trim();if(Z)return $.formatAccessToken?.(Z)??Z;return Q?.apiKey?.trim()||Q?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Q){return _K({...Q,storageProviderId:J,formatAccessToken:$.formatAccessToken})},isConfigured(Q){return!!Q?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function xW($){return d5({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:DK,normalizeStoredAccessToken:UK,login:({settings:J,callbacks:Q,telemetry:Z})=>b5({apiBaseUrl:J?.baseUrl?.trim()||IW().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q,telemetry:Z}),refresh:({settings:J,credentials:Q,forceRefresh:Z,telemetry:W})=>h5(Q,{apiBaseUrl:J.baseUrl?.trim()||IW().apiBaseUrl,telemetry:W},{forceRefresh:Z})})}var OK=[xW({providerId:"cline"}),xW({providerId:"cline-pass",storageProviderId:"cline"}),d5({providerId:"oca",login:({settings:$,callbacks:J,telemetry:Q})=>c5({mode:$?.oca?.mode,callbacks:J,telemetry:Q}),refresh:({settings:$,credentials:J,forceRefresh:Q,telemetry:Z})=>u5(J,{forceRefresh:Q,telemetry:Z},{mode:$.oca?.mode,telemetry:Z})}),d5({providerId:"openai-codex",login:({callbacks:$,telemetry:J})=>k5({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:J}),refresh:({credentials:$,forceRefresh:J,telemetry:Q})=>I5($,{forceRefresh:J,telemetry:Q})})],TK=new Map(OK.map(($)=>[$.providerId,$]));function f0($){return TK.get($.trim().toLowerCase())}function v2($){return f0($)!==void 0}function MK($){return f0($)?.storageProviderId}function qK($,J){let Q=f0(J),Z=Q?.storageProviderId??J,W=$.getProviderSettings(Z);return Q?.getApiKey(W)??P4(J,W)}async function l5($,J,Q){let Z=f0(J);if(!Z)throw Error(`Provider "${J}" does not support OAuth login`);let W=$.getProviderSettings(Z.storageProviderId),j=await Z.login({settings:W,callbacks:Q.callbacks,telemetry:Q.telemetry});return Z.saveCredentials({manager:$,settings:W,credentials:j})}function p5($,J){let Q=f0($);if(!Q)return null;return LK(J,{normalizeAccessToken:Q.normalizeStoredAccessToken})}function c2($){let J=f0($.providerId);if(!J)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return J.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function P4($,J){let Q=f0($);if(Q)return Q.getApiKey(J);return J?.auth?.accessToken?.trim()||J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0}function PK($,J){let Q=f0($);if(!Q)return J.access;return Q.getApiKey({provider:Q.storageProviderId,auth:{accessToken:J.access}})??J.access}import*as C0 from"@cline/llms";import{z as q}from"zod";import*as Q0 from"@cline/llms";function r5($){if(!Array.isArray($))return[];return $.map((J)=>{if(typeof J==="string")return J.trim();if(J&&typeof J==="object"){let Q=J;for(let Z of[Q.id,Q.name,Q.model])if(typeof Z==="string"&&Z.trim())return Z.trim()}return""}).filter((J)=>J.length>0)}function NK($,J){let Q=r5($);if(Q.length>0)return Q;if(!$||typeof $!=="object")return[];let Z=$,W=r5(Z.data??Z.models);if(W.length>0)return W;if(Z.models&&typeof Z.models==="object"&&!Array.isArray(Z.models)){let f=Object.keys(Z.models).filter((X)=>X.trim().length>0);if(f.length>0)return f}let j=Z.providers?.[J];if(j&&typeof j==="object"){let X=r5(j.models??j);if(X.length>0)return X}return[]}async function N4($,J){let Q=await fetch($,{method:"GET"});if(!Q.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Q.status}`);return NK(await Q.json(),J)}function gW($){return $.replace(/\/+$/,"")}function w4($,J,Q){let Z=Q?.trim();if(!Z)return;let W=$?.trim();if(!W||!J?.trim())return Z;try{let j=new URL(Z),f=new URL(J),X=new URL(W);if(j.origin!==f.origin)return Z;let Y=gW(f.pathname),V=gW(X.pathname);if(Y&&j.pathname.startsWith(`${Y}/`)){let H=j.pathname.slice(Y.length);X.pathname=`${V}${H}`}else X.pathname=j.pathname;return X.search=j.search,X.hash=j.hash,X.toString()}catch{return Z}}function wK($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{...Q}]))}function SK($){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 CK=Object.values(Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:wK($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),cW=Object.fromEntries(CK.map(($)=>[$.id,$]));function yK($){return cW[$]}function EK(){return Object.fromEntries(Object.entries(cW).filter(([,$])=>SK($)))}function uW($=[]){let J=$.flatMap((Q)=>{switch(Q){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Q];default:return[]}});return J.length>0?J:void 0}var dW="https://models.dev/api.json",bK=600000,lW=300000,hK=5000,C4=new Map,u2=new Map,n5=new Map,S4=new Map;async function kK(){return Q0.getGeneratedProviderModels()}async function IK($,J={},Q={},Z={},W={},j={}){let f=await kK(),X=Q0.resolveProviderModelCatalogKeys($),Y=Object.assign({},...X.map((B)=>f[B]??{})),V=Boolean(Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),H=Object.keys(W).length>0;if(V&&H)return Q0.sortModelsByReleaseDate({...W,...j});if($==="openai-codex")return Q0.sortModelsByReleaseDate({...J,...Q0.filterOpenAICodexModels(Q),...W,...j});return Q0.sortModelsByReleaseDate({...Y,...J,...Q,...Z,...W,...j})}function xK($,J){let Q=Q0.resolveProviderModelCatalogKeys($);return Object.assign({},...Q.map((Z)=>J[Z]??{}))}function y4($){let J=$?.trim();return J&&J.length>0?J:""}function a5($){let J=$.apiKey?.trim()||$.accessToken?.trim();return J&&J.length>0?J:void 0}function gK($){let J=2166136261;for(let Q=0;Q<$.length;Q+=1)J^=$.charCodeAt(Q),J+=(J<<1)+(J<<4)+(J<<7)+(J<<8)+(J<<24);return(J>>>0).toString(16)}function mK($,J){return`${$}:${y4(J.baseUrl)}:${gK(a5(J)??"")}`}async function E4($,J,Q=hK){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await fetch($,{...J,signal:Z.signal})}finally{clearTimeout(W)}}function B$($,J,Q){if(Q&&!$.includes(J))$.push(J)}function b4($,J){let Q=["streaming","tools"];return B$(Q,"images",Boolean(J.supportsImages)),B$(Q,"prompt-cache",Boolean(J.supportsPromptCache)),B$(Q,"reasoning",Boolean(J.supportsReasoning)),{id:$,name:J.name??$,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxTokens:J.maxTokens,capabilities:Q,releaseDate:J.releaseDate,status:"active"}}async function vK($,J){let Q=await E4("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"}});if(!Q.ok)throw Error(`Baseten model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let Y=f.supported_features??[];j[X]=b4(X,{name:X,contextWindow:f.context_length,maxInputTokens:f.context_length,maxTokens:f.max_completion_tokens,supportsReasoning:Y.includes("reasoning")||Y.includes("reasoning_effort"),supportsImages:!1})}return j}function mW($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let J=Number($);return Number.isFinite(J)?J:void 0}return}async function cK($,J){let Q=await E4("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":J}});if(!Q.ok)throw Error(`Hicap model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;j[X]=b4(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function uK($,J){let Z=`${(y4($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,W=await E4(Z,{method:"GET",headers:{Authorization:`Bearer ${J}`,accept:"application/json"}});if(!W.ok)throw Error(`Poolside model refresh failed: HTTP ${W.status}`);let f=(await W.json())?.data??[],X={};for(let Y of f){let V=Y.id?.trim();if(!V)continue;let H=Y.supported_features??[],B=Y.supported_sampling_parameters??[],A=Y.input_modalities??[],K=["streaming"];B$(K,"tools",H.includes("tools")),B$(K,"reasoning",H.includes("reasoning")),B$(K,"temperature",B.includes("temperature")),B$(K,"images",A.includes("image"));let G={input:mW(Y.pricing?.prompt),output:mW(Y.pricing?.completion)};X[V]={id:V,name:Y.name??V,description:Y.description,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function dK($){let J=y4($);if(!J)return"http://localhost:4000";return J.endsWith("/v1")?J.slice(0,-3):J}async function lK($,J){let Z=`${dK($.baseUrl)}/v1/model/info`,W=async(V)=>E4(Z,{method:"GET",headers:{accept:"application/json",...V}}),j=await W({"x-litellm-api-key":J});if(!j.ok)j=await W({Authorization:`Bearer ${J}`});if(!j.ok)throw Error(`LiteLLM model refresh failed: HTTP ${j.status}`);let X=(await j.json())?.data??[],Y={};for(let V of X){let H=V.model_name?.trim(),A=V.litellm_params?.model?.trim()||H;if(!A)continue;let K=V.model_info,G=b4(A,{name:H??A,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(Y[A]=G,H)Y[H]={...G,id:H,name:H}}return Y}var pW={baseten:vK,hicap:cK,litellm:lK,poolside:uK},vW=new Map,i5=new Map;function pK($,J){return`${$}:${y4(J.baseUrl)}`}async function rK($,J,Q){let Z=Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=w4(Q.baseUrl,Z?.provider.baseUrl,Z?.provider.modelsSourceUrl);if(!W)return{};let j=J?.cacheTtlMs??lW,f=pK($,Q),X=Date.now(),Y=vW.get(f);if(Y&&Y.expiresAt>X)return Y.data;let V=i5.get(f);if(V)return V;let H=N4(W,$).then((B)=>{let A=Object.fromEntries(B.map((K)=>[K,b4(K,{name:K})]));return vW.set(f,{data:A,expiresAt:X+j}),A}).finally(()=>{i5.delete(f)});return i5.set(f,H),H}async function iK($,J){let Q=a5(J);if(!Q)return{};let Z=pW[$];if(!Z)return{};return Z(J,Q)}function nK($,J,Q){if(!Q)return!1;if(!pW[$])return!1;if(J?.loadPrivateOnAuth===!1)return!1;return Boolean(a5(Q))}async function aK($,J,Q){let Z=J?.cacheTtlMs??lW,W=mK($,Q),j=Date.now(),f=n5.get(W);if(f&&f.expiresAt>j)return f.data;let X=S4.get(W);if(X)return X;let Y=iK($,Q).then((V)=>{return n5.set(W,{data:V,expiresAt:j+Z}),V}).finally(()=>{S4.delete(W)});return S4.set(W,Y),Y}async function sK($){return Q0.fetchModelsDevProviderModels($,globalThis.fetch)}async function h4($={}){let J=$.url??dW,Q=$.cacheTtlMs??bK,Z=Date.now(),W=C4.get(J);if(W&&W.expiresAt>Z)return W.data;let j=u2.get(J);if(j)return j;let f=sK(J).then((X)=>{return C4.set(J,{data:X,expiresAt:Z+Q}),X}).finally(()=>{u2.delete(J)});return u2.set(J,f),f}function oK($){if($){C4.delete($),u2.delete($);return}C4.clear(),u2.clear()}function tK(){n5.clear(),S4.clear()}function eK($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{baseUrl:Q.baseUrl,modelId:Q.modelId,capabilities:uW(Q.capabilities)}]))}var s5=eK(EK());function rW($){let J=yK($);if(!J)return;return{baseUrl:J.baseUrl||void 0,modelId:J.modelId,knownModels:J.knownModels,capabilities:uW(J.capabilities)}}async function o5($,J,Q){let Z=rW($);if(!Z)return;try{let W=J?.loadLatestOnInit?await h4(J):void 0,j=W?xK($,W):{},f=Q&&nK($,J,Q)?await aK($,J,Q):{},Y=Boolean(Q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Q??{providerId:$,modelId:Z.modelId,baseUrl:Z.baseUrl}:Q,V=Y?await rK($,J,Y).catch(()=>({})):{},H=await IK($,Z.knownModels,j,f,V,Q?.knownModels);return{...Z,knownModels:H}}catch(W){if(J?.failOnError)throw W;return Z}}var t5=C0.BUILT_IN_PROVIDER,$G=C0.BUILT_IN_PROVIDER_IDS,JG=C0.isBuiltInProviderId,k4=C0.normalizeProviderId,e5=q.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),iW=q.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),nW=q.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),aW=q.object({apiKey:q.string().optional(),accessToken:q.string().optional(),refreshToken:q.string().optional(),expiresAt:q.number().int().positive().optional(),accountId:q.string().optional()}),QG=q.enum(["none","low","medium","high","xhigh"]),sW=q.object({enabled:q.boolean().optional(),effort:QG.optional(),budgetTokens:q.number().int().positive().optional()}),oW=q.object({accessKey:q.string().optional(),secretKey:q.string().optional(),sessionToken:q.string().optional(),region:q.string().optional(),profile:q.string().optional(),authentication:q.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:q.boolean().optional(),useCrossRegionInference:q.boolean().optional(),useGlobalInference:q.boolean().optional(),endpoint:q.string().url().optional(),customModelBaseId:q.string().optional()}),tW=q.object({projectId:q.string().optional(),region:q.string().optional()}),eW=q.object({apiVersion:q.string().optional(),useIdentity:q.boolean().optional()}),$3=q.object({clientId:q.string().optional(),clientSecret:q.string().optional(),tokenUrl:q.string().url().optional(),resourceGroup:q.string().optional(),deploymentId:q.string().optional(),useOrchestrationMode:q.boolean().optional(),api:q.enum(["orchestration","foundation-models"]).optional(),defaultSettings:q.record(q.string(),q.unknown()).optional()}),J3=q.object({mode:q.enum(["internal","external"]).optional(),usePromptCache:q.boolean().optional()}),Q3=q.object({loadLatestOnInit:q.boolean().optional(),loadPrivateOnAuth:q.boolean().optional(),url:q.string().url().optional(),cacheTtlMs:q.number().int().positive().optional(),failOnError:q.boolean().optional()}),e$=q.object({provider:e5,apiKey:q.string().optional(),auth:aW.optional(),model:q.string().optional(),protocol:iW.optional(),client:nW.optional(),routingProviderId:e5.optional(),maxTokens:q.number().int().positive().optional(),contextWindow:q.number().int().positive().optional(),baseUrl:q.string().url().optional(),headers:q.record(q.string(),q.string()).optional(),timeout:q.number().int().positive().optional(),reasoning:sW.optional(),aws:oW.optional(),gcp:tW.optional(),azure:eW.optional(),sap:$3.optional(),oca:J3.optional(),region:q.string().optional(),apiLine:q.enum(["china","international"]).optional(),capabilities:q.array(q.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:Q3.optional()});function Z3($){return e$.parse($)}function W3($){return e$.safeParse($)}function ZG($){return $.protocol==="openai-responses"||$.client==="openai"}function V1($,J={}){let Q=$.provider,Z=k4(Q),W=J.includeKnownModels!==!1,j=$.reasoning?.effort||"none",f=j==="none"?void 0:j,X=s5[Z],Y=Object.assign({},...C0.resolveProviderModelCatalogKeys(Z).map((R)=>C0.getGeneratedModelsForProvider(R))),V=Object.keys(Y)[0],H=P4(Z,$),B=$.baseUrl??(Z==="oca"?$.oca?.mode==="internal"?m5:v5:X?.baseUrl),A=$.routingProviderId??(ZG($)&&Z!==t5.OPENAI_NATIVE?t5.OPENAI_NATIVE:void 0),K=W?X?.knownModels??(Object.keys(Y).length>0?Y:void 0):void 0,G={providerId:Q,clientType:$.client,routingProviderId:A,modelId:$.model??X?.modelId??V??"default",...W?{knownModels:K}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:B,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:f,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,D])=>D!==void 0))}function WG($){let J=Z3($);return V1(J)}function jG($){let J=W3($);if(J.success)return{success:!0,config:V1(J.data)};return{success:!1,error:J.error}}import{SESSION_STATUS_VALUES as fG}from"@cline/shared";var $Q=fG,XG=["idle","running","pending"];function YG($){return!XG.includes($)}function Z0($){return!YG($)}var z0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function j3($){if($===!0)return{};if(!$)return;return $}function f3($){if($==="user")return"global";return $}class JQ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let J=this.getService().ingestEvent($);return{event:J.event,duplicate:J.duplicate,matchedSpecIds:J.matchedSpecs.map((Q)=>Q.specId),queuedRuns:J.queuedRuns,suppressions:J.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function X3($){let{host:J}=$;return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||z0.CLI,interactive:!1,config:{providerId:k4(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:BG(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content),delivery:Z.delivery});if(!W)throw Error("ClineCore automation runtime returned no result");return{result:HG(W)}},async abortSession(Q){return await J.abort(Q,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}function I4($){let J=VG($.automationService,$.automation),Q=$.context?.client??($.clientName?{name:$.clientName}:void 0),Z=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),W=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!J&&!Q&&!Z&&!W&&!j)return $.context;return{...$.context??{},...Q?{client:Q}:{},...Z?{user:Z}:{},...W?{logger:W}:{},...j?{telemetry:j}:{},...J?{automation:J}:{}}}function VG($,J){if(!$)return;return{ingestEvent:(Q)=>{J.ingestEvent(Q)}}}function HG($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function BG($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}import{existsSync as x6}from"node:fs";import{basename as XX,isAbsolute as vz,relative as cz}from"node:path";import{createHash as AG}from"node:crypto";import{watch as KG}from"node:fs";import{readdir as GG,readFile as FG}from"node:fs/promises";import{join as DG}from"node:path";function UG($){return AG("sha1").update($).digest("hex")}function H3($){return Boolean($&&typeof $==="object"&&"code"in $)}function Y3($){return H3($)&&$.code==="ENOENT"}function V3($){return H3($)&&($.code==="EACCES"||$.code==="EPERM")}class d2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,J){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=J?.debounceMs??75,this.emitParseErrors=J?.emitParseErrors??!1;for(let Q of $){if(this.definitionsByType.has(Q.type))throw Error(`Duplicate unified config definition type '${Q.type}'.`);this.definitionsByType.set(Q.type,Q),this.recordsByType.set(Q.type,new Map),this.discoveredDirectoriesByType.set(Q.type,new Set);for(let Z of Q.directories){let W=this.baseTypesByDirectory.get(Z);if(W)W.add(Q.type);else this.baseTypesByDirectory.set(Z,new Set([Q.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let J=this.definitionsByType.get($);if(!J)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(J)})}getSnapshot($){let J=this.recordsByType.get($);return new Map([...J?.entries()??[]].map(([Q,Z])=>[Q,{...Z}]))}getAllSnapshots(){let $=new Map;for(let[J,Q]of this.recordsByType.entries())$.set(J,new Map([...Q.entries()].map(([Z,W])=>[Z,{...W}])));return $}emit($){for(let J of this.listeners)J($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[J,Q]of this.watchersByDirectory.entries()){if($.has(J))continue;Q.close(),this.watchersByDirectory.delete(J)}this.watchedTypesByDirectory=$;for(let J of $.keys()){if(this.watchersByDirectory.has(J))continue;try{let Q=KG(J,()=>{let Z=this.watchedTypesByDirectory.get(J);if(!Z)return;for(let W of Z)this.pendingTypes.add(W);this.scheduleFlush()});this.watchersByDirectory.set(J,Q),Q.on("error",(Z)=>{let W=this.watchedTypesByDirectory.get(J);if(!W)return;for(let j of W)this.emit({kind:"error",type:j,error:Z,filePath:J})})}catch(Q){if(!Y3(Q)&&!V3(Q)){let Z=$.get(J);if(!Z)continue;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:J})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let J of $){let Q=this.definitionsByType.get(J);if(!Q)continue;await this.refreshTypeInternal(Q)}})},this.debounceMs)}async refreshTypeInternal($){let{records:J,discoveredDirectories:Q}=await this.loadDefinition($),Z=this.recordsByType.get($.type)??new Map;for(let[W,j]of Z.entries()){if(J.has(W))continue;this.emit({kind:"remove",type:$.type,id:W,filePath:j.filePath})}for(let[W,j]of J.entries()){let f=Z.get(W);if(f&&f.filePath===j.filePath&&f.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:W,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,J),this.discoveredDirectoriesByType.set($.type,Q),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let J=new Map,Q=new Set;for(let Z of $.directories){Q.add(Z);let W=$.discoverFiles?await $.discoverFiles(Z):await this.readDirectoryFileCandidates(Z);for(let j of W){let{fileName:f,filePath:X}=j;if(Q.add(j.directoryPath),$.includeFile&&!$.includeFile(f,X))continue;try{let Y=await FG(X,"utf8"),V={type:$.type,directoryPath:j.directoryPath,fileName:f,filePath:X,content:Y},H=$.parseFile(V),B=$.resolveId(H,V).trim();if(!B)continue;J.set(B,{type:$.type,id:B,item:H,filePath:X,fingerprint:UG(Y)})}catch(Y){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Y,filePath:X})}}}return{records:J,discoveredDirectories:Q}}buildDesiredTypesByDirectory(){let $=new Map;for(let[J,Q]of this.baseTypesByDirectory.entries())$.set(J,new Set(Q));for(let[J,Q]of this.discoveredDirectoriesByType.entries())for(let Z of Q){let W=$.get(Z);if(W)W.add(J);else $.set(Z,new Set([J]))}return $}async readDirectoryFileCandidates($){try{return(await GG($,{withFileTypes:!0})).filter((Q)=>Q.isFile()).map((Q)=>({directoryPath:$,fileName:Q.name,filePath:DG($,Q.name)})).sort((Q,Z)=>Q.fileName.localeCompare(Z.fileName))}catch(J){if(Y3(J)||V3(J))return[];throw J}}}import{readdir as TQ,readFile as hF,stat as OQ}from"node:fs/promises";import{basename as B1,dirname as kF,extname as s4,join as q0,resolve as s2}from"node:path";import{AGENTS_RULES_FILE_NAME as m3,RULES_CONFIG_DIRECTORY_NAME as v3,resolveGlobalAgentsRulesPath as IF,resolveRulesConfigSearchPaths as xF,resolveSkillsConfigSearchPaths as gF,resolveWorkflowsConfigSearchPaths as mF,SKILLS_CONFIG_DIRECTORY_NAME as MQ,WORKFLOWS_CONFIG_DIRECTORY_NAME as qQ}from"@cline/shared/storage";import vF from"yaml";p0();import{existsSync as r4,readFileSync as _F,statSync as OF}from"node:fs";import{basename as TF,dirname as l4,join as i4,resolve as p4}from"node:path";import{discoverPluginModulePaths as MF,resolveConfiguredPluginModulePaths as h3,resolvePluginConfigSearchPaths as qF,SKILLS_CONFIG_DIRECTORY_NAME as PF}from"@cline/shared/storage";import{resolve as tG}from"node:path";import{normalizePluginManifest as eG}from"@cline/shared";import{existsSync as Y0,readFileSync as Q2}from"node:fs";import{builtinModules as bG,createRequire as VQ}from"node:module";import{dirname as E1,extname as p2,isAbsolute as hG,resolve as u}from"node:path";import{fileURLToPath as D3}from"node:url";import{PLUGIN_FILE_EXTENSIONS as kG}from"@cline/shared";var U3=E1(D3(import.meta.url)),IG=VQ(import.meta.url),xG=u(U3,"..","..","..","..",".."),fQ=vG(xG),gG=["@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"],HQ=new Set(bG.flatMap(($)=>[$,$.replace(/^node:/,"")])),l2=new Set(kG),mG=["development","node","import","require","default"];function vG($){let J={},Q={"@cline/sdk":u($,"packages/sdk/src/index.ts"),"@cline/agents":u($,"packages/agents/src/index.ts"),"@cline/core":u($,"packages/core/src/index.ts"),"@cline/llms":u($,"packages/llms/src/index.ts"),"@cline/shared":u($,"packages/shared/src/index.ts"),"@cline/shared/storage":u($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":u($,"packages/shared/src/db/index.ts")};for(let[Z,W]of Object.entries(Q))if(Y0(W))J[Z]=W;for(let Z of["agents","core","llms","shared"]){let W=u($,"packages",Z),j=u(W,"package.json");if(!Y0(j))continue;try{let f=JSON.parse(Q2(j,"utf8"));if(typeof f.name!=="string"||!f.exports)continue;if(typeof f.exports==="string"){let X=u(W,f.exports);if(Y0(X))J[f.name]=X;continue}if(typeof f.exports!=="object")continue;for(let[X,Y]of Object.entries(f.exports)){let V=cG(W,Y);if(!V)continue;let H=X==="."?f.name:`${f.name}/${X.replace(/^\.\//,"")}`;J[H]=V}}catch{}}return J}function cG($,J){let Q=BQ(J);if(!Q)return null;let Z=R3($,Q);for(let W of Z)if(Y0(W))return W;return null}function BQ($,J=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(J.has($))return null;J.add($);let Q=$;for(let Z of mG){let W=BQ(Q[Z],J);if(W)return W}return null}function R3($,J){let Q=J.replace(/^\.\//,""),Z=[u($,J)];if(Q.startsWith("dist/")){let W=Q.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[u($,`${W}.ts`),u($,`${W}.tsx`),u($,`${W}.mts`),u($,`${W}.cts`),...Z]}return Z}function uG($){return Object.fromEntries(Object.entries($).sort(([J],[Q])=>Q.length-J.length))}function c4($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function J2($){if($.startsWith("@")){let[J,Q]=$.split("/",3);return Q?`${J}/${Q}`:$}return $.split("/",1)[0]??$}function dG($){let J=J2($);if($===J)return".";return`.${$.slice(J.length)}`}function z3($){return J2($).startsWith("@cline/")}function XQ($,J){let Q=J2(J),Z=E1($);while(!0){let W=u(Z,"node_modules",Q);if(Y0(W)||Y0(u(W,"package.json")))return!0;let j=u(Z,"..");if(j===Z)return!1;Z=j}}function F3($){return YQ($)!==null}function YQ($){try{return IG.resolve($)}catch{}return lG($)}function lG($){let J=J2($),Q=L3(J);if(!Q)return null;let Z=u(Q,"package.json");try{let W=JSON.parse(Q2(Z,"utf8")),j=dG($),f=j==="."&&typeof W.exports==="string"?W.exports:W.exports&&typeof W.exports==="object"&&Object.hasOwn(W.exports,j)?W.exports[j]:void 0,X=BQ(f)??(j==="."&&typeof W.main==="string"?W.main:null);if(!X)return null;let Y=u(Q,X),V=[Y,...R3(Q,X).filter((H)=>H!==Y)];for(let H of V)if(Y0(H))return H;return null}catch{return null}}function pG(){let $=[U3],J=process.env.CLINE_WRAPPER_PATH?.trim();if(J)$.push(E1(E1(J)));let Q=process.execPath?.trim();if(Q)$.push(E1(Q));return[...new Set($.map((Z)=>u(Z)))]}function rG($,J){let Q=$;while(!0){let Z=u(Q,"package.json");if(Y0(Z))try{if(JSON.parse(Q2(Z,"utf8")).name===J)return Q}catch{}let W=u(Q,"node_modules",J,"package.json");if(Y0(W))return E1(W);let j=u(Q,"..");if(j===Q)return null;Q=j}}function L3($){for(let J of pG()){let Q=rG(J,$);if(Q)return Q}return null}function iG($){let Q=E1($);for(let Z=0;Z<4;Z++){let W=u(Q,"package.json");if(Y0(W))try{let f=JSON.parse(Q2(W,"utf8"));return f!=null&&typeof f==="object"&&"cline"in f}catch{return!1}let j=u(Q,"..");if(j===Q)return!1;Q=j}return!1}function _3($,J){let Q=J.startsWith("file:")?D3(J):hG(J)?J:u(E1($),J);if(Y0(Q)&&l2.has(p2(Q)))return Q;for(let Z of l2){let W=`${Q}${Z}`;if(Y0(W))return W}for(let Z of l2){let W=u(Q,`index${Z}`);if(Y0(W))return W}return null}function O3($){let J=new Set,Q=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Z of Q)for(let W of $.matchAll(Z)){let j=W[1];if(j)J.add(j)}return[...J]}function nG($){return p2($)!==".ts"}function T3($,J,Q=new Set){if(Q.has($)||!Y0($))return;if(Q.add($),!l2.has(p2($)))return;let Z=Q2($,"utf8"),W=nG($);for(let j of O3(Z)){if(j.startsWith("node:")||HQ.has(j))continue;if(c4(j)){if(!W)continue;if(Object.hasOwn(fQ,j)||Object.hasOwn(fQ,J2(j))||XQ($,j)||z3(j)&&F3(j)||J&&F3(j))continue;throw Error(`Cannot find module '${J2(j)}'`)}let f=_3($,j);if(f)T3(f,J,Q)}}function M3($,J=new Set,Q=new Set){if(J.has($)||!Y0($))return Q;if(J.add($),!l2.has(p2($)))return Q;let Z=Q2($,"utf8");for(let W of O3(Z)){if(Q.add(W),c4(W))continue;let j=_3($,W);if(j)M3(j,J,Q)}return Q}function aG($,J){let Q=VQ($),Z={},W=M3($),j=new Set(gG);for(let[f,X]of Object.entries(fQ)){try{Q.resolve(f);continue}catch{}Z[f]=X}for(let f of W)if(c4(f)&&(z3(f)||J))j.add(f);for(let f of j){if(Object.hasOwn(Z,f)||XQ($,f))continue;let X=YQ(f);if(X)Z[f]=X}if(!J)return Z;for(let f of W){if(!c4(f)||Object.hasOwn(Z,f)||XQ($,f)||f.startsWith("node:")||HQ.has(f))continue;let X=YQ(f);if(X)Z[f]=X}return Z}function sG($){let J=p2($);return J===".ts"||J===".tsx"||J===".mts"||J===".cts"}var A$;function oG(){if(A$!==void 0)return A$;let $=L3("jiti");if(!$)return A$=null,null;let J=u($,"dist","babel.cjs");if(!Y0(J))return A$=null,null;try{let Z=VQ(J)(J);A$=typeof Z==="function"?Z:null}catch{A$=null}return A$}async function q3($,J={}){let Q=!iG($);T3($,Q);let Z=aG($,Q),W=uG(Z),j=await import("jiti"),f=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!f)throw Error("Unable to load jiti");let X=Object.entries(W).filter(([,B])=>sG(B)).map(([B])=>B),Y=oG(),V=Y?(B)=>Y({...B,interopDefault:!0}):void 0;return await f($,{alias:W,cache:J.useCache,requireCache:J.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...HQ],transformModules:X,tryNative:!1,...V?{transform:V}:{}}).import($,{})}function P3($,J){if(!$)return!0;if($.providerIds?.length){if(!J?.providerId||!$.providerIds.includes(J.providerId))return!1}if($.modelIds?.length){if(!J?.modelId||!$.modelIds.includes(J.modelId))return!1}return!0}function N3($){return typeof $==="object"&&$!==null}function AQ($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function $F($,J){if(!N3($.manifest))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);if(!AQ($.manifest.capabilities))throw Error(`Invalid plugin module at ${J}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${J}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!AQ($.manifest.providerIds))throw Error(`Invalid plugin module at ${J}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!AQ($.manifest.modelIds))throw Error(`Invalid plugin module at ${J}: manifest.modelIds must be a string array when provided`)}function JF($,J){if(!N3($))throw Error(`Invalid plugin module at ${J}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${J}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);$F($,J)}async function KQ($,J={}){let Q=tG(J.cwd??process.cwd(),$),Z=await q3(Q,{useCache:J.useCache}),W=J.exportName??"plugin",j=Z.default??Z[W];JF(j,Q);let f=j,X=f.setup,Y=X?(V,H)=>{let B={...J.session,...H.session},A={...H,session:Object.keys(B).length>0?B:void 0,client:J.client??H.client,user:J.user??H.user,workspaceInfo:J.workspaceInfo??H.workspaceInfo,automation:J.automation??H.automation,logger:J.logger??H.logger,telemetry:J.telemetry??H.telemetry};return X(V,A)}:void 0;return{...f,manifest:eG(f.manifest),setup:Y}}async function w3($,J={}){return(await r2($,J)).plugins}async function r2($,J={}){let Q=[],Z=[],W=new Map,j=0;for(let X of $)try{let Y=await KQ(X,J);if(!P3(Y.manifest,J))continue;let V=W.get(Y.name);if(V)Z.push({type:"duplicate_plugin_override",pluginName:Y.name,pluginPath:X,overriddenPluginPath:V.pluginPath,message:`Plugin "${Y.name}" from ${X} overrides ${V.pluginPath}`});W.set(Y.name,{plugin:Y,pluginPath:X,order:j++})}catch(Y){let V=Y instanceof Error?Y.message:String(Y);Q.push({pluginPath:X,phase:"load",message:V,stack:Y instanceof Error?Y.stack:void 0})}let f=[...W.values()].sort((X,Y)=>X.order-Y.order);return{plugins:f.map((X)=>X.plugin),pluginPaths:f.map((X)=>X.pluginPath),failures:Q,warnings:Z}}import{existsSync as DQ}from"node:fs";import{createRequire as b3}from"node:module";import{dirname as d4,join as Z2}from"node:path";import{fileURLToPath as YF}from"node:url";import{spawn as QF}from"node:child_process";import{basename as ZF}from"node:path";import{augmentNodeCommandForDebug as WF,withResolvedClineBuildEnv as jF}from"@cline/shared";function S3($){if($ instanceof Error)return $;return Error(String($))}var fF="CLINE_JS_RUNTIME_PATH";function C3($){let J=$?.trim();if(!J)return!1;let Q=ZF(J).toLowerCase();return Q==="node"||Q==="node.exe"||Q==="bun"||Q==="bun.exe"}function y3($={}){let J=$.env??process.env,Q=$.runtimeExecutable?.trim()||J[fF]?.trim();if(Q)return Q;let Z=$.execPath?.trim()||process.execPath;if(C3(Z))return Z;for(let W of[J.BUN_EXEC_PATH,J.npm_node_execpath,J.NODE]){let j=W?.trim();if(j&&C3(j))return j}return"node"}function XF($,J={}){let Q=y3({env:J.env,execPath:J.execPath,runtimeExecutable:J.runtimeExecutable});return WF([Q,...$],{env:J.env,execArgv:J.execArgv,debugRole:J.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class u4{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let J=this.pending.get($);if(!J)return;if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);return J}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],J=XF($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Q=QF(J[0]??y3(this.options),J.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:jF(process.env),windowsHide:!0});this.process=Q;let Z="",W=(j)=>{let f=Z+j;Z=f.length>4000?f.slice(-4000):f};Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(j)=>{W(j)}),Q.on("message",(j)=>{this.onMessage(j)}),Q.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${S3(j).message}`))}),Q.on("exit",(j,f)=>{this.process=null;let X=Z.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(f)})${X?`: ${X}`:""}`))})}async call($,J,Q={}){this.start();let Z=this.process;if(!Z||Z.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let W=`req_${++this.requestCounter}`,j={type:"call",id:W,method:$,args:J};return await new Promise((f,X)=>{let Y={resolve:(V)=>f(V),reject:X};if((Q.timeoutMs??0)>0)Y.timeout=setTimeout(()=>{this.clearPendingRequest(W),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${Q.timeoutMs}ms: ${$}`))},Q.timeoutMs);this.pending.set(W,Y),Z.send(j,(V)=>{if(!V)return;let H=this.clearPendingRequest(W);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${S3(V).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((J)=>{let Q=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}J()},300);$.once("exit",()=>{clearTimeout(Q),J()});try{$.kill("SIGTERM")}catch{clearTimeout(Q),J()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let J=this.clearPendingRequest($.id);if(!J)return;if($.ok){J.resolve($.result);return}J.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[J,Q]of this.pending.entries()){if(this.pending.delete(J),Q.timeout)clearTimeout(Q.timeout);Q.reject($)}}}function VF($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function i2($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function HF(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function BF(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Q=b3($).resolve(`${HF()}/package.json`),Z=Z2(d4(Q),"extensions","plugin-sandbox-bootstrap.js");return DQ(Z)?Z:void 0}catch{return}}function AF(){let $=process.execPath?.trim();if(!$)return;let J=Z2(d4(d4($)),"extensions","plugin-sandbox-bootstrap.js");return DQ(J)?J:void 0}function KF(){let $=d4(YF(import.meta.url)),J=b3(import.meta.url),Q=[Z2($,"plugin-sandbox-bootstrap.js"),Z2($,"extensions","plugin-sandbox-bootstrap.js"),Z2($,"agents","plugin-sandbox-bootstrap.js"),BF(),AF()];for(let j of Q.filter((f)=>typeof f==="string"))if(DQ(j))return{file:j};let Z=Z2($,"plugin-sandbox-bootstrap.ts"),W="jiti";try{W=J.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(W)});`,`const jiti = createJiti(${JSON.stringify(Z)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Z)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
47
+ `)}}var GQ=KF();function FQ($,J,Q){if(typeof $==="number"&&$>0)return $;if(Q){let Z=process.env[Q];if(Z){let W=Number(Z);if(Number.isInteger(W)&&W>0)return W}}return J}async function W2($){let J=new u4({name:"plugin-sandbox",..."file"in GQ?{bootstrapFile:GQ.file}:{bootstrapScript:GQ.script},onEvent:$.onEvent}),Q=FQ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Z=FQ($.hookTimeoutMs,3000),W=FQ($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},f,X=()=>{return f??=J.call("initialize",j,{timeoutMs:Q}).finally(()=>{f=void 0}),f},Y;try{Y=await J.call("initialize",j,{timeoutMs:Q})}catch(B){throw await J.shutdown().catch(()=>{}),B}let V=Y.plugins.map(VF);return{extensions:V.map((B)=>{let A={name:B.name,__clinePluginPath:B.pluginPath,manifest:B.manifest,setup:(K)=>{GF(K,J,B,W,X),FF(K,J,B,W,X),DF(K,J,B,W,X),RF(K,J,B,W,X),UF(K,B)}};return A.hooks=LF(J,B,Z,X),A}),failures:Y.failures,pluginPaths:V.map((B)=>B.pluginPath),shutdown:async()=>{await J.shutdown()},warnings:Y.warnings}}function GF($,J,Q,Z,W){for(let j of Q.contributions?.tools??[]){let f={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(X,Y)=>{try{return await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}catch(V){if(!i2(V))throw V;return await W(),await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}}};$.registerTool(f)}}function FF($,J,Q,Z,W){for(let j of Q.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(f)=>{try{return await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}catch(X){if(!i2(X))throw X;return await W(),await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}}})}function DF($,J,Q,Z,W){for(let j of Q.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}catch(f){if(!i2(f))throw f;return await W(),await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}}:j.content??""})}function UF($,J){for(let Q of J.contributions?.providers??[])$.registerProvider({name:Q.name,description:Q.description,metadata:Q.metadata});for(let Q of J.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Q.eventType,source:Q.source,description:Q.description,attributesSchema:Q.attributesSchema,payloadSchema:Q.payloadSchema,examples:Q.examples,metadata:Q.metadata});for(let Q of J.contributions?.mcpServers??[])$.registerMcpServer(Q)}function RF($,J,Q,Z,W){for(let j of Q.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(f){try{let X=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return E3(X)?X:f}catch(X){if(!i2(X))throw X;await W();let Y=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return E3(Y)?Y:f}}})}function E3($){return Array.isArray($)&&$.every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&("content"in J))}function zF($,J,Q,Z,W){return async(j)=>{try{return await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}catch(f){if(!i2(f))throw f;return await W(),await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}}}function LF($,J,Q,Z){let W={};for(let j of J.hooks??[])W[j]=zF($,J.pluginId,j,Q,Z);return Object.keys(W).length>0?W:void 0}var RQ="package.json",NF="package";function zQ($){return qF($)}function LQ($){return MF($)}function wF($){try{return r4($)&&OF($).isDirectory()}catch{return!1}}function _Q($){let J=[],Q=new Set;for(let Z of $){let W=p4(Z);if(Q.has(W))continue;Q.add(W),J.push(W)}return J}function k3($){let J=_Q($);return WQ(J)}function I3($){return zQ($).flatMap((J)=>LQ(J)).filter((J)=>r4(J))}function SF($,J){let Q=[];for(let Z of $)try{Q.push(...h3([Z],J))}catch{}return Q}function UQ($){return typeof $==="object"&&$!==null}function CF($){try{let J=JSON.parse(_F(i4($,RQ),"utf8"));if(!UQ(J)||!UQ(J.cline))return[];let Q=J.cline.plugins;if(!Array.isArray(Q))return[];let Z=[];for(let W of Q){if(typeof W==="string"){Z.push(W);continue}if(!UQ(W)||!Array.isArray(W.paths))continue;for(let j of W.paths)if(typeof j==="string")Z.push(j)}return Z}catch{return[]}}function x3($,J){let Q=p4(J);return CF($).some((Z)=>p4($,Z)===Q)}function yF($,J){return TF($)===NF&&r4(i4(l4($),RQ))&&x3(l4($),J)}function EF($){let J=p4($),Q=[],Z=l4(J);while(!0){if(yF(Z,J)){Q.push(Z);break}if(r4(i4(Z,RQ))){if(x3(Z,J))Q.push(Z);break}let W=l4(Z);if(W===Z)break;Z=W}return _Q(Q)}function n2($={}){let J=$.cwd??process.cwd(),Q=I3($.workspacePath),Z=h3($.pluginPaths??[],J);return k3([...Z,...Q])}function bF($={}){let J=$.cwd??process.cwd(),Q=I3($.workspacePath),Z=SF($.pluginPaths??[],J);return k3([...Z,...Q])}function a2($){let J=[];for(let Q of $)for(let Z of EF(Q)){let W=i4(Z,PF);if(wF(W))J.push(W)}return _Q(J)}function g3($={}){return a2(bF($))}async function n4($={}){let J=n2($);if(J.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Z=await r2(J,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Z.plugins,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}let Q=await W2({pluginPaths:J,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Q.extensions??[],shutdown:Q.shutdown,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}var a4="SKILL.md",cF="managed.json",uF=new Set([".md",".markdown",".txt"]);function PQ($){return $.trim().toLowerCase()}function j2($){let J=$;return J?.code==="ENOENT"||J?.code==="EACCES"||J?.code==="EPERM"||J?.code==="ELOOP"}function o4($){return uF.has(s4($).toLowerCase())}function c3($){let J=[],Q=new Set;for(let Z of $){let W=s2(Z);if(Q.has(W))continue;Q.add(W),J.push(Z)}return J}function dF($){let J=[...$?.directories??EQ($?.workspacePath)];if($?.pluginSkillDirectories)J.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)J.push(...g3({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return c3(J)}async function NQ($){try{let J=await TQ($,{withFileTypes:!0}),Q=[];for(let Z of J){if(!Z.isDirectory())continue;let W=q0($,Z.name),j=q0(W,cF);try{let f=await hF(j,"utf8"),X=JSON.parse(f);if(X&&typeof X==="object")Q.push(W)}catch(f){if(j2(f))continue;if(f?.name==="SyntaxError")continue;throw f}}return Q.sort((Z,W)=>Z.localeCompare(W))}catch(J){if(j2(J))return[];throw J}}function wQ($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q;try{let j=vF.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}catch(j){let f=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:f}}}function t4($,J,Q){if($===void 0||$===null){if(Q)throw Error(`Missing required frontmatter field '${J}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${J}' must be a string.`);let Z=$.trim();if(!Z&&Q)throw Error(`Frontmatter field '${J}' cannot be empty.`);return Z||void 0}function f2($,J){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${J}' must be a boolean.`);return $}function lF($,J){if(B1($.filePath).toLowerCase()!==m3.toLowerCase())return B1($.filePath,s4($.filePath));if(J&&s2($.filePath)===s2(J,m3))return"Workspace AGENTS.md";if(s2($.filePath)===s2(IF()))return"Global AGENTS.md";return B1($.filePath,s4($.filePath))}function SQ($,J){let{data:Q,body:Z,parseError:W}=wQ($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in skill file.");let X=t4(Q.name,"name",!1)??J.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:t4(Q.description,"description",!1),disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function CQ($,J){let{data:Q,body:Z,parseError:W}=wQ($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in rule file.");let f=t4(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing rule name.");return{name:f,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function yQ($,J){let{data:Q,body:Z,parseError:W}=wQ($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in workflow file.");let f=t4(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing workflow name.");return{name:f,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function EQ($){return gF($)}function bQ($){return xF($)}function hQ($){return mF($)}async function u3($){if(B1($)===".cline"){let J=await NQ($);return(await Promise.all(J.map((Z)=>u3(q0(Z,MQ))))).flat()}try{let J=await TQ($,{withFileTypes:!0}),Q=[];for(let Z of J){if(Z.isFile()&&Z.name===a4){Q.push({directoryPath:$,fileName:Z.name,filePath:q0($,Z.name)});continue}let W=q0($,Z.name);if(Z.isDirectory()||Z.isSymbolicLink()&&await OQ(W).then((f)=>f.isDirectory()).catch((f)=>{if(j2(f))return!1;throw f}))Q.push({directoryPath:W,fileName:a4,filePath:q0(W,a4)})}return Q}catch(J){if(j2(J))return[];throw J}}async function e4($){if(B1($)===".cline"){let J=await NQ($);return(await Promise.all(J.map((Z)=>e4(q0(Z,"rules.md"))))).flat()}try{if((await OQ($)).isFile())return[{directoryPath:kF($),fileName:B1($),filePath:$}]}catch(J){if(!j2(J))throw J}try{let Q=(await TQ($,{withFileTypes:!0})).filter((W)=>W.isFile()&&o4(W.name)).map((W)=>({directoryPath:$,fileName:W.name,filePath:q0($,W.name)})),Z=q0($,"AGENTS.md");try{if((await OQ(Z)).isFile()){if(!Q.some((f)=>f.fileName==="AGENTS.md"))Q.push({directoryPath:$,fileName:"AGENTS.md",filePath:Z})}}catch{}return Q}catch(J){if(j2(J))return[];throw J}}async function pF($){if(B1($)===".cline"){let J=await NQ($);return(await Promise.all(J.map((Z)=>e4(q0(Z,qQ))))).flat()}return e4($)}function kQ($){let J=dF($),Q=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Q?c3([...J,Q]):J,discoverFiles:u3,includeFile:(Z)=>Z===a4,parseFile:(Z)=>SQ(Z.content,B1(Z.directoryPath)),resolveId:(Z)=>PQ(Z.name)}}function IQ($){let J=$?.directories??bQ($?.workspacePath),Q=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Q?[...J,Q]:J,discoverFiles:e4,includeFile:(Z,W)=>Z===".clinerules"||o4(Z)||o4(W),parseFile:(Z)=>CQ(Z.content,lF(Z,$?.workspacePath)),resolveId:(Z)=>PQ(Z.name)}}function xQ($){let J=$?.directories??hQ($?.workspacePath),Q=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Q?[...J,Q]:J,discoverFiles:pF,includeFile:(Z)=>o4(Z),parseFile:(Z)=>yQ(Z.content,B1(Z.filePath,s4(Z.filePath))),resolveId:(Z)=>PQ(Z.name)}}function d3($){let J=[kQ($?.skills),IQ($?.rules),xQ($?.workflows)];return new d2(J,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as l3}from"@cline/shared";function rF($,J){if($.description?.trim())return l3($.description,".");if(J==="workflow")return;return l3($.instructions,".")}function iF($){return $.disabled!==!0}function p3($,J){return[...$.getSnapshot(J).entries()].map(([Q,Z])=>({id:Q,record:Z})).filter(({record:Q})=>iF(Q.item)).map(({id:Q,record:Z})=>({id:Q,name:Z.item.name,instructions:Z.item.instructions,description:rF(Z.item,J),kind:J})).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function o2($){let J=new Map;for(let Q of[...p3($,"workflow"),...p3($,"skill")])if(!J.has(Q.name))J.set(Q.name,Q);return[...J.values()].sort((Q,Z)=>Q.name.localeCompare(Z.name))}function r3($,J){if(!$.startsWith("/")||$.length<2)return $;let Q=$.match(/^\/(\S+)/);if(!Q)return $;let Z=Q[1];if(!Z)return $;let W=Z.length+1,j=$.slice(W),f=o2(J).find((X)=>X.name===Z);return f?`${f.instructions}${j}`:$}function i3($){return $.disabled!==!0}function $6($){if($.length===0)return"";return`
48
48
 
49
49
  # Rules
50
50
  ${$.map((Q)=>`## ${Q.name}
@@ -52,17 +52,17 @@ ${Q.instructions}`).join(`
52
52
 
53
53
  `)}`}function J6($,J){let Q=$?.trim(),Z=J?.trim();if(Q&&Z)return`${Q}
54
54
 
55
- ${Z}`;return Q||Z||void 0}function iF($){return[...$.getSnapshot("rule").values()].map((Q)=>Q.item).filter(r3).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function i3($){return $6(iF($))}import{validateWithZod as kk,zodToJsonSchema as Ik}from"@cline/shared";var D0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},X2=[D0.READ_FILES,D0.SEARCH_CODEBASE,D0.RUN_COMMANDS,D0.FETCH_WEB_CONTENT,D0.APPLY_PATCH,D0.EDITOR,D0.SKILLS,D0.ASK,D0.SUBMIT_AND_EXIT];F0();import{createTool as A1,validateWithZod as K1,zodToJsonSchema as e0}from"@cline/shared";var n3="__clineInternalTelemetry";function a3($){let J=$?.__clineInternalTelemetry;return J&&typeof J==="object"&&"capture"in J&&typeof J.capture==="function"?J:void 0}import{spawn as Xj}from"node:child_process";import{StringDecoder as sF}from"node:string_decoder";import{getDefaultShell as oF,getShellArgs as tF}from"@cline/shared";import{validateWithZod as nF}from"@cline/shared";import{z as _}from"zod";var h1=6000,t2=_.string().describe("The absolute file path of a text file to read content from"),s3=_.object({start_line:_.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:_.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),b1=_.object({path:t2,start_line:s3.shape.start_line,end_line:s3.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),Q6=_.object({files:_.array(b1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),o3=_.union([Q6,b1,_.array(b1),_.array(_.string()),_.string(),_.object({files:_.array(_.union([t2,b1]))}),_.object({files:b1}),_.object({files:t2}),_.object({file_paths:_.array(t2)}),_.object({file_paths:_.string()}),_.object({paths:_.array(_.union([t2,b1]))}),_.object({paths:b1}),_.object({paths:_.string()})]),Z6=_.object({queries:_.array(_.string()).describe("Array of regex search queries to execute")}),t3=_.union([Z6,_.array(_.string()),_.string(),_.object({queries:_.string()})]),K$=_.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${h1*2} characters) to avoid timeouts.`),e2=_.object({commands:_.array(K$).describe("Array of shell commands to execute")}),e3=_.union([e2,_.object({commands:K$}),_.object({command:K$}),_.object({cmd:K$}),_.array(_.string()),_.string()]),gQ=_.object({command:_.string().min(1).describe("The executable to run directly without shell parsing."),args:_.array(_.string()).optional().describe("Optional argv list passed directly to the executable.")}),$j=_.union([K$,gQ]),mQ=_.object({commands:_.array($j).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.")}),Jj=_.union([e2,mQ,_.object({commands:$j}),_.array(gQ),gQ,_.object({command:K$}),_.object({cmd:K$}),_.array(_.string()),_.string()]),Qj=_.object({url:_.string().describe("The URL to fetch"),prompt:_.string().min(2).describe("Analysis prompt for the fetched content")}),W6=_.object({requests:_.array(Qj).describe("Array of the URLs for the web fetch requests")}),j6=_.object({path:_.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:_.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${h1} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:_.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${h1} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:_.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),f6=_.object({input:_.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),Zj=_.union([f6,_.string()]),X6=_.object({skill:_.string().min(1).describe("Name of the skill to execute."),args:_.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),Y6=_.object({question:_.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:_.array(_.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),V6=_.object({summary:_.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:_.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
55
+ ${Z}`;return Q||Z||void 0}function nF($){return[...$.getSnapshot("rule").values()].map((Q)=>Q.item).filter(i3).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function n3($){return $6(nF($))}import{validateWithZod as Ik,zodToJsonSchema as xk}from"@cline/shared";var D0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},X2=[D0.READ_FILES,D0.SEARCH_CODEBASE,D0.RUN_COMMANDS,D0.FETCH_WEB_CONTENT,D0.APPLY_PATCH,D0.EDITOR,D0.SKILLS,D0.ASK,D0.SUBMIT_AND_EXIT];F0();import{createTool as A1,validateWithZod as K1,zodToJsonSchema as e0}from"@cline/shared";var a3="__clineInternalTelemetry";function s3($){let J=$?.__clineInternalTelemetry;return J&&typeof J==="object"&&"capture"in J&&typeof J.capture==="function"?J:void 0}import{spawn as Yj}from"node:child_process";import{StringDecoder as oF}from"node:string_decoder";import{getDefaultShell as tF,getShellArgs as eF}from"@cline/shared";import{validateWithZod as aF}from"@cline/shared";import{z as _}from"zod";var h1=6000,t2=_.string().describe("The absolute file path of a text file to read content from"),o3=_.object({start_line:_.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:_.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),b1=_.object({path:t2,start_line:o3.shape.start_line,end_line:o3.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),Q6=_.object({files:_.array(b1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),t3=_.union([Q6,b1,_.array(b1),_.array(_.string()),_.string(),_.object({files:_.array(_.union([t2,b1]))}),_.object({files:b1}),_.object({files:t2}),_.object({file_paths:_.array(t2)}),_.object({file_paths:_.string()}),_.object({paths:_.array(_.union([t2,b1]))}),_.object({paths:b1}),_.object({paths:_.string()})]),Z6=_.object({queries:_.array(_.string()).describe("Array of regex search queries to execute")}),e3=_.union([Z6,_.array(_.string()),_.string(),_.object({queries:_.string()})]),K$=_.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${h1*2} characters) to avoid timeouts.`),e2=_.object({commands:_.array(K$).describe("Array of shell commands to execute")}),$j=_.union([e2,_.object({commands:K$}),_.object({command:K$}),_.object({cmd:K$}),_.array(_.string()),_.string()]),gQ=_.object({command:_.string().min(1).describe("The executable to run directly without shell parsing."),args:_.array(_.string()).optional().describe("Optional argv list passed directly to the executable.")}),Jj=_.union([K$,gQ]),mQ=_.object({commands:_.array(Jj).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.")}),Qj=_.union([e2,mQ,_.object({commands:Jj}),_.array(gQ),gQ,_.object({command:K$}),_.object({cmd:K$}),_.array(_.string()),_.string()]),Zj=_.object({url:_.string().describe("The URL to fetch"),prompt:_.string().min(2).describe("Analysis prompt for the fetched content")}),W6=_.object({requests:_.array(Zj).describe("Array of the URLs for the web fetch requests")}),j6=_.object({path:_.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:_.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${h1} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:_.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${h1} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:_.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),f6=_.object({input:_.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),Wj=_.union([f6,_.string()]),X6=_.object({skill:_.string().min(1).describe("Name of the skill to execute."),args:_.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),Y6=_.object({question:_.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:_.array(_.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),V6=_.object({summary:_.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:_.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
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 k1($){if($ instanceof Error)return $.message;return String($)}function Wj($){if(typeof $.old_text==="string"&&$.old_text.length>h1)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${h1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>h1)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${h1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class G$ extends Error{timeoutMs;constructor($,J){super($);this.name="TimeoutError",this.timeoutMs=J}}function t0($,J,Q){return Promise.race([$,new Promise((Z,W)=>{setTimeout(()=>W(new G$(Q,J)),J)})])}function H6($){let{path:J,start_line:Q,end_line:Z}=$;if(Q==null&&Z==null)return J;return`${J}:${Q??1}-${Z??"EOF"}`}function jj($){let{start_line:J,end_line:Q}=$;if(J==null||Q==null||J<=Q)return null;return`start_line must be less than or equal to end_line (received start_line: ${J}, end_line: ${Q})`}function fj($){let J=nF(Jj,$);if(typeof J==="string")return[J];if(Array.isArray(J))return J;if("commands"in J)return Array.isArray(J.commands)?J.commands:[J.commands];if("command"in J)return"args"in J?[J]:[J.command];if("cmd"in J)return[J.cmd];return[J]}function aF($){if(typeof $==="string")return $;let J=$.args??[];if(J.length===0)return $.command;let Q=J.map((Z)=>/[\s"]/u.test(Z)?JSON.stringify(Z):Z);return`${$.command} ${Q.join(" ")}`}var vQ=200;function cQ($){let J=aF($);if(J.length<=vQ)return J;let Q=J.length-vQ;return`${J.slice(0,vQ)} ... [command truncated: ${Q} more chars; full command is in the tool call input]`}var $8=48000,Y2=2000,uQ=2000,B6=48000,V2=48000;class J8 extends Error{exitCode;output;constructor($,J){super(`Command exited with code ${$}`);this.exitCode=$;this.output=J;this.name="CommandExitError"}}function Yj($){let J=Math.ceil($/2),Q=Math.max(1,$-J),Z=new sF("utf8"),W="",j="",f=0,X=(Y)=>{if(!Y)return;f+=Y.length;let V=J-W.length;if(V>0){W+=Y.slice(0,V),j=(j+Y.slice(V)).slice(-Q);return}j=(j+Y).slice(-Q)};return{append(Y){X(Z.write(Y))},snapshot(){return X(Z.end()),{text:W+j,totalChars:f,dropped:f>W.length+j.length}}}}function Vj($,J,Q){let Z=Math.ceil(J/2),W=Math.max(1,J-Z);return`${$.slice(0,Z)}
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 k1($){if($ instanceof Error)return $.message;return String($)}function jj($){if(typeof $.old_text==="string"&&$.old_text.length>h1)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${h1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>h1)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${h1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class G$ extends Error{timeoutMs;constructor($,J){super($);this.name="TimeoutError",this.timeoutMs=J}}function t0($,J,Q){return Promise.race([$,new Promise((Z,W)=>{setTimeout(()=>W(new G$(Q,J)),J)})])}function H6($){let{path:J,start_line:Q,end_line:Z}=$;if(Q==null&&Z==null)return J;return`${J}:${Q??1}-${Z??"EOF"}`}function fj($){let{start_line:J,end_line:Q}=$;if(J==null||Q==null||J<=Q)return null;return`start_line must be less than or equal to end_line (received start_line: ${J}, end_line: ${Q})`}function Xj($){let J=aF(Qj,$);if(typeof J==="string")return[J];if(Array.isArray(J))return J;if("commands"in J)return Array.isArray(J.commands)?J.commands:[J.commands];if("command"in J)return"args"in J?[J]:[J.command];if("cmd"in J)return[J.cmd];return[J]}function sF($){if(typeof $==="string")return $;let J=$.args??[];if(J.length===0)return $.command;let Q=J.map((Z)=>/[\s"]/u.test(Z)?JSON.stringify(Z):Z);return`${$.command} ${Q.join(" ")}`}var vQ=200;function cQ($){let J=sF($);if(J.length<=vQ)return J;let Q=J.length-vQ;return`${J.slice(0,vQ)} ... [command truncated: ${Q} more chars; full command is in the tool call input]`}var $8=48000,Y2=2000,uQ=2000,B6=48000,V2=48000;class J8 extends Error{exitCode;output;constructor($,J){super(`Command exited with code ${$}`);this.exitCode=$;this.output=J;this.name="CommandExitError"}}function Vj($){let J=Math.ceil($/2),Q=Math.max(1,$-J),Z=new oF("utf8"),W="",j="",f=0,X=(Y)=>{if(!Y)return;f+=Y.length;let V=J-W.length;if(V>0){W+=Y.slice(0,V),j=(j+Y.slice(V)).slice(-Q);return}j=(j+Y).slice(-Q)};return{append(Y){X(Z.write(Y))},snapshot(){return X(Z.end()),{text:W+j,totalChars:f,dropped:f>W.length+j.length}}}}function Hj($,J,Q){let Z=Math.ceil(J/2),W=Math.max(1,J-Z);return`${$.slice(0,Z)}
58
58
  [... output truncated: ${Q} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
59
- `+$.slice(-W)}function eF($,J,Q,Z,W){return new Promise((j,f)=>{let X=process.platform==="win32",Y=Xj($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X,windowsHide:!0}),V=Y.pid,H=Yj(Z),B=Yj(Z),A=!1,K=!1,G=(T)=>{if(K)return;K=!0,T()},R=()=>{if(!V)return;if(X){Xj("taskkill",["/pid",String(V),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-V,"SIGKILL")}catch{Y.kill("SIGKILL")}},D=(T)=>{A=!0,R(),G(()=>f(T))},U=setTimeout(()=>D(new G$(`Command timed out after ${Q}ms`,Q)),Q),F=()=>D(Error("Command was aborted"));if(J.signal)J.signal.addEventListener("abort",F);let O=()=>{clearTimeout(U),J.signal?.removeEventListener("abort",F)};Y.stdout?.on("data",(T)=>{H.append(T)}),Y.stderr?.on("data",(T)=>{B.append(T)}),Y.on("close",(T)=>{if(O(),A)return;let L=H.snapshot(),z=B.snapshot();if(T!==0){let M=T??1,P=W?L.text+(z.text?`
59
+ `+$.slice(-W)}function $D($,J,Q,Z,W){return new Promise((j,f)=>{let X=process.platform==="win32",Y=Yj($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X,windowsHide:!0}),V=Y.pid,H=Vj(Z),B=Vj(Z),A=!1,K=!1,G=(T)=>{if(K)return;K=!0,T()},R=()=>{if(!V)return;if(X){Yj("taskkill",["/pid",String(V),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-V,"SIGKILL")}catch{Y.kill("SIGKILL")}},D=(T)=>{A=!0,R(),G(()=>f(T))},U=setTimeout(()=>D(new G$(`Command timed out after ${Q}ms`,Q)),Q),F=()=>D(Error("Command was aborted"));if(J.signal)J.signal.addEventListener("abort",F);let O=()=>{clearTimeout(U),J.signal?.removeEventListener("abort",F)};Y.stdout?.on("data",(T)=>{H.append(T)}),Y.stderr?.on("data",(T)=>{B.append(T)}),Y.on("close",(T)=>{if(O(),A)return;let L=H.snapshot(),z=B.snapshot();if(T!==0){let M=T??1,P=W?L.text+(z.text?`
60
60
  [stderr]
61
- ${z.text}`:""):L.text,C=L.dropped||W&&z.dropped,m=W?L.totalChars+z.totalChars:L.totalChars;if(C||P.length>Z)P=Vj(P,Z,m);let n=P.length>0?`[Command exited with code ${M}]
61
+ ${z.text}`:""):L.text,C=L.dropped||W&&z.dropped,m=W?L.totalChars+z.totalChars:L.totalChars;if(C||P.length>Z)P=Hj(P,Z,m);let n=P.length>0?`[Command exited with code ${M}]
62
62
  ${P}`:`[Command exited with code ${M}]`;G(()=>f(new J8(M,n)))}else{let M=W?L.text+(z.text?`
63
63
  [stderr]
64
- ${z.text}`:""):L.text;if(L.dropped||W&&z.dropped||M.length>Z){let C=W?L.totalChars+z.totalChars:L.totalChars;M=Vj(M,Z,C)}G(()=>j(M))}}),Y.on("error",(T)=>{O(),G(()=>f(Error(`Failed to execute command: ${T.message}`)))})})}function A6($={}){let{shell:J=oF(process.platform),timeoutMs:Q=30000,env:Z={},combineOutput:W=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??$8;return(f,X,Y)=>{let V=typeof f!=="string";return eF({executable:V?f.command:J,args:V?f.args??[]:tF(J,f),cwd:X,env:Z},Y,Q,j,W)}}function Hj($,J){let Q=$.metadata?.[J];return typeof Q==="string"?Q:void 0}function Bj($,J){FW(a3($.metadata),{tool_name:"run_commands",effective_timeout_ms:J.effectiveTimeoutMs,timeout_source:J.timeoutSource,command_count:J.commandCount,duration_ms:J.durationMs,ulid:$.sessionId,mode:Hj($,"mode"),source:Hj($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function $D($){let J=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return J?.[1]??J?.[2]??J?.[3]}function JD($){let J=[];for(let Q=0;Q<$.length;Q+=1){let Z=$[Q],W=$D(Z);if(!W){J.push(Z);continue}let j=$.findIndex((X,Y)=>Y>Q&&X.trim()===W);if(j===-1){J.push(Z);continue}let f=[Z];while(Q<j){Q+=1;let X=$[Q];f.push(X)}J.push(f.join(`
65
- `))}return J}function Aj($,J={}){let Q=J.fileReadTimeoutMs??1e4;return A1({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${Y2} lines / ~${Math.round(B6/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:e0(Q6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=K1(o3,Z),f;if(typeof j==="string")f=[{path:j}];else if(Array.isArray(j))f=j.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in j)f=(Array.isArray(j.files)?j.files:[j.files]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("file_paths"in j)f=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((Y)=>({path:Y}));else if("paths"in j)f=(Array.isArray(j.paths)?j.paths:[j.paths]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else f=[j];return Promise.all(f.map(async(X)=>{let Y=jj(X);if(Y)return{query:H6(X),result:"",error:`Invalid file range: ${Y}`,success:!1};try{let V=await t0($(X,W),Q,`File read timed out after ${Q}ms`);return{query:H6(X),result:V,success:!0}}catch(V){let H=k1(V);return{query:H6(X),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function Kj($,J={}){let Q=J.searchTimeoutMs??30000,Z=J.cwd??process.cwd();return A1({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(V2/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:e0(Z6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(W,j)=>{let f=K1(t3,W),X=Array.isArray(f)?f:typeof f==="object"?Array.isArray(f.queries)?f.queries:[f.queries]:[f];return Promise.all(X.map(async(Y)=>{try{let V=await t0($(Y,Z,j),Q,`Search timed out after ${Q}ms`);return{query:Y,result:V,success:!0}}catch(V){let H=k1(V);return{query:Y,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}function Gj($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return A1({name:"run_commands",description:`Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands only when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. Output beyond ~${Math.round($8/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:e0(e2),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=K1(e3,j),Y;if(typeof X==="string")Y=[X];else if(Array.isArray(X))Y=X;else if("commands"in X)Y=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)Y=[X.command];else Y=[X.cmd];return Y=JD(Y),Promise.all(Y.map(async(V)=>{let H=Date.now(),B=cQ(V);try{let A=await t0($(V,W,f),Q,`Command timed out after ${Q}ms`);return{query:B,result:A,success:!0}}catch(A){if(A instanceof G$)Bj(f,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:Z,commandCount:Y.length,durationMs:Date.now()-H});if(A instanceof J8)return{query:B,result:A.output,error:A.message,success:!1};let K=k1(A);return{query:B,result:"",error:`Command failed: ${K}`,success:!1}}}))}})}function Fj($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return A1({name:"run_commands",description:`Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Output beyond ~${Math.round($8/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped. Include multiple commands when they are independent and safe to run concurrently.`,inputSchema:e0(mQ),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=fj(j);return Promise.all(X.map(async(Y)=>{let V=Date.now(),H=cQ(Y);try{let B=await t0($(Y,W,f),Q,`Command timed out after ${Q}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof G$)Bj(f,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Z,commandCount:X.length,durationMs:Date.now()-V});if(B instanceof J8)return{query:H,result:B.output,error:B.message,success:!1};let A=k1(B);return{query:H,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function Dj($,J={}){let Q=J.webFetchTimeoutMs??30000;return A1({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:e0(W6),timeoutMs:Q*2,retryable:!0,maxRetries:2,execute:async(Z,W)=>{let j=K1(W6,Z);return Promise.all(j.requests.map(async(f)=>{try{let X=await t0($(f.url,f.prompt,W),Q,`Web fetch timed out after ${Q}ms`);return{query:f.url,result:X,success:!0}}catch(X){let Y=k1(X);return{query:f.url,result:"",error:`Error fetching web content: ${Y}`,success:!1}}}))}})}var QD=`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:
64
+ ${z.text}`:""):L.text;if(L.dropped||W&&z.dropped||M.length>Z){let C=W?L.totalChars+z.totalChars:L.totalChars;M=Hj(M,Z,C)}G(()=>j(M))}}),Y.on("error",(T)=>{O(),G(()=>f(Error(`Failed to execute command: ${T.message}`)))})})}function A6($={}){let{shell:J=tF(process.platform),timeoutMs:Q=30000,env:Z={},combineOutput:W=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??$8;return(f,X,Y)=>{let V=typeof f!=="string";return $D({executable:V?f.command:J,args:V?f.args??[]:eF(J,f),cwd:X,env:Z},Y,Q,j,W)}}function Bj($,J){let Q=$.metadata?.[J];return typeof Q==="string"?Q:void 0}function Aj($,J){DW(s3($.metadata),{tool_name:"run_commands",effective_timeout_ms:J.effectiveTimeoutMs,timeout_source:J.timeoutSource,command_count:J.commandCount,duration_ms:J.durationMs,ulid:$.sessionId,mode:Bj($,"mode"),source:Bj($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function JD($){let J=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return J?.[1]??J?.[2]??J?.[3]}function QD($){let J=[];for(let Q=0;Q<$.length;Q+=1){let Z=$[Q],W=JD(Z);if(!W){J.push(Z);continue}let j=$.findIndex((X,Y)=>Y>Q&&X.trim()===W);if(j===-1){J.push(Z);continue}let f=[Z];while(Q<j){Q+=1;let X=$[Q];f.push(X)}J.push(f.join(`
65
+ `))}return J}function Kj($,J={}){let Q=J.fileReadTimeoutMs??1e4;return A1({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${Y2} lines / ~${Math.round(B6/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:e0(Q6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=K1(t3,Z),f;if(typeof j==="string")f=[{path:j}];else if(Array.isArray(j))f=j.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in j)f=(Array.isArray(j.files)?j.files:[j.files]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("file_paths"in j)f=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((Y)=>({path:Y}));else if("paths"in j)f=(Array.isArray(j.paths)?j.paths:[j.paths]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else f=[j];return Promise.all(f.map(async(X)=>{let Y=fj(X);if(Y)return{query:H6(X),result:"",error:`Invalid file range: ${Y}`,success:!1};try{let V=await t0($(X,W),Q,`File read timed out after ${Q}ms`);return{query:H6(X),result:V,success:!0}}catch(V){let H=k1(V);return{query:H6(X),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function Gj($,J={}){let Q=J.searchTimeoutMs??30000,Z=J.cwd??process.cwd();return A1({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(V2/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:e0(Z6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(W,j)=>{let f=K1(e3,W),X=Array.isArray(f)?f:typeof f==="object"?Array.isArray(f.queries)?f.queries:[f.queries]:[f];return Promise.all(X.map(async(Y)=>{try{let V=await t0($(Y,Z,j),Q,`Search timed out after ${Q}ms`);return{query:Y,result:V,success:!0}}catch(V){let H=k1(V);return{query:Y,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}function Fj($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return A1({name:"run_commands",description:`Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands only when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. Output beyond ~${Math.round($8/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:e0(e2),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=K1($j,j),Y;if(typeof X==="string")Y=[X];else if(Array.isArray(X))Y=X;else if("commands"in X)Y=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)Y=[X.command];else Y=[X.cmd];return Y=QD(Y),Promise.all(Y.map(async(V)=>{let H=Date.now(),B=cQ(V);try{let A=await t0($(V,W,f),Q,`Command timed out after ${Q}ms`);return{query:B,result:A,success:!0}}catch(A){if(A instanceof G$)Aj(f,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:Z,commandCount:Y.length,durationMs:Date.now()-H});if(A instanceof J8)return{query:B,result:A.output,error:A.message,success:!1};let K=k1(A);return{query:B,result:"",error:`Command failed: ${K}`,success:!1}}}))}})}function Dj($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return A1({name:"run_commands",description:`Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Output beyond ~${Math.round($8/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped. Include multiple commands when they are independent and safe to run concurrently.`,inputSchema:e0(mQ),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=Xj(j);return Promise.all(X.map(async(Y)=>{let V=Date.now(),H=cQ(Y);try{let B=await t0($(Y,W,f),Q,`Command timed out after ${Q}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof G$)Aj(f,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Z,commandCount:X.length,durationMs:Date.now()-V});if(B instanceof J8)return{query:H,result:B.output,error:B.message,success:!1};let A=k1(B);return{query:H,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function Uj($,J={}){let Q=J.webFetchTimeoutMs??30000;return A1({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:e0(W6),timeoutMs:Q*2,retryable:!0,maxRetries:2,execute:async(Z,W)=>{let j=K1(W6,Z);return Promise.all(j.requests.map(async(f)=>{try{let X=await t0($(f.url,f.prompt,W),Q,`Web fetch timed out after ${Q}ms`);return{query:f.url,result:X,success:!0}}catch(X){let Y=k1(X);return{query:f.url,result:"",error:`Error fetching web content: ${Y}`,success:!1}}}))}})}var ZD=`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:
66
66
 
67
67
  *** Begin Patch
68
68
  *** Update File: path/to/file.ts
@@ -98,82 +98,82 @@ Example:
98
98
  </div>
99
99
  );
100
100
  }
101
- *** End Patch`;function Uj($,J={}){let Q=J.applyPatchTimeoutMs??30000,Z=J.cwd??process.cwd();return A1({name:"apply_patch",description:QD,inputSchema:e0(f6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=K1(Zj,W),X=typeof f==="string"?f:f.input;try{return{query:"apply_patch",result:await t0($({input:X},Z,j),Q,`apply_patch timed out after ${Q}ms`),success:!0}}catch(Y){return{query:"apply_patch",result:"",error:`apply_patch failed: ${k1(Y)}`,success:!1}}}})}function Rj($,J={}){let Q=J.editorTimeoutMs??30000,Z=J.cwd??process.cwd();return A1({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:e0(j6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=K1(j6,W),X=f.insert_line==null?"edit":"insert",Y=Wj(f);if(Y)return{query:`${X}:${f.path}`,result:"",error:Y,success:!1};try{let V=await t0($(f,Z,j),Q,`Editor operation timed out after ${Q}ms`);return{query:`${X}:${f.path}`,result:V,success:!0}}catch(V){let H=k1(V);return{query:`${X}:${f.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function H2($,J={}){let Q=J.skillsTimeoutMs??15000,Z='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',W=A1({name:"skills",description:Z,inputSchema:e0(X6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=K1(X6,j);return t0($(X.skill,X.args||void 0,f),Q,`Skills operation timed out after ${Q}ms`)}});return Object.defineProperty(W,"description",{get(){let j=$.configuredSkills?.filter((f)=>!f.disabled).map((f)=>f.name);if(j&&j.length>0)return`${Z} Available skills: ${j.join(", ")}.`;return Z},enumerable:!0,configurable:!0}),W}function zj($){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:e0(Y6),retryable:!1,maxRetries:0,execute:async(J,Q)=>{let Z=K1(Y6,J);return $(Z.question,Z.options,Q)}}}function Lj($,J={}){let Q=J.submitTimeoutMs??15000;return A1({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:e0(V6),lifecycle:{completesRun:!0},timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=K1(V6,Z);return t0($(j.summary,j.verified,W),Q,`submit_and_exit timed out after ${Q}ms`)}})}function B2($){let{executors:J,enableReadFiles:Q=!0,enableSearch:Z=!0,enableBash:W=!0,enableWebFetch:j=!0,enableApplyPatch:f=!1,enableEditor:X=!0,enableSkills:Y=!0,enableAskQuestion:V=!0,enableSubmitAndExit:H=!1,...B}=$,A=[];if(Q&&J.readFile)A.push(Aj(J.readFile,B));if(Z&&J.search)A.push(Kj(J.search,B));if(W&&J.bash)if(process.platform==="win32")A.push(Fj(J.bash,B));else A.push(Gj(J.bash,B));if(j&&J.webFetch)A.push(Dj(J.webFetch,B));if(X&&J.editor)A.push(Rj(J.editor,B));else if(f&&J.applyPatch)A.push(Uj(J.applyPatch,B));if(Y&&J.skills)A.push(H2(J.skills,B));let K=H?J.submit:void 0;if(V&&J.askQuestion&&!K)A.push(zj(J.askQuestion));if(K)A.push(Lj(K,B));return A}import*as E0 from"node:fs/promises";import*as b0 from"node:path";var v={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},Oj=["%%bash","apply_patch","EOF","```"];class $0 extends Error{constructor($){super($);this.name="DiffError"}}function y0($){let J={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Q)=>J[Q]??Q).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class dQ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,J){this.lines=$;this.currentFiles=J}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(v.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(v.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(v.UPDATE)){this.parseUpdate($.substring(v.UPDATE.length).trim());return}if($?.startsWith(v.DELETE)){this.parseDelete($.substring(v.DELETE.length).trim());return}if($?.startsWith(v.ADD)){this.parseAdd($.substring(v.ADD.length).trim());return}throw new $0(`Unknown line while parsing: ${$}`)}checkDuplicate($,J){if($ in this.patch.actions)throw new $0(`Duplicate ${J} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let J=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new $0(`Update File Error: Missing File: ${$}`);let Q=this.currentFiles[$]??"",Z=this.parseUpdateFile(Q,$);Z.movePath=J,this.patch.actions[$]=Z,this.currentPath=void 0}parseUpdateFile($,J){let Q={type:"update",chunks:[]},Z=$.split(`
101
+ *** End Patch`;function Rj($,J={}){let Q=J.applyPatchTimeoutMs??30000,Z=J.cwd??process.cwd();return A1({name:"apply_patch",description:ZD,inputSchema:e0(f6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=K1(Wj,W),X=typeof f==="string"?f:f.input;try{return{query:"apply_patch",result:await t0($({input:X},Z,j),Q,`apply_patch timed out after ${Q}ms`),success:!0}}catch(Y){return{query:"apply_patch",result:"",error:`apply_patch failed: ${k1(Y)}`,success:!1}}}})}function zj($,J={}){let Q=J.editorTimeoutMs??30000,Z=J.cwd??process.cwd();return A1({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:e0(j6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=K1(j6,W),X=f.insert_line==null?"edit":"insert",Y=jj(f);if(Y)return{query:`${X}:${f.path}`,result:"",error:Y,success:!1};try{let V=await t0($(f,Z,j),Q,`Editor operation timed out after ${Q}ms`);return{query:`${X}:${f.path}`,result:V,success:!0}}catch(V){let H=k1(V);return{query:`${X}:${f.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function H2($,J={}){let Q=J.skillsTimeoutMs??15000,Z='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',W=A1({name:"skills",description:Z,inputSchema:e0(X6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=K1(X6,j);return t0($(X.skill,X.args||void 0,f),Q,`Skills operation timed out after ${Q}ms`)}});return Object.defineProperty(W,"description",{get(){let j=$.configuredSkills?.filter((f)=>!f.disabled).map((f)=>f.name);if(j&&j.length>0)return`${Z} Available skills: ${j.join(", ")}.`;return Z},enumerable:!0,configurable:!0}),W}function Lj($){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:e0(Y6),retryable:!1,maxRetries:0,execute:async(J,Q)=>{let Z=K1(Y6,J);return $(Z.question,Z.options,Q)}}}function _j($,J={}){let Q=J.submitTimeoutMs??15000;return A1({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:e0(V6),lifecycle:{completesRun:!0},timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=K1(V6,Z);return t0($(j.summary,j.verified,W),Q,`submit_and_exit timed out after ${Q}ms`)}})}function B2($){let{executors:J,enableReadFiles:Q=!0,enableSearch:Z=!0,enableBash:W=!0,enableWebFetch:j=!0,enableApplyPatch:f=!1,enableEditor:X=!0,enableSkills:Y=!0,enableAskQuestion:V=!0,enableSubmitAndExit:H=!1,...B}=$,A=[];if(Q&&J.readFile)A.push(Kj(J.readFile,B));if(Z&&J.search)A.push(Gj(J.search,B));if(W&&J.bash)if(process.platform==="win32")A.push(Dj(J.bash,B));else A.push(Fj(J.bash,B));if(j&&J.webFetch)A.push(Uj(J.webFetch,B));if(X&&J.editor)A.push(zj(J.editor,B));else if(f&&J.applyPatch)A.push(Rj(J.applyPatch,B));if(Y&&J.skills)A.push(H2(J.skills,B));let K=H?J.submit:void 0;if(V&&J.askQuestion&&!K)A.push(Lj(J.askQuestion));if(K)A.push(_j(K,B));return A}import*as E0 from"node:fs/promises";import*as b0 from"node:path";var v={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},Tj=["%%bash","apply_patch","EOF","```"];class $0 extends Error{constructor($){super($);this.name="DiffError"}}function y0($){let J={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Q)=>J[Q]??Q).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class dQ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,J){this.lines=$;this.currentFiles=J}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(v.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(v.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(v.UPDATE)){this.parseUpdate($.substring(v.UPDATE.length).trim());return}if($?.startsWith(v.DELETE)){this.parseDelete($.substring(v.DELETE.length).trim());return}if($?.startsWith(v.ADD)){this.parseAdd($.substring(v.ADD.length).trim());return}throw new $0(`Unknown line while parsing: ${$}`)}checkDuplicate($,J){if($ in this.patch.actions)throw new $0(`Duplicate ${J} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let J=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new $0(`Update File Error: Missing File: ${$}`);let Q=this.currentFiles[$]??"",Z=this.parseUpdateFile(Q,$);Z.movePath=J,this.patch.actions[$]=Z,this.currentPath=void 0}parseUpdateFile($,J){let Q={type:"update",chunks:[]},Z=$.split(`
102
102
  `),W=0,j=[v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(!j.some((f)=>this.lines[this.index]?.startsWith(f.trim()))){let f=this.lines[this.index],X=f?.startsWith("@@ ")?f.substring(3):void 0;if(X!==void 0||(f==="@@"?f:void 0)!==void 0)this.index++;else if(W!==0)throw new $0(`Invalid Line:
103
- ${this.lines[this.index]}`);if(X?.trim()){let D=y0(X.trim());for(let U=W;U<Z.length;U++){let F=Z[U];if(F&&(y0(F)===D||y0(F.trim())===D)){if(W=U+1,y0(F.trim())===D&&y0(F)!==D)this.fuzz++;break}}}let[V,H,B,A]=jD(this.lines,this.index),[K,G,R]=WD(Z,V,W,A);if(K===-1){let D=V.join(`
103
+ ${this.lines[this.index]}`);if(X?.trim()){let D=y0(X.trim());for(let U=W;U<Z.length;U++){let F=Z[U];if(F&&(y0(F)===D||y0(F.trim())===D)){if(W=U+1,y0(F.trim())===D&&y0(F)!==D)this.fuzz++;break}}}let[V,H,B,A]=fD(this.lines,this.index),[K,G,R]=jD(Z,V,W,A);if(K===-1){let D=V.join(`
104
104
  `);this.addWarning({path:this.currentPath||J,chunkIndex:Q.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:D.length>200?`${D.substring(0,200)}...`:D}),this.index=B}else{this.fuzz+=G;for(let D of H)D.origIndex+=K,Q.chunks.push(D);W=K+V.length,this.index=B}}return Q}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new $0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new $0(`Add File Error: File already exists: ${$}`);this.index++;let J=[],Q=[v.END,v.UPDATE,v.DELETE,v.ADD];while(this.hasMoreLines()&&!Q.some((Z)=>this.lines[this.index]?.startsWith(Z.trim()))){let Z=this.lines[this.index++];if(Z===void 0)break;if(!Z.startsWith("+"))throw new $0(`Invalid Add File line (missing '+'): ${Z}`);J.push(Z.substring(1))}this.patch.actions[$]={type:"add",newFile:J.join(`
105
- `),chunks:[]}}}function _j($,J){let Q=$.length>J.length?$:J,Z=$.length>J.length?J:$;if(Q.length===0)return 1;let W=ZD(Z,Q);return(Q.length-W)/Q.length}function ZD($,J){let Q=J.length+1,Z=$.length+1,W=Array(Q*Z).fill(0),j=(X,Y)=>W[X*Z+Y]??0,f=(X,Y,V)=>{W[X*Z+Y]=V};for(let X=0;X<=J.length;X++)f(X,0,X);for(let X=0;X<=$.length;X++)f(0,X,X);for(let X=1;X<=J.length;X++)for(let Y=1;Y<=$.length;Y++)if(J[X-1]===$[Y-1])f(X,Y,j(X-1,Y-1));else f(X,Y,1+Math.min(j(X-1,Y-1),j(X,Y-1),j(X-1,Y)));return j(J.length,$.length)}function WD($,J,Q,Z){if(J.length===0)return[Q,0,1];let W=0,j=(f)=>{let X=y0(J.join(`
105
+ `),chunks:[]}}}function Oj($,J){let Q=$.length>J.length?$:J,Z=$.length>J.length?J:$;if(Q.length===0)return 1;let W=WD(Z,Q);return(Q.length-W)/Q.length}function WD($,J){let Q=J.length+1,Z=$.length+1,W=Array(Q*Z).fill(0),j=(X,Y)=>W[X*Z+Y]??0,f=(X,Y,V)=>{W[X*Z+Y]=V};for(let X=0;X<=J.length;X++)f(X,0,X);for(let X=0;X<=$.length;X++)f(0,X,X);for(let X=1;X<=J.length;X++)for(let Y=1;Y<=$.length;Y++)if(J[X-1]===$[Y-1])f(X,Y,j(X-1,Y-1));else f(X,Y,1+Math.min(j(X-1,Y-1),j(X,Y-1),j(X-1,Y)));return j(J.length,$.length)}function jD($,J,Q,Z){if(J.length===0)return[Q,0,1];let W=0,j=(f)=>{let X=y0(J.join(`
106
106
  `));for(let V=f;V<$.length;V++){let H=y0($.slice(V,V+J.length).join(`
107
- `));if(H===X)return[V,0,1];let B=_j(H,X);if(B>W)W=B}for(let V=f;V<$.length;V++){let H=y0($.slice(V,V+J.length).map((A)=>A.trimEnd()).join(`
107
+ `));if(H===X)return[V,0,1];let B=Oj(H,X);if(B>W)W=B}for(let V=f;V<$.length;V++){let H=y0($.slice(V,V+J.length).map((A)=>A.trimEnd()).join(`
108
108
  `)),B=y0(J.map((A)=>A.trimEnd()).join(`
109
109
  `));if(H===B)return[V,1,1]}for(let V=f;V<$.length;V++){let H=y0($.slice(V,V+J.length).map((A)=>A.trim()).join(`
110
110
  `)),B=y0(J.map((A)=>A.trim()).join(`
111
111
  `));if(H===B)return[V,100,1]}let Y=0.66;for(let V=f;V<$.length;V++){let H=y0($.slice(V,V+J.length).join(`
112
- `)),B=_j(H,X);if(B>=Y)return[V,1000,B];if(B>W)W=B}return[-1,0,W]};if(Z){let[f,X,Y]=j($.length-J.length);if(f!==-1)return[f,X,Y];return[f,X,Y]=j(Q),[f,X+1e4,Y]}return j(Q)}function jD($,J){let Q=J,Z=[],W=[],j=[],f=[],X="keep",Y=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(Q<$.length){let V=$[Q];if(!V||Y.some((A)=>V.startsWith(A.trim())))break;if(V==="***")break;if(V.startsWith("***"))throw new $0(`Invalid line: ${V}`);Q++;let H=X,B=V;if(B[0]==="+")X="add";else if(B[0]==="-")X="delete";else if(B[0]===" ")X="keep";else X="keep",B=` ${B}`;if(B=B.slice(1),X==="keep"&&H!==X){if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});W=[],j=[]}if(X==="delete")W.push(B),Z.push(B);else if(X==="add")j.push(B);else Z.push(B)}if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});if(Q<$.length&&$[Q]===v.END_FILE)return Q++,[Z,f,Q,!0];return[Z,f,Q,!1]}function lQ($,J,Q){let Z=b0.isAbsolute(J),W=Z?b0.normalize(J):b0.resolve($,J);if(!Q||Z)return W;let j=b0.relative($,W);if(j.startsWith("..")||b0.isAbsolute(j))throw new $0(`Path must stay within cwd: ${J}`);return W}function fD($){return $.split(`
113
- `).map((J)=>J.replace(/\r$/,""))}function Tj($){if($.trim()==="")return!1;return Oj.some((J)=>$.startsWith(J))}function XD($){let J=0,Q=$.length;while(J<Q&&Tj($[J]??""))J++;while(Q>J&&Tj($[Q-1]??""))Q--;return $.slice(J,Q)}function YD($){let J=fD($),Q=J.findIndex((f)=>f.startsWith(v.BEGIN)),Z=-1;for(let f=J.length-1;f>=0;f--)if(J[f]?.startsWith(v.END)){Z=f;break}if(Q!==-1||Z!==-1){if(Q===-1||Z===-1||Z<Q)throw new $0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:J.slice(Q,Z+1)}}let W=XD(J);while(W.length>0&&W[0]==="")W.shift();while(W.length>0&&W[W.length-1]==="")W.pop();return{lines:[v.BEGIN,...W,v.END]}}function VD($,J){let Q=new Set;for(let Z of $)for(let W of J)if(Z.startsWith(W)){Q.add(Z.substring(W.length).trim());break}return[...Q]}function HD($,J,Q){if(J.length===0)return $;let Z=$.split(`
112
+ `)),B=Oj(H,X);if(B>=Y)return[V,1000,B];if(B>W)W=B}return[-1,0,W]};if(Z){let[f,X,Y]=j($.length-J.length);if(f!==-1)return[f,X,Y];return[f,X,Y]=j(Q),[f,X+1e4,Y]}return j(Q)}function fD($,J){let Q=J,Z=[],W=[],j=[],f=[],X="keep",Y=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(Q<$.length){let V=$[Q];if(!V||Y.some((A)=>V.startsWith(A.trim())))break;if(V==="***")break;if(V.startsWith("***"))throw new $0(`Invalid line: ${V}`);Q++;let H=X,B=V;if(B[0]==="+")X="add";else if(B[0]==="-")X="delete";else if(B[0]===" ")X="keep";else X="keep",B=` ${B}`;if(B=B.slice(1),X==="keep"&&H!==X){if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});W=[],j=[]}if(X==="delete")W.push(B),Z.push(B);else if(X==="add")j.push(B);else Z.push(B)}if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});if(Q<$.length&&$[Q]===v.END_FILE)return Q++,[Z,f,Q,!0];return[Z,f,Q,!1]}function lQ($,J,Q){let Z=b0.isAbsolute(J),W=Z?b0.normalize(J):b0.resolve($,J);if(!Q||Z)return W;let j=b0.relative($,W);if(j.startsWith("..")||b0.isAbsolute(j))throw new $0(`Path must stay within cwd: ${J}`);return W}function XD($){return $.split(`
113
+ `).map((J)=>J.replace(/\r$/,""))}function Mj($){if($.trim()==="")return!1;return Tj.some((J)=>$.startsWith(J))}function YD($){let J=0,Q=$.length;while(J<Q&&Mj($[J]??""))J++;while(Q>J&&Mj($[Q-1]??""))Q--;return $.slice(J,Q)}function VD($){let J=XD($),Q=J.findIndex((f)=>f.startsWith(v.BEGIN)),Z=-1;for(let f=J.length-1;f>=0;f--)if(J[f]?.startsWith(v.END)){Z=f;break}if(Q!==-1||Z!==-1){if(Q===-1||Z===-1||Z<Q)throw new $0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:J.slice(Q,Z+1)}}let W=YD(J);while(W.length>0&&W[0]==="")W.shift();while(W.length>0&&W[W.length-1]==="")W.pop();return{lines:[v.BEGIN,...W,v.END]}}function HD($,J){let Q=new Set;for(let Z of $)for(let W of J)if(Z.startsWith(W)){Q.add(Z.substring(W.length).trim());break}return[...Q]}function BD($,J,Q){if(J.length===0)return $;let Z=$.split(`
114
114
  `),W=[],j=0;for(let f of J){if(f.origIndex>Z.length)throw new $0(`${Q}: chunk.origIndex ${f.origIndex} > lines.length ${Z.length}`);if(j>f.origIndex)throw new $0(`${Q}: currentIndex ${j} > chunk.origIndex ${f.origIndex}`);W.push(...Z.slice(j,f.origIndex)),W.push(...f.insLines),j=f.origIndex+f.delLines.length}return W.push(...Z.slice(j)),W.join(`
115
- `)}async function BD($,J,Q,Z){let W=VD($,[v.UPDATE,v.DELETE]),j={};for(let f of W){let X=lQ(J,f,Z),Y;try{Y=await E0.readFile(X,Q)}catch{throw new $0(`File not found: ${f}`)}j[f]=Y.replace(/\r\n/g,`
116
- `)}return j}function AD($,J){let Q={};for(let[Z,W]of Object.entries($.actions))switch(W.type){case"delete":Q[Z]={type:"delete",oldContent:J[Z]};break;case"add":if(W.newFile===void 0)throw new $0("ADD action without file content");Q[Z]={type:"add",newContent:W.newFile};break;case"update":Q[Z]={type:"update",oldContent:J[Z],newContent:HD(J[Z]??"",W.chunks,Z),movePath:W.movePath};break}return Q}function KD($){let J=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Q of $){let Z=Q.chunkIndex===void 0?"unknown":String(Q.chunkIndex+1);if(J.push(`${Q.path}: hunk ${Z}: ${Q.message}`),Q.context)J.push(`Context:
115
+ `)}async function AD($,J,Q,Z){let W=HD($,[v.UPDATE,v.DELETE]),j={};for(let f of W){let X=lQ(J,f,Z),Y;try{Y=await E0.readFile(X,Q)}catch{throw new $0(`File not found: ${f}`)}j[f]=Y.replace(/\r\n/g,`
116
+ `)}return j}function KD($,J){let Q={};for(let[Z,W]of Object.entries($.actions))switch(W.type){case"delete":Q[Z]={type:"delete",oldContent:J[Z]};break;case"add":if(W.newFile===void 0)throw new $0("ADD action without file content");Q[Z]={type:"add",newContent:W.newFile};break;case"update":Q[Z]={type:"update",oldContent:J[Z],newContent:BD(J[Z]??"",W.chunks,Z),movePath:W.movePath};break}return Q}function GD($){let J=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Q of $){let Z=Q.chunkIndex===void 0?"unknown":String(Q.chunkIndex+1);if(J.push(`${Q.path}: hunk ${Z}: ${Q.message}`),Q.context)J.push(`Context:
117
117
  ${Q.context}`)}return J.join(`
118
- `)}async function GD($,J,Q,Z){let W=[];for(let[j,f]of Object.entries($)){let X=lQ(J,j,Z);switch(f.type){case"delete":await E0.rm(X,{force:!0}),W.push(`${j}: [deleted]`);break;case"add":if(f.newContent===void 0)throw new $0(`Cannot create ${j} with no content`);await E0.mkdir(b0.dirname(X),{recursive:!0}),await E0.writeFile(X,f.newContent,{encoding:Q}),W.push(j);break;case"update":{if(f.newContent===void 0)throw new $0(`UPDATE change for ${j} has no new content`);if(f.movePath){let Y=lQ(J,f.movePath,Z);await E0.mkdir(b0.dirname(Y),{recursive:!0}),await E0.writeFile(Y,f.newContent,{encoding:Q}),await E0.rm(X,{force:!0}),W.push(`${j} -> ${f.movePath}`)}else await E0.writeFile(X,f.newContent,{encoding:Q}),W.push(j);break}}}return W}function K6($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0}=$;return async(Z,W,j)=>{let f=YD(Z.input),X=await BD(f.lines,W,J,Q),Y=new dQ(f.lines,X),{patch:V,fuzz:H}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new $0(KD(V.warnings));let B=AD(V,X),A=await GD(B,W,J,Q),K=["Successfully applied patch to the following files:"];for(let G of A)K.push(G);if(H>0)K.push(`Note: Patch applied with fuzz factor ${H}`);return K.join(`
119
- `)}}import*as i0 from"node:fs/promises";import*as r0 from"node:path";function FD($,J,Q){let Z=r0.isAbsolute(J),W=Z?r0.normalize(J):r0.resolve($,J);if(!Q)return W;if(Z)return W;let j=r0.relative($,W);if(j.startsWith("..")||r0.isAbsolute(j))throw Error(`Path must stay within cwd: ${J}`);return W}function DD($,J){if(J.length===0)return 0;return $.split(J).length-1}function UD($,J,Q){let Z=$.split(`
118
+ `)}async function FD($,J,Q,Z){let W=[];for(let[j,f]of Object.entries($)){let X=lQ(J,j,Z);switch(f.type){case"delete":await E0.rm(X,{force:!0}),W.push(`${j}: [deleted]`);break;case"add":if(f.newContent===void 0)throw new $0(`Cannot create ${j} with no content`);await E0.mkdir(b0.dirname(X),{recursive:!0}),await E0.writeFile(X,f.newContent,{encoding:Q}),W.push(j);break;case"update":{if(f.newContent===void 0)throw new $0(`UPDATE change for ${j} has no new content`);if(f.movePath){let Y=lQ(J,f.movePath,Z);await E0.mkdir(b0.dirname(Y),{recursive:!0}),await E0.writeFile(Y,f.newContent,{encoding:Q}),await E0.rm(X,{force:!0}),W.push(`${j} -> ${f.movePath}`)}else await E0.writeFile(X,f.newContent,{encoding:Q}),W.push(j);break}}}return W}function K6($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0}=$;return async(Z,W,j)=>{let f=VD(Z.input),X=await AD(f.lines,W,J,Q),Y=new dQ(f.lines,X),{patch:V,fuzz:H}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new $0(GD(V.warnings));let B=KD(V,X),A=await FD(B,W,J,Q),K=["Successfully applied patch to the following files:"];for(let G of A)K.push(G);if(H>0)K.push(`Note: Patch applied with fuzz factor ${H}`);return K.join(`
119
+ `)}}import*as i0 from"node:fs/promises";import*as r0 from"node:path";function DD($,J,Q){let Z=r0.isAbsolute(J),W=Z?r0.normalize(J):r0.resolve($,J);if(!Q)return W;if(Z)return W;let j=r0.relative($,W);if(j.startsWith("..")||r0.isAbsolute(j))throw Error(`Path must stay within cwd: ${J}`);return W}function UD($,J){if(J.length===0)return 0;return $.split(J).length-1}function RD($,J,Q){let Z=$.split(`
120
120
  `),W=J.split(`
121
121
  `),j=Math.max(Z.length,W.length),f=["```diff"],X=0;for(let Y=0;Y<j;Y++){if(X>=Q){f.push("... diff truncated ...");break}let V=Z[Y],H=W[Y];if(V===H)continue;let B=Y+1;if(V!==void 0)f.push(`-${B}: ${V}`),X++;if(H!==void 0&&X<Q)f.push(`+${B}: ${H}`),X++}return f.push("```"),f.join(`
122
- `)}async function RD($,J,Q){return await i0.mkdir(r0.dirname($),{recursive:!0}),await i0.writeFile($,J,{encoding:Q}),`File created successfully at: ${$}`}async function zD($){try{return await i0.access($),!0}catch{return!1}}async function LD($,J,Q,Z,W){let j=await i0.readFile($,Z),f=DD(j,J);if(f===0)throw Error(`No replacement performed: text not found in ${$}.`);if(f>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let X=j.replace(J,Q??"");await i0.writeFile($,X,{encoding:Z});let Y=UD(j,X,W);return`Edited ${$}
123
- ${Y}`}async function _D($,J,Q,Z){let j=(await i0.readFile($,Z)).split(`
122
+ `)}async function zD($,J,Q){return await i0.mkdir(r0.dirname($),{recursive:!0}),await i0.writeFile($,J,{encoding:Q}),`File created successfully at: ${$}`}async function LD($){try{return await i0.access($),!0}catch{return!1}}async function _D($,J,Q,Z,W){let j=await i0.readFile($,Z),f=UD(j,J);if(f===0)throw Error(`No replacement performed: text not found in ${$}.`);if(f>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let X=j.replace(J,Q??"");await i0.writeFile($,X,{encoding:Z});let Y=RD(j,X,W);return`Edited ${$}
123
+ ${Y}`}async function OD($,J,Q,Z){let j=(await i0.readFile($,Z)).split(`
124
124
  `),f=j.length+1;if(J<1||J>f)throw Error(`Invalid insert_line: ${J}. insert_line must be a positive one-based boundary line in the range 1-${f}. Use ${f} to append at EOF.`);let X=J-1;return j.splice(X,0,...Q.split(`
125
125
  `)),await i0.writeFile($,j.join(`
126
- `),{encoding:Z}),`Inserted content at line ${J} in ${$}.`}function G6($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0,maxDiffLines:Z=200}=$;return async(W,j,f)=>{let X=FD(j,W.path,Q);if(W.insert_line!=null)return _D(X,W.insert_line,W.new_text,J);if(!await zD(X))return RD(X,W.new_text,J);if(W.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return LD(X,W.old_text,W.new_text,J,Z)}}import{createReadStream as OD}from"node:fs";import*as F6 from"node:fs/promises";import*as I1 from"node:path";import{createInterface as TD}from"node:readline";import{resolveExistingFilePath as MD}from"@cline/shared/storage";var qD=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),PD={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},Mj=1e8,ND=50000;function qj($){let{reason:J}=$;if(J instanceof Error)return J;if(J!==void 0)return Error(String(J));return Error("File read was aborted")}async function wD($,J,Q,Z,W,j){if(j?.aborted)throw qj(j);let f=Math.max(Z??1,1),X=W??Number.POSITIVE_INFINITY,Y=Number.isFinite(X),V=Y?X:f+ND-1,H=[],B=0,A=0,K=!1,G=!1,R=Number.isFinite(X)?Math.min(X,f+Y2-1):f+Y2-1,D=Q?String(R).length+3:0,U=OD($,{encoding:J}),F=TD({input:U,crlfDelay:Number.POSITIVE_INFINITY}),O=j?()=>U.destroy(qj(j)):void 0;if(j&&O)j.addEventListener("abort",O,{once:!0});try{for await(let C of F){if(A+=1,A>X){A=X;break}if(!Y&&K&&A>=V){G=!0;break}if(A<f||K)continue;if(H.length>=Y2){K=!0;continue}let m=C;if(m.length>uQ)m=`${m.slice(0,uQ)} [line truncated]`;let n=B+m.length+D+1;if(n>B6&&H.length>0){K=!0;continue}H.push({lineNumber:A,text:m}),B=n}}finally{if(j&&O)j.removeEventListener("abort",O);F.close(),U.destroy()}let T=String(H[H.length-1]?.lineNumber??A).length,L=H.map(({lineNumber:C,text:m})=>Q?`${String(C).padStart(T," ")} | ${m}`:m).join(`
126
+ `),{encoding:Z}),`Inserted content at line ${J} in ${$}.`}function G6($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0,maxDiffLines:Z=200}=$;return async(W,j,f)=>{let X=DD(j,W.path,Q);if(W.insert_line!=null)return OD(X,W.insert_line,W.new_text,J);if(!await LD(X))return zD(X,W.new_text,J);if(W.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return _D(X,W.old_text,W.new_text,J,Z)}}import{createReadStream as TD}from"node:fs";import*as F6 from"node:fs/promises";import*as I1 from"node:path";import{createInterface as MD}from"node:readline";import{resolveExistingFilePath as qD}from"@cline/shared/storage";var PD=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),ND={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},qj=1e8,wD=50000;function Pj($){let{reason:J}=$;if(J instanceof Error)return J;if(J!==void 0)return Error(String(J));return Error("File read was aborted")}async function SD($,J,Q,Z,W,j){if(j?.aborted)throw Pj(j);let f=Math.max(Z??1,1),X=W??Number.POSITIVE_INFINITY,Y=Number.isFinite(X),V=Y?X:f+wD-1,H=[],B=0,A=0,K=!1,G=!1,R=Number.isFinite(X)?Math.min(X,f+Y2-1):f+Y2-1,D=Q?String(R).length+3:0,U=TD($,{encoding:J}),F=MD({input:U,crlfDelay:Number.POSITIVE_INFINITY}),O=j?()=>U.destroy(Pj(j)):void 0;if(j&&O)j.addEventListener("abort",O,{once:!0});try{for await(let C of F){if(A+=1,A>X){A=X;break}if(!Y&&K&&A>=V){G=!0;break}if(A<f||K)continue;if(H.length>=Y2){K=!0;continue}let m=C;if(m.length>uQ)m=`${m.slice(0,uQ)} [line truncated]`;let n=B+m.length+D+1;if(n>B6&&H.length>0){K=!0;continue}H.push({lineNumber:A,text:m}),B=n}}finally{if(j&&O)j.removeEventListener("abort",O);F.close(),U.destroy()}let T=String(H[H.length-1]?.lineNumber??A).length,L=H.map(({lineNumber:C,text:m})=>Q?`${String(C).padStart(T," ")} | ${m}`:m).join(`
127
127
  `),z=H[H.length-1]?.lineNumber;if(z===void 0)return L;let M=Math.min(X,A);if(z>=M)return L;let P=G?`${A}+ lines`:M;return`${L}
128
128
 
129
- [Showing lines ${f}-${z} of ${P}. Use start_line/end_line to read other sections.]`}function D6($={}){let{maxFileSizeBytes:J,encoding:Q,includeLineNumbers:Z}={...PD,...$};return async(W,j)=>{let{path:f,start_line:X,end_line:Y}=W,V=I1.isAbsolute(f)?I1.normalize(f):I1.resolve(process.cwd(),f),H=MD(V)??V,B=I1.extname(H).toLowerCase(),A=qD.get(B),K=await F6.stat(H);if(!K.isFile())throw Error(`Path is not a file: ${H}`);if(A){if(K.size>J)throw Error(`Image file too large: ${K.size} bytes (max: ${J} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let G=await F6.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:G.toString("base64"),mediaType:A}]}if(K.size>Mj)throw Error(`Text file too large to stream safely: ${K.size} bytes (max: ${Mj} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return wD(H,Q,Z,X,Y,j.signal)}}import{spawn as bj}from"node:child_process";import*as hj from"node:fs/promises";import*as z6 from"node:path";import{spawn as SD}from"node:child_process";import{readdir as CD}from"node:fs/promises";import rQ from"node:path";import{isMainThread as wj,parentPort as Pj,Worker as yD}from"node:worker_threads";var ED=15000,bD=600000,hD=1000,kD=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function Nj($){let J=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return J==="EACCES"||J==="EPERM"||J==="ENOENT"}var A2=new Map;function ID(){if(!wj)return!1;return!0}function xD($){if(A2.size<=1)return;for(let[J,Q]of A2.entries()){if(Q.pending)continue;if($-Q.lastAccessedAt>bD)A2.delete(J)}}function gD($,J){return rQ.relative($,J).split(rQ.sep).join("/")}async function mD($){let Q=(await new Promise((Z,W)=>{let j=SD("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),f="",X="";j.stdout.on("data",(Y)=>{f+=Y.toString()}),j.stderr.on("data",(Y)=>{X+=Y.toString()}),j.on("error",W),j.on("close",(Y)=>{if(Y===0){Z(f);return}W(Error(X||`rg exited with code ${Y}`))})})).split(/\r?\n/).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>Z.replace(/\\/g,"/"));return new Set(Q)}async function Sj($,J,Q){let Z;try{Z=await CD(J,{withFileTypes:!0})}catch(W){if(Nj(W))return;throw W}for(let W of Z){let j=rQ.join(J,W.name);if(W.isDirectory()){if(kD.has(W.name))continue;try{await Sj($,j,Q)}catch(f){if(Nj(f))continue;throw f}continue}if(W.isFile())Q.add(gD($,j))}}async function vD($){let J=new Set;return await Sj($,$,J),J}async function U6($){try{return await mD($)}catch{return vD($)}}function cD(){if(wj||!Pj)return;let $=Pj;$.on("message",(J)=>{if(J.type!=="index")return;U6(J.cwd).then((Q)=>{let Z={type:"indexResult",requestId:J.requestId,files:Array.from(Q)};$.postMessage(Z)}).catch((Q)=>{let Z={type:"indexResult",requestId:J.requestId,error:Q instanceof Error?Q.message:"Failed to build file index"};$.postMessage(Z)})})}class Cj{worker=new yD(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let J=this.pending.get($.requestId);if(!J)return;if(this.pending.delete($.requestId),$.error){J.reject(Error($.error));return}J.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let J=++this.nextRequestId,Q=new Promise((W,j)=>{let f=setTimeout(()=>{this.pending.delete(J),W(null)},hD);f.unref(),this.pending.set(J,{resolve:(X)=>{clearTimeout(f),W(X)},reject:(X)=>{clearTimeout(f),j(X)}})}),Z={type:"index",requestId:J,cwd:$};return this.worker.postMessage(Z),Q}flushPending($){for(let[J,Q]of this.pending.entries())Q.reject($),this.pending.delete(J)}}cD();var pQ;function uD(){if(!ID())return null;if(pQ===void 0)pQ=new Cj;return pQ}async function dD($){let J=uD();if(!J)return U6($);try{let Q=await J.requestIndex($);if(Q===null)return U6($);return new Set(Q)}catch{return U6($)}}async function F$($,J={}){let Q=J.ttlMs??ED,Z=Date.now();xD(Z);let W=A2.get($);if(W&&Q>0&&Z-W.lastBuiltAt<=Q&&W.files.size>0)return W.lastAccessedAt=Z,W.files;if(W?.pending)return W.lastAccessedAt=Z,W.pending;let j=dD($).then((f)=>{return A2.set($,{files:f,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),f});return A2.set($,{files:W?.files??new Set,lastBuiltAt:W?.lastBuiltAt??0,lastAccessedAt:Z,pending:j}),j}async function yj($,J={}){await F$($,{...J,ttlMs:0})}import{stat as lD}from"node:fs/promises";import D$ from"node:path";var pD=/[),.:;!?`'"]+$/,rD=/^[(`'"]+/;function iD($){let J=$.matchAll(/(^|[\s])@([^\s]+)/g),Q=[];for(let Z of J){let W=(Z[2]??"").trim();if(W.length===0)continue;let j=W.replace(rD,"").replace(pD,"");if(j.length===0||j.includes("@"))continue;Q.push(j)}return Array.from(new Set(Q))}function nD($,J){let Q=$.replace(/\\/g,"/"),Z=D$.isAbsolute(Q)?D$.resolve(Q):D$.resolve(J,Q),W=D$.relative(J,Z);if(W.startsWith("..")||D$.isAbsolute(W))return;return W.split(D$.sep).join("/")}async function R6($,J,Q={}){let Z=iD($);if(Z.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:W,maxFileBytes:j,maxTotalBytes:f}=Q,X=await F$(J,{ttlMs:Q.ttlMs}),Y=[],V=[],H=[],B=0;for(let A of Z){if(W&&H.length>=W){V.push(A);continue}let K=nD(A,J);if(!K||!X.has(K)){V.push(A);continue}if(!j||!f){Y.push(K);continue}let G=D$.join(J,K);try{if(!(await lD(G)).isFile()){V.push(A);continue}let D=B+j;if(D>f){V.push(A);continue}B=D,Y.push(K)}catch{V.push(A)}}return{prompt:$,mentions:Z,matchedFiles:Y,ignoredMentions:V}}var aD=["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"],sD=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],U$=null;function oD(){if(U$!==null)return Promise.resolve(U$);return new Promise(($)=>{let J=bj("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});J.on("close",(Q)=>{U$=Q===0,$(U$)}),J.on("error",()=>{U$=!1,$(!1)}),setTimeout(()=>{if(!J.killed)J.kill("SIGTERM");if(U$===null)U$=!1,$(!1)},1000)})}function tD($,J,Q,Z,W=5000,j){return new Promise((f)=>{let X=bj("rg",["--json",`--context=${Z}`,"--max-count=1","-i",$],{cwd:J,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V=!1,H=()=>{if(!X.killed)X.kill("SIGTERM")},B=setTimeout(()=>{if(!V)V=!0,H(),f(null)},W),A=(K)=>{if(!V)V=!0,clearTimeout(B),H(),f(K)};if(j?.aborted){H(),f(null);return}j?.addEventListener("abort",()=>{A(null)}),X.stdout.on("data",(K)=>{Y+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=Y.split(`
130
- `).filter((D)=>D.trim());for(let D of R){if(G.length>=Q)break;let U=JSON.parse(D);if(U.type==="match"){let F=U.data,O=[];if(U.data.submatches&&U.data.submatches.length>0){let T=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:O})}}else if(U.type==="context"&&G.length>0){let F=G[G.length-1],O=U.data.line_number===F.line?">":" ";F.context.push(`${O} ${U.data.line_number}: ${U.data.lines?.text??U.data.line?.text??""}`)}}A(G.length>0?G:null)}catch{A(null)}return}A(null)}),X.on("error",()=>{A(null)})})}function eD($,J,Q,Z){let W=$.split("/"),j=W[W.length-1]??"";if(W.length-1>Z)return!1;for(let Y=0;Y<W.length-1;Y++)if(J.has(W[Y]??""))return!1;let X=z6.posix.extname(j).slice(1).toLowerCase();return Q.has(X)||!X&&!j.startsWith(".")}function L6($={}){let{includeExtensions:J=aD,excludeDirs:Q=sD,maxResults:Z=100,contextLines:W=2,maxDepth:j=20}=$,f=new Set(Q),X=new Set(J.map((Y)=>Y.toLowerCase()));return async(Y,V,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let B=await oD(),A=null;if(B)A=await tD(Y,V,Z,W,5000,H.signal);if(A){let F=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${Y}`,""];for(let O of A)F.push(`${O.file}:${O.line}:${O.column}`),F.push(...O.context),F.push("");if(A.length>=Z)F.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return Ej(F.join(`
131
- `))}let K;try{K=new RegExp(Y,"gim")}catch(F){throw Error(`Invalid regex pattern: ${Y}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,D=await F$(V);for(let F of D){if(H.signal?.aborted)throw Error("Search operation aborted");if(!eD(F,f,X,j))continue;if(G.length>=Z)break;R++;let O=z6.join(V,F);try{let L=(await hj.readFile(O,"utf-8")).split(`
129
+ [Showing lines ${f}-${z} of ${P}. Use start_line/end_line to read other sections.]`}function D6($={}){let{maxFileSizeBytes:J,encoding:Q,includeLineNumbers:Z}={...ND,...$};return async(W,j)=>{let{path:f,start_line:X,end_line:Y}=W,V=I1.isAbsolute(f)?I1.normalize(f):I1.resolve(process.cwd(),f),H=qD(V)??V,B=I1.extname(H).toLowerCase(),A=PD.get(B),K=await F6.stat(H);if(!K.isFile())throw Error(`Path is not a file: ${H}`);if(A){if(K.size>J)throw Error(`Image file too large: ${K.size} bytes (max: ${J} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let G=await F6.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:G.toString("base64"),mediaType:A}]}if(K.size>qj)throw Error(`Text file too large to stream safely: ${K.size} bytes (max: ${qj} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return SD(H,Q,Z,X,Y,j.signal)}}import{spawn as hj}from"node:child_process";import*as kj from"node:fs/promises";import*as z6 from"node:path";import{spawn as CD}from"node:child_process";import{readdir as yD}from"node:fs/promises";import rQ from"node:path";import{isMainThread as Sj,parentPort as Nj,Worker as ED}from"node:worker_threads";var bD=15000,hD=600000,kD=1000,ID=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function wj($){let J=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return J==="EACCES"||J==="EPERM"||J==="ENOENT"}var A2=new Map;function xD(){if(!Sj)return!1;return!0}function gD($){if(A2.size<=1)return;for(let[J,Q]of A2.entries()){if(Q.pending)continue;if($-Q.lastAccessedAt>hD)A2.delete(J)}}function mD($,J){return rQ.relative($,J).split(rQ.sep).join("/")}async function vD($){let Q=(await new Promise((Z,W)=>{let j=CD("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),f="",X="";j.stdout.on("data",(Y)=>{f+=Y.toString()}),j.stderr.on("data",(Y)=>{X+=Y.toString()}),j.on("error",W),j.on("close",(Y)=>{if(Y===0){Z(f);return}W(Error(X||`rg exited with code ${Y}`))})})).split(/\r?\n/).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>Z.replace(/\\/g,"/"));return new Set(Q)}async function Cj($,J,Q){let Z;try{Z=await yD(J,{withFileTypes:!0})}catch(W){if(wj(W))return;throw W}for(let W of Z){let j=rQ.join(J,W.name);if(W.isDirectory()){if(ID.has(W.name))continue;try{await Cj($,j,Q)}catch(f){if(wj(f))continue;throw f}continue}if(W.isFile())Q.add(mD($,j))}}async function cD($){let J=new Set;return await Cj($,$,J),J}async function U6($){try{return await vD($)}catch{return cD($)}}function uD(){if(Sj||!Nj)return;let $=Nj;$.on("message",(J)=>{if(J.type!=="index")return;U6(J.cwd).then((Q)=>{let Z={type:"indexResult",requestId:J.requestId,files:Array.from(Q)};$.postMessage(Z)}).catch((Q)=>{let Z={type:"indexResult",requestId:J.requestId,error:Q instanceof Error?Q.message:"Failed to build file index"};$.postMessage(Z)})})}class yj{worker=new ED(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let J=this.pending.get($.requestId);if(!J)return;if(this.pending.delete($.requestId),$.error){J.reject(Error($.error));return}J.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let J=++this.nextRequestId,Q=new Promise((W,j)=>{let f=setTimeout(()=>{this.pending.delete(J),W(null)},kD);f.unref(),this.pending.set(J,{resolve:(X)=>{clearTimeout(f),W(X)},reject:(X)=>{clearTimeout(f),j(X)}})}),Z={type:"index",requestId:J,cwd:$};return this.worker.postMessage(Z),Q}flushPending($){for(let[J,Q]of this.pending.entries())Q.reject($),this.pending.delete(J)}}uD();var pQ;function dD(){if(!xD())return null;if(pQ===void 0)pQ=new yj;return pQ}async function lD($){let J=dD();if(!J)return U6($);try{let Q=await J.requestIndex($);if(Q===null)return U6($);return new Set(Q)}catch{return U6($)}}async function F$($,J={}){let Q=J.ttlMs??bD,Z=Date.now();gD(Z);let W=A2.get($);if(W&&Q>0&&Z-W.lastBuiltAt<=Q&&W.files.size>0)return W.lastAccessedAt=Z,W.files;if(W?.pending)return W.lastAccessedAt=Z,W.pending;let j=lD($).then((f)=>{return A2.set($,{files:f,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),f});return A2.set($,{files:W?.files??new Set,lastBuiltAt:W?.lastBuiltAt??0,lastAccessedAt:Z,pending:j}),j}async function Ej($,J={}){await F$($,{...J,ttlMs:0})}import{stat as pD}from"node:fs/promises";import D$ from"node:path";var rD=/[),.:;!?`'"]+$/,iD=/^[(`'"]+/;function nD($){let J=$.matchAll(/(^|[\s])@([^\s]+)/g),Q=[];for(let Z of J){let W=(Z[2]??"").trim();if(W.length===0)continue;let j=W.replace(iD,"").replace(rD,"");if(j.length===0||j.includes("@"))continue;Q.push(j)}return Array.from(new Set(Q))}function aD($,J){let Q=$.replace(/\\/g,"/"),Z=D$.isAbsolute(Q)?D$.resolve(Q):D$.resolve(J,Q),W=D$.relative(J,Z);if(W.startsWith("..")||D$.isAbsolute(W))return;return W.split(D$.sep).join("/")}async function R6($,J,Q={}){let Z=nD($);if(Z.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:W,maxFileBytes:j,maxTotalBytes:f}=Q,X=await F$(J,{ttlMs:Q.ttlMs}),Y=[],V=[],H=[],B=0;for(let A of Z){if(W&&H.length>=W){V.push(A);continue}let K=aD(A,J);if(!K||!X.has(K)){V.push(A);continue}if(!j||!f){Y.push(K);continue}let G=D$.join(J,K);try{if(!(await pD(G)).isFile()){V.push(A);continue}let D=B+j;if(D>f){V.push(A);continue}B=D,Y.push(K)}catch{V.push(A)}}return{prompt:$,mentions:Z,matchedFiles:Y,ignoredMentions:V}}var sD=["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"],oD=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],U$=null;function tD(){if(U$!==null)return Promise.resolve(U$);return new Promise(($)=>{let J=hj("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});J.on("close",(Q)=>{U$=Q===0,$(U$)}),J.on("error",()=>{U$=!1,$(!1)}),setTimeout(()=>{if(!J.killed)J.kill("SIGTERM");if(U$===null)U$=!1,$(!1)},1000)})}function eD($,J,Q,Z,W=5000,j){return new Promise((f)=>{let X=hj("rg",["--json",`--context=${Z}`,"--max-count=1","-i",$],{cwd:J,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V=!1,H=()=>{if(!X.killed)X.kill("SIGTERM")},B=setTimeout(()=>{if(!V)V=!0,H(),f(null)},W),A=(K)=>{if(!V)V=!0,clearTimeout(B),H(),f(K)};if(j?.aborted){H(),f(null);return}j?.addEventListener("abort",()=>{A(null)}),X.stdout.on("data",(K)=>{Y+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=Y.split(`
130
+ `).filter((D)=>D.trim());for(let D of R){if(G.length>=Q)break;let U=JSON.parse(D);if(U.type==="match"){let F=U.data,O=[];if(U.data.submatches&&U.data.submatches.length>0){let T=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:O})}}else if(U.type==="context"&&G.length>0){let F=G[G.length-1],O=U.data.line_number===F.line?">":" ";F.context.push(`${O} ${U.data.line_number}: ${U.data.lines?.text??U.data.line?.text??""}`)}}A(G.length>0?G:null)}catch{A(null)}return}A(null)}),X.on("error",()=>{A(null)})})}function $U($,J,Q,Z){let W=$.split("/"),j=W[W.length-1]??"";if(W.length-1>Z)return!1;for(let Y=0;Y<W.length-1;Y++)if(J.has(W[Y]??""))return!1;let X=z6.posix.extname(j).slice(1).toLowerCase();return Q.has(X)||!X&&!j.startsWith(".")}function L6($={}){let{includeExtensions:J=sD,excludeDirs:Q=oD,maxResults:Z=100,contextLines:W=2,maxDepth:j=20}=$,f=new Set(Q),X=new Set(J.map((Y)=>Y.toLowerCase()));return async(Y,V,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let B=await tD(),A=null;if(B)A=await eD(Y,V,Z,W,5000,H.signal);if(A){let F=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${Y}`,""];for(let O of A)F.push(`${O.file}:${O.line}:${O.column}`),F.push(...O.context),F.push("");if(A.length>=Z)F.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return bj(F.join(`
131
+ `))}let K;try{K=new RegExp(Y,"gim")}catch(F){throw Error(`Invalid regex pattern: ${Y}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,D=await F$(V);for(let F of D){if(H.signal?.aborted)throw Error("Search operation aborted");if(!$U(F,f,X,j))continue;if(G.length>=Z)break;R++;let O=z6.join(V,F);try{let L=(await kj.readFile(O,"utf-8")).split(`
132
132
  `);for(let z=0;z<L.length;z++){let M=L[z];K.lastIndex=0;let P=K.exec(M);while(P!==null){if(G.length>=Z)break;let C=Math.max(0,z-W),m=Math.min(L.length-1,z+W),n=[];for(let o=C;o<=m;o++){let a=o===z?">":" ";n.push(`${a} ${o+1}: ${L[o]}`)}if(G.push({file:F,line:z+1,column:P.index+1,match:P[0],context:n}),P.index===K.lastIndex)K.lastIndex++;P=K.exec(M)}}}catch{}}if(G.length===0)return`No results found for pattern: ${Y}
133
- Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Y}`,`Searched ${R} files.`,""];for(let F of G)U.push(`${F.file}:${F.line}:${F.column}`),U.push(...F.context),U.push("");if(G.length>=Z)U.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return Ej(U.join(`
134
- `))}}function Ej($){if($.length<=V2)return $;let J=Math.ceil(V2/2),Q=Math.max(1,V2-J);return`${$.slice(0,J)}
133
+ Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Y}`,`Searched ${R} files.`,""];for(let F of G)U.push(`${F.file}:${F.line}:${F.column}`),U.push(...F.context),U.push("");if(G.length>=Z)U.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return bj(U.join(`
134
+ `))}}function bj($){if($.length<=V2)return $;let J=Math.ceil(V2/2),Q=Math.max(1,V2-J);return`${$.slice(0,J)}
135
135
  [... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
136
- `+$.slice(-Q)}function $U($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
136
+ `+$.slice(-Q)}function JU($){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,`
137
137
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(J,Q)=>String.fromCharCode(parseInt(Q,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
138
138
  `).replace(/\n{3,}/g,`
139
139
 
140
- `).trim()}function _6($={}){let{timeoutMs:J=30000,maxResponseBytes:Q=5000000,userAgent:Z="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:W={},followRedirects:j=!0}=$;return async(f,X,Y)=>{let V;try{V=new URL(f)}catch{throw Error(`Invalid URL: ${f}`)}if(!["http:","https:"].includes(V.protocol))throw Error(`Invalid protocol: ${V.protocol}. Only http and https are supported.`);let H=new AbortController,B=setTimeout(()=>H.abort(),J),A;if(Y.signal)A=()=>H.abort(),Y.signal.addEventListener("abort",A);try{let K=await fetch(f,{method:"GET",headers:{"User-Agent":Z,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...W},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(B),!j&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let D=[],U=0;while(!0){let{done:M,value:P}=await R.read();if(M)break;if(U+=P.length,U>Q)throw R.cancel(),Error(`Response too large: exceeded ${Q} bytes`);D.push(P)}let F=new Uint8Array(U),O=0;for(let M of D)F.set(M,O),O+=M.length;let T=new TextDecoder("utf-8").decode(F),L;if(G.includes("text/html")||G.includes("application/xhtml"))L=$U(T);else if(G.includes("application/json"))try{let M=JSON.parse(T);L=JSON.stringify(M,null,2)}catch{L=T}else L=T;let z=[`URL: ${f}`,`Content-Type: ${G}`,`Size: ${U} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)z.push(`
140
+ `).trim()}function _6($={}){let{timeoutMs:J=30000,maxResponseBytes:Q=5000000,userAgent:Z="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:W={},followRedirects:j=!0}=$;return async(f,X,Y)=>{let V;try{V=new URL(f)}catch{throw Error(`Invalid URL: ${f}`)}if(!["http:","https:"].includes(V.protocol))throw Error(`Invalid protocol: ${V.protocol}. Only http and https are supported.`);let H=new AbortController,B=setTimeout(()=>H.abort(),J),A;if(Y.signal)A=()=>H.abort(),Y.signal.addEventListener("abort",A);try{let K=await fetch(f,{method:"GET",headers:{"User-Agent":Z,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...W},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(B),!j&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let D=[],U=0;while(!0){let{done:M,value:P}=await R.read();if(M)break;if(U+=P.length,U>Q)throw R.cancel(),Error(`Response too large: exceeded ${Q} bytes`);D.push(P)}let F=new Uint8Array(U),O=0;for(let M of D)F.set(M,O),O+=M.length;let T=new TextDecoder("utf-8").decode(F),L;if(G.includes("text/html")||G.includes("application/xhtml"))L=JU(T);else if(G.includes("application/json"))try{let M=JSON.parse(T);L=JSON.stringify(M,null,2)}catch{L=T}else L=T;let z=[`URL: ${f}`,`Content-Type: ${G}`,`Size: ${U} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)z.push(`
141
141
  [Content truncated: showing first 50000 of ${L.length} characters]`);return z.push("","--- Analysis Request ---",`Prompt: ${X}`),z.join(`
142
- `)}catch(K){if(clearTimeout(B),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${J}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(Y.signal&&A)Y.signal.removeEventListener("abort",A)}}}function O6($={}){return{readFile:D6($.fileRead),search:L6($.search),bash:A6($.bash),webFetch:_6($.webFetch),applyPatch:K6($.applyPatch),editor:G6($.editor)}}var JU={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"},Q8=[{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 kj($,J){if(!J||J.length===0)return!0;let Q=$.toLowerCase();return J.some((Z)=>Q.includes(Z.toLowerCase()))}function QU($,J,Q,Z){if($.mode&&$.mode!=="any"&&$.mode!==Z)return!1;return kj(J,$.providerIdIncludes)&&kj(Q,$.modelIdIncludes)}function Z8($,J,Q,Z){if(!Z||Z.length===0)return{};let W=new Map;for(let f of Z){if(!QU(f,$,J,Q))continue;for(let X of f.disableTools??[])W.set(X,!1);for(let X of f.enableTools??[])W.set(X,!0)}let j={};for(let[f,X]of W.entries())j[JU[f]]=X;return j}var $1={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 x1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function Ij($){if($!=="yolo")return{};let J={enabled:!0,autoApprove:!0},Q={"*":J};for(let Z of X2)Q[Z]=J;return Q}function xj($,J){let Q=$1[$],{enableSpawnAgent:Z,enableAgentTeams:W,...j}=Q;return B2({...j,...J})}import{createTool as HR,zodToJsonSchema as BR}from"@cline/shared";import{z as f9}from"zod";p0();import{createAgentRuntime as tU}from"@cline/agents";import{createContributionRegistry as eU}from"@cline/shared";import{createGateway as AU,createHandlerAsync as KU,hasRegisteredHandler as GU,MODEL_COLLECTIONS_BY_PROVIDER_ID as FU,normalizeProviderId as DU}from"@cline/llms";import{EMPTY_CONTENT_TEXT as ZU}from"@cline/shared";function WU($){let J=fU($.content),Q=[],Z=$.id??VU(),W=0,j=[],f=()=>{if(j.length===0)return;let X=W===0?Z:`${Z}_part_${W}`;W+=1,Q.push({id:X,role:$.role,content:j.map(XU),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:gj($.metrics)}),j=[]};if(J.length===0)return Q.push({id:Z,role:$.role,content:[{type:"text",text:ZU}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:gj($.metrics)}),Q;for(let X of J){if(X.type!=="tool_result"){j.push(X);continue}f(),Q.push({id:`${Z}_tool_${X.tool_use_id}`,role:"tool",content:[vj(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return f(),Q}function T6($){return $.flatMap(WU)}function jU($){let J=$.content.map(cj).filter((Q)=>Q!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:J,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:YU($.metrics)}}function K2($){return $.map(jU)}function M6($){let J=[];for(let Q of $){let Z=Q.content.map(cj).filter((f)=>f!==void 0),W=Q.role==="tool"?"user":Q.role,j=J[J.length-1];if(W==="user"&&Z.length>0&&Z.every((f)=>f.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((f)=>f.type==="tool_result")){j.content.push(...Z);continue}J.push({role:W,content:Z})}return J}function fU($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function XU($){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 vj($)}}function vj($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function cj($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let J=$.metadata;return{type:"thinking",thinking:$.text,signature:J?.signature,details:J?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let J=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:J?.thoughtSignature??J?.signature}}case"tool-result":{let J=$.output,Q=typeof J==="string"?J:Array.isArray(J)?J:JSON.stringify(J);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Q,is_error:$.isError}}}}function gj($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function YU($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var mj=0;function VU(){return mj+=1,`msg_${Date.now().toString(36)}_${mj.toString(36)}`}function HU($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let J=$.tool_call.function,Q=J.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??J.id,toolName:J.name,inputText:typeof Q==="string"?Q:void 0,input:typeof Q==="string"?void 0:Q,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:BU($),error:$.error}];default:return[]}}function BU($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function uj($){return{async*stream(J){let Q=!1,Z=!1;try{let W=typeof $==="function"?await $():$;W.setAbortSignal?.(J.signal);let j=M6(J.messages),f=J.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of W.createMessage(J.systemPrompt??"",j,f))for(let Y of HU(X)){if(Y.type==="finish")Q=!0;else if(Y.type==="tool-call-delta")Z=!0;yield Y}if(!Q)yield{type:"finish",reason:Z?"tool-calls":"stop"}}catch(W){if(!Q)yield{type:"finish",reason:J.signal?.aborted?"aborted":"error",error:W instanceof Error?W.message:String(W)}}}}}function UU($){let J=Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0));return Object.keys(J).length>0?J:void 0}function RU($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function zU($){let J={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(RU($))Object.assign(J,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(J,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Q=$.gcp?.region??$.region;Object.assign(J,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Q,region:Q})}return UU(J)}function iQ($){let J=$.providerConfig;if(J?.knownModels)return J.knownModels;if($.knownModels)return $.knownModels;return FU[$.providerId]?.models??void 0}function LU($){if(!$?.length)return;let J=new Set;for(let Q of $)switch(Q){case"tools":case"reasoning":case"prompt-cache":case"images":J.add(Q);break;case"structured_output":J.add("structured-output");break;default:J.add("text")}return J.add("text"),[...J]}function _U($,J){return{id:$,name:J.name??$,description:J.description,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxOutputTokens:J.maxTokens,capabilities:LU(J.capabilities),metadata:{family:J.family,pricing:J.pricing,status:J.status,releaseDate:J.releaseDate}}}function dj($,J,Q){let Z=$.providerConfig,W=Z?.providerId===$.providerId?Z:void 0,j={...W??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.headers??W?.headers,knownModels:iQ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:J,extensionContext:$.extensionContext};if(GU(DU(j.providerId)))return uj(()=>KU(j));return AU({providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,options:zU(j),models:j.knownModels?Object.entries(j.knownModels).map(([f,X])=>_U(f,X)):void 0}],logger:J,telemetry:Q??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens})}import{createMediaBudgetState as OU,IMAGE_OMITTED_PLACEHOLDER as lj,normalizeUserInput as pj,resolveMediaBudget as TU,validateAndReserveImageMedia as MU}from"@cline/shared";var qU=50000,PU=6000000,rj=8000,NU=new Set(["read","read_files","search","search_codebase","bash","run_commands","fetch_web_content"]),wU=new Set(["read","read_files"]),R$="[outdated - see the latest file content]",ij="Tool execution was interrupted before a result was produced.",SU=($)=>`
142
+ `)}catch(K){if(clearTimeout(B),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${J}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(Y.signal&&A)Y.signal.removeEventListener("abort",A)}}}function O6($={}){return{readFile:D6($.fileRead),search:L6($.search),bash:A6($.bash),webFetch:_6($.webFetch),applyPatch:K6($.applyPatch),editor:G6($.editor)}}var QU={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion",submit_and_exit:"enableSubmitAndExit"},Q8=[{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 Ij($,J){if(!J||J.length===0)return!0;let Q=$.toLowerCase();return J.some((Z)=>Q.includes(Z.toLowerCase()))}function ZU($,J,Q,Z){if($.mode&&$.mode!=="any"&&$.mode!==Z)return!1;return Ij(J,$.providerIdIncludes)&&Ij(Q,$.modelIdIncludes)}function Z8($,J,Q,Z){if(!Z||Z.length===0)return{};let W=new Map;for(let f of Z){if(!ZU(f,$,J,Q))continue;for(let X of f.disableTools??[])W.set(X,!1);for(let X of f.enableTools??[])W.set(X,!0)}let j={};for(let[f,X]of W.entries())j[QU[f]]=X;return j}var $1={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 x1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function xj($){if($!=="yolo")return{};let J={enabled:!0,autoApprove:!0},Q={"*":J};for(let Z of X2)Q[Z]=J;return Q}function gj($,J){let Q=$1[$],{enableSpawnAgent:Z,enableAgentTeams:W,...j}=Q;return B2({...j,...J})}import{createTool as BR,zodToJsonSchema as AR}from"@cline/shared";import{z as f9}from"zod";p0();import{createAgentRuntime as eU}from"@cline/agents";import{createContributionRegistry as $R,mergeModelOptions as tj}from"@cline/shared";import{createGateway as KU,createHandlerAsync as GU,hasRegisteredHandler as FU,MODEL_COLLECTIONS_BY_PROVIDER_ID as DU,normalizeProviderId as UU}from"@cline/llms";import{EMPTY_CONTENT_TEXT as WU}from"@cline/shared";function jU($){let J=XU($.content),Q=[],Z=$.id??HU(),W=0,j=[],f=()=>{if(j.length===0)return;let X=W===0?Z:`${Z}_part_${W}`;W+=1,Q.push({id:X,role:$.role,content:j.map(YU),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:mj($.metrics)}),j=[]};if(J.length===0)return Q.push({id:Z,role:$.role,content:[{type:"text",text:WU}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:mj($.metrics)}),Q;for(let X of J){if(X.type!=="tool_result"){j.push(X);continue}f(),Q.push({id:`${Z}_tool_${X.tool_use_id}`,role:"tool",content:[cj(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return f(),Q}function T6($){return $.flatMap(jU)}function fU($){let J=$.content.map(uj).filter((Q)=>Q!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:J,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:VU($.metrics)}}function K2($){return $.map(fU)}function M6($){let J=[];for(let Q of $){let Z=Q.content.map(uj).filter((f)=>f!==void 0),W=Q.role==="tool"?"user":Q.role,j=J[J.length-1];if(W==="user"&&Z.length>0&&Z.every((f)=>f.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((f)=>f.type==="tool_result")){j.content.push(...Z);continue}J.push({role:W,content:Z})}return J}function XU($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function YU($){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 cj($)}}function cj($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function uj($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let J=$.metadata;return{type:"thinking",thinking:$.text,signature:J?.signature,details:J?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let J=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:J?.thoughtSignature??J?.signature}}case"tool-result":{let J=$.output,Q=typeof J==="string"?J:Array.isArray(J)?J:JSON.stringify(J);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Q,is_error:$.isError}}}}function mj($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function VU($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var vj=0;function HU(){return vj+=1,`msg_${Date.now().toString(36)}_${vj.toString(36)}`}function BU($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let J=$.tool_call.function,Q=J.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??J.id,toolName:J.name,inputText:typeof Q==="string"?Q:void 0,input:typeof Q==="string"?void 0:Q,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:AU($),error:$.error}];default:return[]}}function AU($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function dj($){return{async*stream(J){let Q=!1,Z=!1;try{let W=typeof $==="function"?await $():$;W.setAbortSignal?.(J.signal);let j=M6(J.messages),f=J.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of W.createMessage(J.systemPrompt??"",j,f))for(let Y of BU(X)){if(Y.type==="finish")Q=!0;else if(Y.type==="tool-call-delta")Z=!0;yield Y}if(!Q)yield{type:"finish",reason:Z?"tool-calls":"stop"}}catch(W){if(!Q)yield{type:"finish",reason:J.signal?.aborted?"aborted":"error",error:W instanceof Error?W.message:String(W)}}}}}function RU($){let J=Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0));return Object.keys(J).length>0?J:void 0}function zU($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function LU($){let J={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(zU($))Object.assign(J,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(J,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Q=$.gcp?.region??$.region;Object.assign(J,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Q,region:Q})}return RU(J)}function iQ($){let J=$.providerConfig;if(J?.knownModels)return J.knownModels;if($.knownModels)return $.knownModels;return DU[$.providerId]?.models??void 0}function _U($){if(!$?.length)return;let J=new Set;for(let Q of $)switch(Q){case"tools":case"reasoning":case"prompt-cache":case"images":J.add(Q);break;case"structured_output":J.add("structured-output");break;default:J.add("text")}return J.add("text"),[...J]}function OU($,J){return{id:$,name:J.name??$,description:J.description,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxOutputTokens:J.maxTokens,capabilities:_U(J.capabilities),metadata:{family:J.family,pricing:J.pricing,status:J.status,releaseDate:J.releaseDate}}}function lj($,J,Q){let Z=$.providerConfig,W=Z?.providerId===$.providerId?Z:void 0,j={...W??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.headers??W?.headers,knownModels:iQ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:J,extensionContext:$.extensionContext};if(FU(UU(j.providerId)))return dj(()=>GU(j));return KU({providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,options:LU(j),models:j.knownModels?Object.entries(j.knownModels).map(([f,X])=>OU(f,X)):void 0}],logger:J,telemetry:Q??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens})}import{createMediaBudgetState as TU,IMAGE_OMITTED_PLACEHOLDER as pj,normalizeUserInput as rj,resolveMediaBudget as MU,validateAndReserveImageMedia as qU}from"@cline/shared";var PU=50000,NU=6000000,ij=8000,wU=new Set(["read","read_files","search","search_codebase","bash","run_commands","fetch_web_content"]),SU=new Set(["read","read_files"]),R$="[outdated - see the latest file content]",nj="Tool execution was interrupted before a result was produced.",CU=($)=>`
143
143
 
144
144
  ...[truncated ${$} chars]...
145
145
 
146
- `,CU=($)=>`
146
+ `,yU=($)=>`
147
147
 
148
148
  ...[truncated ${$} chars to fit provider request budget]...
149
149
 
150
- `;class tQ{maxToolResultChars;targetToolNames;maxTotalTextBytes;mediaBudget;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=qU,J=NU,Q=PU,Z={}){this.maxToolResultChars=$;this.targetToolNames=J;this.maxTotalTextBytes=Q;this.mediaBudget=Z}buildForApi($){this.reindex($);let Q=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let X=pj(W.content);if(X!==W.content)return{...W,content:X}}return W}let j=!1,f=W.content.map((X)=>{let Y=this.transformBlock(X,W.role);if(Y!==X)j=!0;return Y});return j?{...W,content:f}:W}),Z=this.applyMediaBudget(Q);return this.truncateToTotalTextBudget(Z)}transformBlock($,J){if(J==="user"&&$.type==="text"&&typeof $.text==="string"){let W=pj($.text);if(W!==$.text)return{...$,text:W};return $}if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="tool_result")return $;let Q=this.toolNameByIdCache.get($.tool_use_id),Z=$.content;if(this.isReadTool(Q)&&$.is_error!==!0){let W=this.getReadLocators($);if(W.length>0){let j=W.filter((f)=>this.isOutdatedReadLocator(f,$.tool_use_id));if(j.length>0)Z=this.replaceOutdatedReadContent(Z,j)}}if(this.shouldTruncateTool(Q))Z=this.truncateToolResultContent(Z);return Z===$.content?$:{...$,content:Z}}reindex($){let J=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!J)this.resetIndexes();for(let Q=this.indexedMessageCount;Q<$.length;Q++){let Z=$[Q];if(!Array.isArray(Z.content))continue;for(let W=0;W<Z.content.length;W++){let j=Z.content[W];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Q}:${W}`);else if(j.type==="tool_use"){let f=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,f),this.isReadTool(f)){let X=this.extractLocatorsFromReadToolInput(j.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(j.id,X)}}else if(j.type==="tool_result"){let f=this.toolNameByIdCache.get(j.tool_use_id);if(!this.isReadTool(f)||j.is_error===!0)continue;let X=this.getReadLocators(j);for(let Y of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(Y),j.tool_use_id),this.isFullFileRead(Y))this.latestFullContentOwnerByPathCache.set(Y.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let J=this.collectToolResultIds($),Q=[],Z=new Map,W=!1,j=()=>{if(Z.size===0)return;f(this.createMissingToolResultMessage(Z)),Z.clear(),W=!0},f=(X)=>{let Y=Q.at(-1);if(this.shouldMergeUserAfterToolResults(Y,X)){Q[Q.length-1]={...Y,content:[...Y.content,...this.contentBlocksForUserMerge(X.content)]},W=!0;return}Q.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(f(this.appendMissingToolResults(X,Z)),Z.size>0)Z.clear(),W=!0;continue}if(Array.isArray(X.content)){let Y=X.content.filter((H)=>H.type==="tool_result"),V=X.content.filter((H)=>H.type!=="tool_result");if(Y.length>0){let H=this.appendMissingToolResults({...X,role:"user",content:Y},Z);if(f(H),Z.size>0)Z.clear();W=!0}if(V.length>0||Y.length===0){if(Y.length===0)j();let H=Y.length>0?{...X,content:V}:X;if(f(H),H.role==="assistant")this.trackMissingToolCalls(H,J,Z)}continue}j(),f(X)}return j(),W?Q:$}appendMissingToolResults($,J){if(J.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(J)]}}shouldMergeUserAfterToolResults($,J){return $?.role==="user"&&J.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(J.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let J=new Set;for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content)if(Z.type==="tool_result")J.add(Z.tool_use_id)}return J}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((J)=>J.type==="tool_result")}trackMissingToolCalls($,J,Q){if(!Array.isArray($.content))return;for(let Z of $.content){if(Z.type!=="tool_use"||J.has(Z.id))continue;Q.set(Z.id,Z.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([J,Q])=>({type:"tool_result",tool_use_id:J,name:Q,content:[{type:"text",text:this.formatMissingToolResultText(Q)}],is_error:!0}))}formatMissingToolResultText($){return $?`${ij} Tool: ${$}.`:ij}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let J=$,Q=this.readResultLocatorCache.get(J);if(Q===void 0)Q=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(J,Q);if(Q.length>0)return Q;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let J=$,Q=[],Z=this.extractLocatorFromReadRequest(J);if(Z)Q.push(Z);if(Array.isArray(J.files))for(let W of J.files){let j=this.extractLocatorFromReadRequest(W);if(j)Q.push(j)}if(Array.isArray(J.file_paths)){for(let W of J.file_paths)if(typeof W==="string"&&W.length>0)Q.push({path:W,startLine:null,endLine:null})}return this.dedupeReadLocators(Q)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let J of $){if(J.type!=="text")continue;let Q=this.tryParseReadLocators(J.text);if(Q.length>0)return Q}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Q=[];for(let Z of $){let W=this.extractLocatorFromResultEntry(Z);if(W)Q.push(W)}return this.dedupeReadLocators(Q)}let J=this.extractLocatorFromResultEntry($);return J?[J]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(!Q)return;return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(Q)return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)};if(typeof J.query==="string"&&J.query.length>0)return this.parseReadQuery(J.query);return}extractPath($){let J=[$.path,$.file_path,$.filePath];for(let Q of J)if(typeof Q==="string"&&Q.length>0)return Q;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let J=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!J)return{path:$,startLine:null,endLine:null};return{path:J[1],startLine:Number(J[2]),endLine:J[3]==="EOF"?null:Number(J[3])}}dedupeReadLocators($){let J=new Map;for(let Q of $)J.set(this.toReadLocatorKey(Q),Q);return Array.from(J.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,J){let Q=this.latestFullContentOwnerByPathCache.get($.path);if(Q&&Q!==J)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==J}replaceOutdatedReadContent($,J){let Q=new Set(J.map((j)=>this.toReadLocatorKey(j))),Z=new Set(J.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Q)??R$;let W=0;for(let j of $)if(j.type==="text")W+=this.countOutdatedImageEntries(j.text,Q);return $.map((j)=>{if(j.type==="file"){if(!Z.has(j.path))return j;return{...j,content:R$}}if(j.type==="image"){if(W===0)return j;return W-=1,{type:"text",text:R$}}if(j.type!=="text")return j;let f=this.replaceOutdatedInString(j.text,Q);if(f===null)return{...j,text:R$};return f===j.text?j:{...j,text:f}})}countOutdatedImageEntries($,J){let Q;try{Q=JSON.parse($)}catch{return 0}let Z=Array.isArray(Q)?Q:[Q],W=0;for(let j of Z){if(!j||typeof j!=="object")continue;let f=j,X=this.extractLocatorFromResultEntry(f);if(!X)continue;if(!J.has(this.toReadLocatorKey(X)))continue;if(f.result==="Successfully read image"||f.content==="Successfully read image")W+=1}return W}replaceOutdatedInString($,J){let Q;try{Q=JSON.parse($)}catch{return null}let Z=Array.isArray(Q)?Q.map((W)=>this.replaceOutdatedReadEntry(W,J)):this.replaceOutdatedReadEntry(Q,J);return JSON.stringify(Z)}replaceOutdatedReadEntry($,J){if(!$||typeof $!=="object")return $;let Q=this.extractLocatorFromResultEntry($);if(!Q||!J.has(this.toReadLocatorKey(Q)))return $;let Z={...$};if(typeof Z.result==="string")Z.result=R$;else if(typeof Z.content==="string")Z.content=R$;else Z.result=R$;return Z}isReadTool($){return!!$&&wU.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((J)=>{if(J.type==="file"){let Q=this.truncateMiddle(J.content);return Q===J.content?J:{...J,content:Q}}if(J.type==="text"){let Q=this.truncateMiddle(J.text);return Q===J.text?J:{...J,text:Q}}if(W8(J))return this.truncateNestedStrings(J);return J})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let J=!1,Q=$.map((Z)=>{let W=this.truncateNestedStrings(Z);if(W!==Z)J=!0;return W});return J?Q:$}if($!==null&&typeof $==="object"){if(q6($))return $;let J=!1,Q={};for(let[Z,W]of Object.entries($)){let j=this.truncateNestedStrings(W);if(j!==W)J=!0;Q[Z]=j}return J?Q:$}return $}truncateMiddle($){return nQ($,this.maxToolResultChars,SU)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let J=this.countMessageTextBytes($);if(J<=this.maxTotalTextBytes)return $;let Q=$.map((W)=>{if(!Array.isArray(W.content))return W;return{...W,content:W.content.map((j)=>EU(j))}}),Z=this.collectTruncationCandidates(Q);for(let W of Z){if(J<=this.maxTotalTextBytes)break;let j=W.byteLength;if(j<=rj)continue;let f=J-this.maxTotalTextBytes,X=Math.max(rj,j-f),Y=yU(W.get(),X,CU);W.set(Y),J-=j-V0(Y)}return Q}countMessageTextBytes($){let J=0;for(let Q of $){if(typeof Q.content==="string"){J+=V0(Q.content);continue}for(let Z of Q.content)if(Z.type==="text")J+=V0(Z.text);else if(Z.type==="thinking")J+=V0(Z.thinking);else if(Z.type==="file")J+=V0(Z.content);else if(Z.type==="tool_result"){if(typeof Z.content==="string")J+=V0(Z.content);else for(let W of Z.content)if(W.type==="text")J+=V0(W.text);else if(W.type==="file")J+=V0(W.content);else if(W8(W))J+=aQ(W)}}return J}collectTruncationCandidates($){let J=[];for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content){if(Z.type!=="tool_result")continue;let W=this.toolNameByIdCache.get(Z.tool_use_id);if(!this.shouldTruncateTool(W))continue;if(typeof Z.content==="string"){J.push({byteLength:V0(Z.content),get:()=>Z.content,set:(j)=>{Z.content=j}});continue}for(let j of Z.content)if(j.type==="text")J.push({byteLength:V0(j.text),get:()=>j.text,set:(f)=>{j.text=f}});else if(j.type==="file")J.push({byteLength:V0(j.content),get:()=>j.content,set:(f)=>{j.content=f}});else if(W8(j))sQ(j,J)}}return J.sort((Q,Z)=>Z.byteLength-Q.byteLength)}applyMediaBudget($){let J=this.resolveMediaBudget();if(J.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&J.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&J.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Q=OU(),Z=!1,W=$.map((j)=>{if(!Array.isArray(j.content))return j;let f=!1,X=j.content.map((Y)=>{let V=this.applyMediaBudgetToBlock(Y,J,Q);if(V!==Y)f=!0;return V});if(!f)return j;return Z=!0,{...j,content:X}});return Z?W:$}resolveMediaBudget(){return TU(this.mediaBudget)}applyMediaBudgetToBlock($,J,Q){if(q6($))return this.limitImageContent($,J,Q);if($.type!=="tool_result"||typeof $.content==="string")return $;let Z=!1,W=$.content.map((j)=>{let f=this.applyMediaBudgetToToolResultEntry(j,J,Q);if(f!==j)Z=!0;return f});return Z?{...$,content:W}:$}applyMediaBudgetToToolResultEntry($,J,Q){if(q6($))return this.limitImageContent($,J,Q);if(W8($))return this.limitNestedMedia($,J,Q);return $}limitNestedMedia($,J,Q){if(q6($)){let Z=this.limitImageContent($,J,Q);return Z.type==="text"?Z.text:Z}if(Array.isArray($)){let Z=!1,W=$.map((j)=>{let f=this.limitNestedMedia(j,J,Q);if(f!==j)Z=!0;return f});return Z?W:$}if($!==null&&typeof $==="object"){let Z=!1,W={};for(let[j,f]of Object.entries($)){let X=this.limitNestedMedia(f,J,Q);if(X!==f)Z=!0;W[j]=X}return Z?W:$}return $}limitImageContent($,J,Q){if(!eQ($))return{type:"text",text:lj};let Z=MU($.mediaType,$.data,{maxImageEncodedBytes:J.maxImageEncodedBytes,maxImageDecodedBytes:J.maxImageDecodedBytes,maxTotalMediaBytes:J.maxTotalMediaBytes},Q);if(!Z.ok)return{type:"text",text:lj};return{...$,data:Z.base64,mediaType:Z.mediaType}}}function V0($){return Buffer.byteLength($,"utf8")}function nQ($,J,Q){if($.length<=J)return $;let Z=Q($.length-J),W=Math.max(0,Math.floor((J-Z.length)/2)),j=Math.max(0,$.length-W*2),f=Q(j),X=Math.max(0,Math.floor((J-f.length)/2)),Y=$.slice(0,X),V=X>0?$.slice(-X):"";return`${Y}${f}${V}`}function yU($,J,Q){if(V0($)<=J)return $;let Z=0,W=$.length,j=nQ($,0,Q);while(Z<=W){let f=Z+W>>>1,X=nQ($,f,Q);if(V0(X)<=J)j=X,Z=f+1;else W=f-1}return j}function EU($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((J)=>W8(J)?oQ(J):{...J})}}function W8($){if($===null||typeof $!=="object")return!1;let J=$.type;return J!=="text"&&J!=="image"&&J!=="file"}function q6($){return $!==null&&typeof $==="object"&&$.type==="image"}function eQ($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function aQ($){if(typeof $==="string")return V0($);if(Array.isArray($)){let J=0;for(let Q of $)J+=aQ(Q);return J}if($!==null&&typeof $==="object"){if(eQ($))return 0;let J=0;for(let Q of Object.values($))J+=aQ(Q);return J}return 0}function sQ($,J){if(Array.isArray($)){$.forEach((Q,Z)=>{if(typeof Q==="string")J.push({byteLength:V0(Q),get:()=>$[Z],set:(W)=>{$[Z]=W}});else sQ(Q,J)});return}if($!==null&&typeof $==="object"){if(eQ($))return;let Q=$;for(let Z of Object.keys(Q)){let W=Q[Z];if(typeof W==="string")J.push({byteLength:V0(W),get:()=>Q[Z],set:(j)=>{Q[Z]=j}});else sQ(W,J)}}}function oQ($){if(Array.isArray($))return $.map(oQ);if($!==null&&typeof $==="object"){let J={};for(let[Q,Z]of Object.entries($))J[Q]=oQ(Z);return J}return $}function $9(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class J9{messages=[];conversationId=$9();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=$9(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=$9(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function nj($){let{agentConfig:J}=$,Q=bU(J),Z=hU(J),W=$.hooks,j=kU(J.maxParallelToolCalls);return{sessionId:$.sessionId??J.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??J.systemPrompt,messageModelInfo:Z,model:$.model,modelOptions:Q,tools:$.tools,hooks:W,prepareTurn:$.prepareTurn,consumePendingUserMessage:J.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??J.logger,telemetry:$.telemetry??J.telemetry,initialMessages:$.initialMessages,completionPolicy:J.completionPolicy,maxIterations:J.maxIterations,toolExecution:j,toolPolicies:J.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:J.requestToolApproval}}function bU($){let J={};if($.thinking!==void 0)J.thinking=$.thinking;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)J.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)J.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(J).length>0?J:void 0}function hU($){let J=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:J}}function kU($){if($===void 0)return;return $>=2?"parallel":"sequential"}function IU(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function xU($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function Q9($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(Q9);let J={};for(let Q of Object.keys($).sort())J[Q]=Q9($[Q]);return J}function gU($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(Q9($))}catch{return String($)}}function mU($,J,Q,Z){if(J===$.lastToolName&&Q===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=J,$.lastToolSignature=Q,{softWarning:$.consecutiveIdenticalCount===Z.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Z.hardThreshold}}var aj={softThreshold:3,hardThreshold:5};class Z9{config;state=IU();constructor($){this.config={softThreshold:$?.softThreshold??aj.softThreshold,hardThreshold:$?.hardThreshold??aj.hardThreshold}}inspect($){let J=gU($.input),Q=mU(this.state,$.name,J,this.config);if(Q.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Q.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){xU(this.state)}}class W9{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let J=this.options.maxConsecutiveMistakes,Q=$.forceAtLimit&&J?J:this.consecutiveMistakes+1;this.consecutiveMistakes=Q;let Z=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Z),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Q,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!J||Q<J)return{action:"continue"};let W=await cU({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details},this.options.onLimitReached);if(W.action==="continue"){let j=W.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:W.reason?.trim()||void 0,message:vU({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details,stopReason:W.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function vU($){let J=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Q=$.details?.trim();if(Q)J.push(`Error: ${Q}`);let Z=$.stopReason?.trim();if(Z)J.push(`Decision: ${Z}`);return J.push("Session state was preserved. Send a new prompt to resume from the latest state."),J.join(" ")}async function cU($,J){if(!J)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await J($)}catch(Q){return{action:"stop",reason:Q instanceof Error?Q.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function uU($){let J=$.content.filter((Q)=>Q.type==="text");if(J.length===0)return;return J.map((Q)=>Q.text).join("")}function dU($){let J=$.content.filter((Q)=>Q.type==="reasoning");if(J.length===0)return;return{reasoning:J.map((Q)=>Q.text).join(""),redacted:J.some((Q)=>Q.redacted===!0)}}function lU($){return $.content.find((J)=>J.type==="tool-result")}function pU($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function rU($){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 j9{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let J=[],Q=uU($);if(Q!==void 0)J.push({type:"content_end",contentType:"text",text:Q});let Z=dU($);if(Z!==void 0)J.push({type:"content_end",contentType:"reasoning",reasoning:Z.reasoning});return J}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let J=this.toolStartedAt.get($.toolCall.toolCallId),Q=J===void 0?void 0:Date.now()-J;this.toolStartedAt.delete($.toolCall.toolCallId);let Z=lU($.message),W=Z?.output,j=rU(Z);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:W,error:j,durationMs:Q}]}translateUsage($){let J=$.inputTokens-this.lastUsage.inputTokens,Q=$.outputTokens-this.lastUsage.outputTokens,Z=$.cacheReadTokens-this.lastUsage.cacheReadTokens,W=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,X=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,J),outputTokens:Math.max(0,Q),cacheReadTokens:Z===0?void 0:Math.max(0,Z),cacheWriteTokens:W===0?void 0:Math.max(0,W),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let J={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:pU($.status),text:$.outputText,iterations:$.iterations,usage:J}]}}function $R($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function JR($){let Q=(typeof $.content==="function"?await $.content():$.content).trim();return Q.length>0?Q:void 0}function QR($,J){let Q=$.trim(),Z=J.map((W)=>W.trim()).filter(Boolean).join(`
150
+ `;class tQ{maxToolResultChars;targetToolNames;maxTotalTextBytes;mediaBudget;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=PU,J=wU,Q=NU,Z={}){this.maxToolResultChars=$;this.targetToolNames=J;this.maxTotalTextBytes=Q;this.mediaBudget=Z}buildForApi($){this.reindex($);let Q=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let X=rj(W.content);if(X!==W.content)return{...W,content:X}}return W}let j=!1,f=W.content.map((X)=>{let Y=this.transformBlock(X,W.role);if(Y!==X)j=!0;return Y});return j?{...W,content:f}:W}),Z=this.applyMediaBudget(Q);return this.truncateToTotalTextBudget(Z)}transformBlock($,J){if(J==="user"&&$.type==="text"&&typeof $.text==="string"){let W=rj($.text);if(W!==$.text)return{...$,text:W};return $}if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="tool_result")return $;let Q=this.toolNameByIdCache.get($.tool_use_id),Z=$.content;if(this.isReadTool(Q)&&$.is_error!==!0){let W=this.getReadLocators($);if(W.length>0){let j=W.filter((f)=>this.isOutdatedReadLocator(f,$.tool_use_id));if(j.length>0)Z=this.replaceOutdatedReadContent(Z,j)}}if(this.shouldTruncateTool(Q))Z=this.truncateToolResultContent(Z);return Z===$.content?$:{...$,content:Z}}reindex($){let J=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!J)this.resetIndexes();for(let Q=this.indexedMessageCount;Q<$.length;Q++){let Z=$[Q];if(!Array.isArray(Z.content))continue;for(let W=0;W<Z.content.length;W++){let j=Z.content[W];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Q}:${W}`);else if(j.type==="tool_use"){let f=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,f),this.isReadTool(f)){let X=this.extractLocatorsFromReadToolInput(j.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(j.id,X)}}else if(j.type==="tool_result"){let f=this.toolNameByIdCache.get(j.tool_use_id);if(!this.isReadTool(f)||j.is_error===!0)continue;let X=this.getReadLocators(j);for(let Y of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(Y),j.tool_use_id),this.isFullFileRead(Y))this.latestFullContentOwnerByPathCache.set(Y.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let J=this.collectToolResultIds($),Q=[],Z=new Map,W=!1,j=()=>{if(Z.size===0)return;f(this.createMissingToolResultMessage(Z)),Z.clear(),W=!0},f=(X)=>{let Y=Q.at(-1);if(this.shouldMergeUserAfterToolResults(Y,X)){Q[Q.length-1]={...Y,content:[...Y.content,...this.contentBlocksForUserMerge(X.content)]},W=!0;return}Q.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(f(this.appendMissingToolResults(X,Z)),Z.size>0)Z.clear(),W=!0;continue}if(Array.isArray(X.content)){let Y=X.content.filter((H)=>H.type==="tool_result"),V=X.content.filter((H)=>H.type!=="tool_result");if(Y.length>0){let H=this.appendMissingToolResults({...X,role:"user",content:Y},Z);if(f(H),Z.size>0)Z.clear();W=!0}if(V.length>0||Y.length===0){if(Y.length===0)j();let H=Y.length>0?{...X,content:V}:X;if(f(H),H.role==="assistant")this.trackMissingToolCalls(H,J,Z)}continue}j(),f(X)}return j(),W?Q:$}appendMissingToolResults($,J){if(J.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(J)]}}shouldMergeUserAfterToolResults($,J){return $?.role==="user"&&J.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(J.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let J=new Set;for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content)if(Z.type==="tool_result")J.add(Z.tool_use_id)}return J}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((J)=>J.type==="tool_result")}trackMissingToolCalls($,J,Q){if(!Array.isArray($.content))return;for(let Z of $.content){if(Z.type!=="tool_use"||J.has(Z.id))continue;Q.set(Z.id,Z.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([J,Q])=>({type:"tool_result",tool_use_id:J,name:Q,content:[{type:"text",text:this.formatMissingToolResultText(Q)}],is_error:!0}))}formatMissingToolResultText($){return $?`${nj} Tool: ${$}.`:nj}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let J=$,Q=this.readResultLocatorCache.get(J);if(Q===void 0)Q=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(J,Q);if(Q.length>0)return Q;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let J=$,Q=[],Z=this.extractLocatorFromReadRequest(J);if(Z)Q.push(Z);if(Array.isArray(J.files))for(let W of J.files){let j=this.extractLocatorFromReadRequest(W);if(j)Q.push(j)}if(Array.isArray(J.file_paths)){for(let W of J.file_paths)if(typeof W==="string"&&W.length>0)Q.push({path:W,startLine:null,endLine:null})}return this.dedupeReadLocators(Q)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let J of $){if(J.type!=="text")continue;let Q=this.tryParseReadLocators(J.text);if(Q.length>0)return Q}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Q=[];for(let Z of $){let W=this.extractLocatorFromResultEntry(Z);if(W)Q.push(W)}return this.dedupeReadLocators(Q)}let J=this.extractLocatorFromResultEntry($);return J?[J]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(!Q)return;return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(Q)return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)};if(typeof J.query==="string"&&J.query.length>0)return this.parseReadQuery(J.query);return}extractPath($){let J=[$.path,$.file_path,$.filePath];for(let Q of J)if(typeof Q==="string"&&Q.length>0)return Q;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let J=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!J)return{path:$,startLine:null,endLine:null};return{path:J[1],startLine:Number(J[2]),endLine:J[3]==="EOF"?null:Number(J[3])}}dedupeReadLocators($){let J=new Map;for(let Q of $)J.set(this.toReadLocatorKey(Q),Q);return Array.from(J.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,J){let Q=this.latestFullContentOwnerByPathCache.get($.path);if(Q&&Q!==J)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==J}replaceOutdatedReadContent($,J){let Q=new Set(J.map((j)=>this.toReadLocatorKey(j))),Z=new Set(J.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Q)??R$;let W=0;for(let j of $)if(j.type==="text")W+=this.countOutdatedImageEntries(j.text,Q);return $.map((j)=>{if(j.type==="file"){if(!Z.has(j.path))return j;return{...j,content:R$}}if(j.type==="image"){if(W===0)return j;return W-=1,{type:"text",text:R$}}if(j.type!=="text")return j;let f=this.replaceOutdatedInString(j.text,Q);if(f===null)return{...j,text:R$};return f===j.text?j:{...j,text:f}})}countOutdatedImageEntries($,J){let Q;try{Q=JSON.parse($)}catch{return 0}let Z=Array.isArray(Q)?Q:[Q],W=0;for(let j of Z){if(!j||typeof j!=="object")continue;let f=j,X=this.extractLocatorFromResultEntry(f);if(!X)continue;if(!J.has(this.toReadLocatorKey(X)))continue;if(f.result==="Successfully read image"||f.content==="Successfully read image")W+=1}return W}replaceOutdatedInString($,J){let Q;try{Q=JSON.parse($)}catch{return null}let Z=Array.isArray(Q)?Q.map((W)=>this.replaceOutdatedReadEntry(W,J)):this.replaceOutdatedReadEntry(Q,J);return JSON.stringify(Z)}replaceOutdatedReadEntry($,J){if(!$||typeof $!=="object")return $;let Q=this.extractLocatorFromResultEntry($);if(!Q||!J.has(this.toReadLocatorKey(Q)))return $;let Z={...$};if(typeof Z.result==="string")Z.result=R$;else if(typeof Z.content==="string")Z.content=R$;else Z.result=R$;return Z}isReadTool($){return!!$&&SU.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((J)=>{if(J.type==="file"){let Q=this.truncateMiddle(J.content);return Q===J.content?J:{...J,content:Q}}if(J.type==="text"){let Q=this.truncateMiddle(J.text);return Q===J.text?J:{...J,text:Q}}if(W8(J))return this.truncateNestedStrings(J);return J})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let J=!1,Q=$.map((Z)=>{let W=this.truncateNestedStrings(Z);if(W!==Z)J=!0;return W});return J?Q:$}if($!==null&&typeof $==="object"){if(q6($))return $;let J=!1,Q={};for(let[Z,W]of Object.entries($)){let j=this.truncateNestedStrings(W);if(j!==W)J=!0;Q[Z]=j}return J?Q:$}return $}truncateMiddle($){return nQ($,this.maxToolResultChars,CU)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let J=this.countMessageTextBytes($);if(J<=this.maxTotalTextBytes)return $;let Q=$.map((W)=>{if(!Array.isArray(W.content))return W;return{...W,content:W.content.map((j)=>bU(j))}}),Z=this.collectTruncationCandidates(Q);for(let W of Z){if(J<=this.maxTotalTextBytes)break;let j=W.byteLength;if(j<=ij)continue;let f=J-this.maxTotalTextBytes,X=Math.max(ij,j-f),Y=EU(W.get(),X,yU);W.set(Y),J-=j-V0(Y)}return Q}countMessageTextBytes($){let J=0;for(let Q of $){if(typeof Q.content==="string"){J+=V0(Q.content);continue}for(let Z of Q.content)if(Z.type==="text")J+=V0(Z.text);else if(Z.type==="thinking")J+=V0(Z.thinking);else if(Z.type==="file")J+=V0(Z.content);else if(Z.type==="tool_result"){if(typeof Z.content==="string")J+=V0(Z.content);else for(let W of Z.content)if(W.type==="text")J+=V0(W.text);else if(W.type==="file")J+=V0(W.content);else if(W8(W))J+=aQ(W)}}return J}collectTruncationCandidates($){let J=[];for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content){if(Z.type!=="tool_result")continue;let W=this.toolNameByIdCache.get(Z.tool_use_id);if(!this.shouldTruncateTool(W))continue;if(typeof Z.content==="string"){J.push({byteLength:V0(Z.content),get:()=>Z.content,set:(j)=>{Z.content=j}});continue}for(let j of Z.content)if(j.type==="text")J.push({byteLength:V0(j.text),get:()=>j.text,set:(f)=>{j.text=f}});else if(j.type==="file")J.push({byteLength:V0(j.content),get:()=>j.content,set:(f)=>{j.content=f}});else if(W8(j))sQ(j,J)}}return J.sort((Q,Z)=>Z.byteLength-Q.byteLength)}applyMediaBudget($){let J=this.resolveMediaBudget();if(J.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&J.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&J.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Q=TU(),Z=!1,W=$.map((j)=>{if(!Array.isArray(j.content))return j;let f=!1,X=j.content.map((Y)=>{let V=this.applyMediaBudgetToBlock(Y,J,Q);if(V!==Y)f=!0;return V});if(!f)return j;return Z=!0,{...j,content:X}});return Z?W:$}resolveMediaBudget(){return MU(this.mediaBudget)}applyMediaBudgetToBlock($,J,Q){if(q6($))return this.limitImageContent($,J,Q);if($.type!=="tool_result"||typeof $.content==="string")return $;let Z=!1,W=$.content.map((j)=>{let f=this.applyMediaBudgetToToolResultEntry(j,J,Q);if(f!==j)Z=!0;return f});return Z?{...$,content:W}:$}applyMediaBudgetToToolResultEntry($,J,Q){if(q6($))return this.limitImageContent($,J,Q);if(W8($))return this.limitNestedMedia($,J,Q);return $}limitNestedMedia($,J,Q){if(q6($)){let Z=this.limitImageContent($,J,Q);return Z.type==="text"?Z.text:Z}if(Array.isArray($)){let Z=!1,W=$.map((j)=>{let f=this.limitNestedMedia(j,J,Q);if(f!==j)Z=!0;return f});return Z?W:$}if($!==null&&typeof $==="object"){let Z=!1,W={};for(let[j,f]of Object.entries($)){let X=this.limitNestedMedia(f,J,Q);if(X!==f)Z=!0;W[j]=X}return Z?W:$}return $}limitImageContent($,J,Q){if(!eQ($))return{type:"text",text:pj};let Z=qU($.mediaType,$.data,{maxImageEncodedBytes:J.maxImageEncodedBytes,maxImageDecodedBytes:J.maxImageDecodedBytes,maxTotalMediaBytes:J.maxTotalMediaBytes},Q);if(!Z.ok)return{type:"text",text:pj};return{...$,data:Z.base64,mediaType:Z.mediaType}}}function V0($){return Buffer.byteLength($,"utf8")}function nQ($,J,Q){if($.length<=J)return $;let Z=Q($.length-J),W=Math.max(0,Math.floor((J-Z.length)/2)),j=Math.max(0,$.length-W*2),f=Q(j),X=Math.max(0,Math.floor((J-f.length)/2)),Y=$.slice(0,X),V=X>0?$.slice(-X):"";return`${Y}${f}${V}`}function EU($,J,Q){if(V0($)<=J)return $;let Z=0,W=$.length,j=nQ($,0,Q);while(Z<=W){let f=Z+W>>>1,X=nQ($,f,Q);if(V0(X)<=J)j=X,Z=f+1;else W=f-1}return j}function bU($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((J)=>W8(J)?oQ(J):{...J})}}function W8($){if($===null||typeof $!=="object")return!1;let J=$.type;return J!=="text"&&J!=="image"&&J!=="file"}function q6($){return $!==null&&typeof $==="object"&&$.type==="image"}function eQ($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function aQ($){if(typeof $==="string")return V0($);if(Array.isArray($)){let J=0;for(let Q of $)J+=aQ(Q);return J}if($!==null&&typeof $==="object"){if(eQ($))return 0;let J=0;for(let Q of Object.values($))J+=aQ(Q);return J}return 0}function sQ($,J){if(Array.isArray($)){$.forEach((Q,Z)=>{if(typeof Q==="string")J.push({byteLength:V0(Q),get:()=>$[Z],set:(W)=>{$[Z]=W}});else sQ(Q,J)});return}if($!==null&&typeof $==="object"){if(eQ($))return;let Q=$;for(let Z of Object.keys(Q)){let W=Q[Z];if(typeof W==="string")J.push({byteLength:V0(W),get:()=>Q[Z],set:(j)=>{Q[Z]=j}});else sQ(W,J)}}}function oQ($){if(Array.isArray($))return $.map(oQ);if($!==null&&typeof $==="object"){let J={};for(let[Q,Z]of Object.entries($))J[Q]=oQ(Z);return J}return $}function $9(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class J9{messages=[];conversationId=$9();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=$9(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=$9(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function aj($){let{agentConfig:J}=$,Q=hU(J),Z=kU(J),W=$.hooks,j=IU(J.maxParallelToolCalls);return{sessionId:$.sessionId??J.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??J.systemPrompt,messageModelInfo:Z,model:$.model,modelOptions:Q,tools:$.tools,hooks:W,prepareTurn:$.prepareTurn,consumePendingUserMessage:J.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??J.logger,telemetry:$.telemetry??J.telemetry,initialMessages:$.initialMessages,completionPolicy:J.completionPolicy,maxIterations:J.maxIterations,toolExecution:j,toolPolicies:J.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:J.requestToolApproval}}function hU($){let J={};if($.thinking!==void 0)J.thinking=$.thinking;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)J.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)J.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(J).length>0?J:void 0}function kU($){let J=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:J}}function IU($){if($===void 0)return;return $>=2?"parallel":"sequential"}function xU(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function gU($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function Q9($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(Q9);let J={};for(let Q of Object.keys($).sort())J[Q]=Q9($[Q]);return J}function mU($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(Q9($))}catch{return String($)}}function vU($,J,Q,Z){if(J===$.lastToolName&&Q===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=J,$.lastToolSignature=Q,{softWarning:$.consecutiveIdenticalCount===Z.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Z.hardThreshold}}var sj={softThreshold:3,hardThreshold:5};class Z9{config;state=xU();constructor($){this.config={softThreshold:$?.softThreshold??sj.softThreshold,hardThreshold:$?.hardThreshold??sj.hardThreshold}}inspect($){let J=mU($.input),Q=vU(this.state,$.name,J,this.config);if(Q.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Q.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){gU(this.state)}}class W9{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let J=this.options.maxConsecutiveMistakes,Q=$.forceAtLimit&&J?J:this.consecutiveMistakes+1;this.consecutiveMistakes=Q;let Z=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Z),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Q,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!J||Q<J)return{action:"continue"};let W=await uU({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details},this.options.onLimitReached);if(W.action==="continue"){let j=W.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:W.reason?.trim()||void 0,message:cU({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details,stopReason:W.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function cU($){let J=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Q=$.details?.trim();if(Q)J.push(`Error: ${Q}`);let Z=$.stopReason?.trim();if(Z)J.push(`Decision: ${Z}`);return J.push("Session state was preserved. Send a new prompt to resume from the latest state."),J.join(" ")}async function uU($,J){if(!J)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await J($)}catch(Q){return{action:"stop",reason:Q instanceof Error?Q.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function dU($){let J=$.content.filter((Q)=>Q.type==="text");if(J.length===0)return;return J.map((Q)=>Q.text).join("")}function lU($){let J=$.content.filter((Q)=>Q.type==="reasoning");if(J.length===0)return;return{reasoning:J.map((Q)=>Q.text).join(""),redacted:J.some((Q)=>Q.redacted===!0)}}function pU($){return $.content.find((J)=>J.type==="tool-result")}function rU($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function iU($){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 j9{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let J=[],Q=dU($);if(Q!==void 0)J.push({type:"content_end",contentType:"text",text:Q});let Z=lU($);if(Z!==void 0)J.push({type:"content_end",contentType:"reasoning",reasoning:Z.reasoning});return J}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let J=this.toolStartedAt.get($.toolCall.toolCallId),Q=J===void 0?void 0:Date.now()-J;this.toolStartedAt.delete($.toolCall.toolCallId);let Z=pU($.message),W=Z?.output,j=iU(Z);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:W,error:j,durationMs:Q}]}translateUsage($){let J=$.inputTokens-this.lastUsage.inputTokens,Q=$.outputTokens-this.lastUsage.outputTokens,Z=$.cacheReadTokens-this.lastUsage.cacheReadTokens,W=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,X=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,J),outputTokens:Math.max(0,Q),cacheReadTokens:Z===0?void 0:Math.max(0,Z),cacheWriteTokens:W===0?void 0:Math.max(0,W),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let J={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:rU($.status),text:$.outputText,iterations:$.iterations,usage:J}]}}function JR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function QR($){let Q=(typeof $.content==="function"?await $.content():$.content).trim();return Q.length>0?Q:void 0}function ZR($,J){let Q=$.trim(),Z=J.map((W)=>W.trim()).filter(Boolean).join(`
151
151
 
152
152
  `);if(Q&&Z)return`${Q}
153
153
 
154
- ${Z}`;return Q||Z}function ZR($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function WR($,J){return $.filter((Q)=>ZR(Q.name,J))}function jR($,J){return y1(WR($,J))}function fR($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return{};return{beforeRun:async(Q)=>{for(let Z of J){let W=await Z.beforeRun?.(Q);if(W?.stop)return W}return},afterRun:async(Q)=>{for(let Z of J)await Z.afterRun?.(Q)},beforeModel:async(Q)=>{let Z=Q.request,W;for(let j of J){let f=await j.beforeModel?.({...Q,request:Z});if(!f)continue;if(f.stop)return f;W={...W,...f,options:{...W?.options??{},...f.options??{}}},Z={...Z,...f.messages?{messages:f.messages}:{},...f.tools?{tools:f.tools}:{},...f.options?{options:{...Z.options??{},...f.options}}:{}}}return W},afterModel:async(Q)=>{for(let Z of J){let W=await Z.afterModel?.(Q);if(W?.stop)return W}return},beforeTool:async(Q)=>{let Z=Q.input,W;for(let j of J){let f=await j.beforeTool?.({...Q,input:Z});if(!f)continue;if(f.stop||f.skip)return f;if(W={...W,...f},Object.hasOwn(f,"input"))Z=f.input}return W},afterTool:async(Q)=>{let Z=Q.result,W;for(let j of J){let f=await j.afterTool?.({...Q,result:Z});if(!f)continue;if(f.stop)return f;if(W={...W,...f},f.result)Z=f.result}return W},onEvent:async(Q)=>{for(let Z of J)await Z.onEvent?.(Q)}}}class g1{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 j9;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,J={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=J.logger??$.logger,this.telemetry=J.telemetry??$.telemetry,this.createAgentRuntimeImpl=J.createAgentRuntimeImpl??tU,this.conversation=new J9($.initialMessages),this.messageBuilder=new tQ,this.contributionRegistry=eU({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Q=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new W9({maxConsecutiveMistakes:Q,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,f,X)=>XR(this.logger,j,f,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,f)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Z=$.execution?.loopDetection;this.loopDetectionDisabled=Z===!1;let W=Z===!1||Z===void 0?void 0:Z;this.loopTracker=new Z9(W)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let J=new Set(this.config.tools.map((Z)=>Z.name)),Q=[...this.config.tools];for(let Z of $)if(!J.has(Z.name))Q.push(Z),J.add(Z.name);this.config={...this.config,tools:Q}}updateConnection($){let J={...this.config};if($.providerId!==void 0)J.providerId=$.providerId;if($.modelId!==void 0)J.modelId=$.modelId;if($.apiKey!==void 0)J.apiKey=$.apiKey;if($.baseUrl!==void 0)J.baseUrl=$.baseUrl;if($.headers!==void 0)J.headers=$.headers;if($.providerConfig!==void 0)J.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)J.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=J}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let J=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=J,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(J)}async shutdown($,J){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,J,Q){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!1})}continue($,J,Q){return this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let J of this.contributionRegistry.getRegisteredRules()){let Q=await JR(J);if(Q)$.push(Q)}return QR(this.config.systemPrompt,$)}executeRun($){let J;return J=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===J)this.activeRunPromise=null}),this.activeRunPromise=J,J}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let J=new Date,Q=$.userMessage;if(Q!==void 0){let F=await VR(Q,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Z=await this.composeSystemPrompt(),W=dj(this.config,this.logger,this.telemetry),j=new Map;for(let F of this.contributionRegistry.getRegisteredTools())j.set(F.name,F);let f=jR([...j.values()],this.config.toolPolicies),X=new Map;for(let F of f)X.set(F.name,F);for(let F of this.config.tools)X.set(F.name,F);let Y=this.conversation.getConversationId(),V=oj(this.config),H=Array.from(X.values()),B=T6(this.conversation.getMessages()),A=nj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:Y,parentAgentId:this.parentAgentId,model:W,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:V?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[n3]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(V,H),initialMessages:B,systemPrompt:Z}),K=this.createAgentRuntimeImpl(A);if(this.activeRuntime=K,this.abortRequested)K.abort(this.abortReason);let G=K.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,D;try{if($.isContinue)R=await K.continue(void 0);else R=await K.run("")}catch(F){D=F instanceof Error?F:Error(String(F))}finally{G();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=K2(R.messages);this.conversation.replaceMessages(F)}let U=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:D,startedAt:J,endedAt:U})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=fR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((J)=>J.hooks)]);return{...$,beforeModel:async(J)=>{let Q=await $.beforeModel?.(J);if(Q?.stop)return Q;let Z=Q?.messages??J.request.messages,W=await this.prepareMessagesForModelRequest(Z);return{...Q,messages:W}}}}createRuntimePrepareTurn($,J){let Q=this.config.prepareTurn;if(!Q)return;return async(Z)=>{let W=K2(Z.messages),j=await this.prepareProviderMessagesForApi(W),f=await Q({agentId:Z.agentId,conversationId:Z.conversationId??this.conversation.getConversationId(),parentAgentId:Z.parentAgentId??null,iteration:Z.iteration,messages:W,apiMessages:j,abortSignal:Z.signal??new AbortController().signal,systemPrompt:Z.systemPrompt??"",tools:J,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Z.emitStatusNotice});if(!f)return;return{...f.messages?{messages:T6(f.messages)}:{},...f.systemPrompt!==void 0?{systemPrompt:f.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let J=await this.prepareProviderMessagesForApi(M6($));return T6(J)}async prepareProviderMessagesForApi($){let J=$,Q=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Z of Q)J=await Z.build(J);return this.messageBuilder.buildForApi(J)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let J=this.toolStartedAt.get($.toolCall.toolCallId),Q=new Date,Z=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let W=$.message.content.find((Y)=>Y.type==="tool-result"),j=W?.type==="tool-result"&&W.isError===!0,f=j?$R(W?.type==="tool-result"?W.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Z,output:W?.type==="tool-result"?W.output:void 0,error:f,durationMs:J===void 0?0:Q.getTime()-J.getTime(),startedAt:J??Q,endedAt:Q};if(this.currentRunToolCalls.push(X),j){if(this.currentTurnFailedTools+=1,f)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${f}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let J=this.currentTurnFailedTools,Q=this.currentTurnSuccessfulTools;if(J>0&&Q===0){let Z=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${J} tool call(s) failed${Z?`: ${Z}`:""}`})}else if(Q>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let J of this.eventAdapter.translate($))this.emitLegacyEvent(J)}syncConversationFromRuntimeMessage($,J){if($.length>0){this.conversation.replaceMessages(K2($));return}if(J.length===0)return;let Q=new Set(this.conversation.getMessages().map((W)=>W.id).filter((W)=>typeof W==="string")),Z=K2(J).filter((W)=>!W.id||!Q.has(W.id));if(Z.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Z])}emitLegacyEvent($){for(let J of this.listeners)try{J($)}catch(Q){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Q})}}inspectLoopForToolCall($,J,Q){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Z=this.loopTracker.inspect({name:$,input:J});if(Z.kind==="ok")return;if(Z.kind==="soft"){if(Z.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Z.message}]});return}this.enqueueMistakeRecord({iteration:Q,reason:"tool_execution_failed",forceAtLimit:!0,details:Z.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let J=await this.mistakeTracker.record($);if(J.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:J.message}]}),this.activeRuntime?.abort(J.reason??J.message)})}buildLegacyResult($){let{runResult:J,thrownError:Q,startedAt:Z,endedAt:W}=$,j=W.getTime()-Z.getTime(),f=Q?"error":YR(J),X=J?.outputText||(J?.status==="failed"?J.error?.message:void 0)||"",Y=J?{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens>0?J.usage.cacheReadTokens:void 0,cacheWriteTokens:J.usage.cacheWriteTokens>0?J.usage.cacheWriteTokens:void 0,totalCost:J.usage.totalCost}:this.currentRunUsage,V=J?K2(J.messages):this.conversation.getMessages(),H=oj(this.config);if(Q)throw Q;return{text:X,usage:Y,messages:V,toolCalls:this.currentRunToolCalls,iterations:J?.iterations??0,finishReason:f,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Z,endedAt:W,durationMs:j}}}function XR($,J,Q,Z){if(!$)return;if(J==="debug"){$.debug(Q,Z);return}if(J==="error"&&$.error){$.error(Q,Z);return}let W=J==="warn"?"warn":J==="error"?"error":"info";$.log(Q,{...Z,severity:W})}function YR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function VR($,J,Q,Z){let{buildInitialUserContent:W}=await Promise.resolve().then(() => sj);return W($,J,Q,Z)}function oj($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let J=iQ($);if(J?.[$.modelId])return J[$.modelId];return}import{buildClineSystemPrompt as tj}from"@cline/shared";function ej($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return tj({ide:J.clineIdeName?.trim()||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,rules:`# Team Teammate Role
155
- ${Q}`,platform:J.clinePlatform,metadata:J.workspaceMetadata})}function $f($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return tj({ide:J.clineIdeName||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,overridePrompt:Q,metadata:J.workspaceMetadata,platform:J.clinePlatform})}function G2($){let J={...$};return{getRuntimeConfig:()=>J,getConnectionConfig:()=>({providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking}),updateConnectionDefaults:(Q)=>{J={...J,...Q}}}}function f8($){let J=$.configProvider.getRuntimeConfig(),Q=$.kind==="teammate"?ej($.prompt,J):$f($.prompt,J);return{...$.configProvider.getConnectionConfig(),systemPrompt:Q,tools:$.tools,maxIterations:$.maxIterations??J.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:J.hooks,extensions:J.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:J.logger,role:$.role}}function F2($){let J=f8($),Q=new g1(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);return Q}var AR=f9.object({systemPrompt:f9.string().describe("System prompt defining the sub-agent's behavior"),task:f9.string().describe("Task for the sub-agent to complete")});function D2($){return HR({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:BR(AR),execute:async(J,Q)=>{let Z=$.createSubAgentTools?await $.createSubAgentTools(J,Q):$.subAgentTools??[],W=F2({kind:"subagent",prompt:J.systemPrompt,configProvider:$.configProvider,tools:Z,maxIterations:$.defaultMaxIterations,parentAgentId:Q.agentId,abortSignal:Q.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=W.getAgentId(),f=W.getConversationId(),X=Q.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:f,parentAgentId:X,input:J})}catch{}try{let Y=await W.run(J.task),V={text:Y.text,iterations:Y.iterations,finishReason:Y.finishReason,usage:{inputTokens:Y.usage.inputTokens,outputTokens:Y.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,result:V,agentResult:Y})}catch{}return V}catch(Y){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,error:Y instanceof Error?Y:Error(String(Y))})}catch{}throw Y}},timeoutMs:300000,retryable:!1})}import{createTool as W0,TEAM_AWAIT_TIMEOUT_MS as KR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as GR,TEAM_RUN_TEXT_PREVIEW_LIMIT as FR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as DR,TeamAttachOutcomeFragmentInputSchema as Jf,TeamAwaitRunsInputSchema as Qf,TeamBroadcastInputSchema as Zf,TeamBroadcastToolResultSchema as UR,TeamCancelRunInputSchema as Wf,TeamCancelRunToolResultSchema as RR,TeamCleanupInputSchema as jf,TeamCleanupToolResultSchema as zR,TeamCreateOutcomeInputSchema as ff,TeamCreateOutcomeToolResultSchema as LR,TeamFinalizeOutcomeInputSchema as Xf,TeamFinalizeOutcomeToolResultSchema as _R,TeamListOutcomesInputSchema as Yf,TeamListRunsInputSchema as Vf,TeamMailboxMessageToolResultSchema as OR,TeamMissionLogInputSchema as Hf,TeamMissionLogToolResultSchema as TR,TeamOutcomeFragmentToolResultSchema as Bf,TeamOutcomeToolResultSchema as MR,TeamReadMailboxInputSchema as Af,TeamReviewOutcomeFragmentInputSchema as Kf,TeamRunTaskInputSchema as Gf,TeamRunTaskToolResultSchema as X9,TeamRunToolSummarySchema as Y9,TeamSendMessageInputSchema as Ff,TeamSendMessageToolResultSchema as qR,TeamShutdownTeammateInputSchema as Df,TeamSimpleAgentStatusToolResultSchema as Uf,TeamSpawnTeammateInputSchema as Rf,TeamStatusInputSchema as zf,TeamStatusToolResultSchema as PR,TeamTaskInputSchema as Lf,TeamTaskToolResultSchema as X8,validateWithZod as E,zodToJsonSchema as j0}from"@cline/shared";function _f($,J){let Q=$.replace(/\s+/g," ").trim();if(Q.length<=J)return Q;return`${Q.slice(0,Math.max(0,J-3)).trimEnd()}...`}function z$($,J){if($===void 0)throw Error(`Missing required field: ${J}`);return $}function NR($){let J=$.result;if(!J)return;return{textPreview:_f(J.text,FR),iterations:J.iterations,finishReason:J.finishReason,durationMs:J.durationMs,usage:{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens,cacheWriteTokens:J.usage.cacheWriteTokens,totalCost:J.usage.totalCost}}}function P6($){return $?.toISOString()}function V9($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:_f($.message,GR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:P6($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:P6($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:P6($.heartbeatAt),lastProgressAt:P6($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:NR($)}}function wR($){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 N6=["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 Of($){let J=[];if($.createBaseTools)J.push(...$.createBaseTools());J.push(...Y8({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:f8({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:J,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function w6($){let J=$.leadAgentId??"lead",Q=$.restoredFromPersistence===!0,Z=Y8({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),W=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;Of({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),W.push(j.agentId)}return{tools:Z,restoredFromPersistence:Q,restoredTeammates:W}}function Y8($){let J=$.allowSpawn??!0,Q=$.includeSpawnTool??!0,Z=$.includeManagementTools??!0,W=[];if(Q)W.push(W0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(Rf),execute:async(f)=>{let X=E(Rf,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!J)throw Error("Spawning teammates is disabled in this context.");let Y={agentId:X.agentId,rolePrompt:X.rolePrompt};if(Of({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Y}),!Z)$.onLeadToolsUnlocked?.(Y8({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return E(Uf,{agentId:X.agentId,status:"spawned"})}}));if(!Z)return W;W.push(W0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(Df),execute:async(f)=>{let X=E(Df,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),E(Uf,{agentId:X.agentId,status:"stopped"})}})),W.push(W0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(zf),execute:async(f)=>{return E(zf,f),E(PR,$.runtime.getSnapshot())}})),W.push(W0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:j0(Lf),execute:async(f)=>{let X=E(Lf,f);switch(X.action){case"create":{let Y=new Set(DR.create??[]),V=Object.entries(f).filter(([B,A])=>Y.has(B)&&A!=null).map(([B])=>B),H=$.runtime.createTask({title:z$(X.title,"title"),description:z$(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return E(X8,{action:"create",taskId:H.id,status:H.status,...V.length>0?{ignoredFields:V,note:`Ignored fields for action=create: ${V.join(", ")}`}:{}})}case"list":return E(X8,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let Y=$.runtime.claimTask(z$(X.taskId,"taskId"),$.requesterId);return E(X8,{action:"claim",taskId:Y.id,status:Y.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let Y=$.runtime.completeTask(z$(X.taskId,"taskId"),$.requesterId,z$(X.summary,"summary"));return E(X8,{action:"complete",taskId:Y.id,status:Y.status})}case"block":{let Y=$.runtime.blockTask(z$(X.taskId,"taskId"),$.requesterId,z$(X.reason,"reason"));return E(X8,{action:"block",taskId:Y.id,status:Y.status})}}}}));let j=new Map;return W.push(W0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(Gf),execute:async(f)=>{let X=E(Gf,f);if(X.runMode==="async"){let H=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return E(X9,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${H.id}.`,runId:H.id})}let Y=j.get(X.agentId);if(Y){let H=await Y;return E(X9,{...H,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let V=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((H)=>E(X9,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(X.agentId)});return j.set(X.agentId,V),await V}})),W.push(W0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(Wf),execute:async(f)=>{let X=E(Wf,f),Y=$.runtime.cancelRun(X.runId,X.reason);return E(RR,{runId:Y.id,status:Y.status})}})),W.push(W0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(Vf),execute:async(f)=>E(Y9.array(),$.runtime.listRuns(E(Vf,f)).map(V9))})),W.push(W0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:j0(Qf),timeoutMs:KR,execute:async(f)=>{let X=E(Qf,f);if(X.runId){let H=await $.runtime.awaitRun(X.runId);return wR(H),E(Y9,V9(H))}let Y=await $.runtime.awaitAllRuns(),V=Y.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(V.length>0){let H=V.map((B)=>`${B.id}:${B.status}${B.error?`(${B.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return E(Y9.array(),Y.map(V9))}})),W.push(W0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(Ff),execute:async(f)=>{let X=E(Ff,f),Y=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return E(qR,{id:Y.id,toAgentId:Y.toAgentId})}})),W.push(W0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(Zf),execute:async(f)=>{let X=E(Zf,f),Y=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return E(UR,{delivered:Y.length})}})),W.push(W0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(Af),execute:async(f)=>{let X=E(Af,f);return E(OR.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),W.push(W0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(Hf),execute:async(f)=>{let X=E(Hf,f),Y=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return E(TR,{id:Y.id})}})),W.push(W0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(jf),execute:async(f)=>{if(E(jf,f),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),E(zR,{status:"cleaned"})}})),W.push(W0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(ff),execute:async(f)=>{let X=E(ff,f),Y=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return E(LR,{outcomeId:Y.id,status:Y.status,requiredSections:Y.requiredSections})}})),W.push(W0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(Jf),execute:async(f)=>{let X=E(Jf,f),Y=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return E(Bf,{fragmentId:Y.id,status:Y.status})}})),W.push(W0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(Kf),execute:async(f)=>{let X=E(Kf,f),Y=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return E(Bf,{fragmentId:Y.id,status:Y.status})}})),W.push(W0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(Xf),execute:async(f)=>{let X=E(Xf,f),Y=$.runtime.finalizeOutcome(X.outcomeId);return E(_R,{outcomeId:Y.id,status:Y.status})}})),W.push(W0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(Yf),execute:async(f)=>{return E(Yf,f),E(MR.array(),$.runtime.listOutcomes())}})),W}function Tf($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}var SR=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:D2({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...N6]}],CR={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function yR($){return $==="plan"||$==="yolo"?$:"act"}function qf($){let J=yR($.mode),Q=$1[x1({mode:J})],Z=Z8($.providerId??"",$.modelId??"",J,Q8);return{mode:J,flags:{...Q,...Z,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function Mf($,J){if(J.disabledToolIds?.has($))return!1;let{flags:Q}=qf(J);if($==="spawn_agent")return Q.enableSpawnAgent===!0;if($==="teams")return Q.enableAgentTeams===!0;if($==="editor")return Q.enableEditor===!0||Q.enableApplyPatch===!0;let Z=CR[$];return Z?Q[Z]===!0:!1}function ER($,J){if($.id==="editor"){let{flags:Q}=qf(J),Z=Q.enableApplyPatch===!0&&Q.enableEditor!==!0;return{...$,defaultEnabled:Mf($.id,J),headlessToolNames:[Z?"apply_patch":"editor"]}}return{...$,defaultEnabled:Mf($.id,J)}}function V8($={}){return SR.map((J)=>ER(J,$))}function Pf($={}){return V8($).filter((J)=>J.defaultEnabled).map((J)=>J.id)}function Nf($){if(!$.enabled)return new Set;let J=V8($.availabilityContext),Q=new Set(J.map((Z)=>Z.id));if(!$.allowlist||$.allowlist.length===0)return new Set(J.filter((Z)=>Z.defaultEnabled).map((Z)=>Z.id));for(let Z of $.allowlist)if(!Q.has(Z))throw Error(`Unknown tool "${Z}". Available tools: ${J.map((W)=>W.id).join(", ")}`);return new Set($.allowlist)}function H9($,J={}){return V8(J).filter((Q)=>$.has(Q.id)).flatMap((Q)=>Q.headlessToolNames)}function wf($,J={}){return H9($,J)}function H8($={}){let{executorOptions:J={},executors:Q,...Z}=$,W={...O6(J),...Q??{}};return B2({...Z,executors:W})}function S6($){return $.trim().replace(/^\/+/,"").toLowerCase()}function bR($){if(!$||$.length===0)return;let J=$.map(S6).filter((Q)=>Q.length>0);return J.length>0?new Set(J):void 0}function hR($,J,Q){if(!Q)return!0;let Z=S6($),W=S6(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function B8($,J){let Q=bR(J);return[...$.getSnapshot("skill").entries()].map(([W,j])=>{let f=j.item;return{id:W,name:f.name.trim(),description:f.description?.trim(),disabled:f.disabled===!0,skill:f}}).filter((W)=>hR(W.id,W.name,Q))}function kR($,J){return B8($,J).filter((Q)=>!Q.disabled).map((Q)=>Q.name.trim()).filter((Q)=>Q.length>0).sort((Q,Z)=>Q.localeCompare(Z))}function IR($,J,Q){let Z=S6(J);if(!Z)return{error:"Missing skill name."};let W=B8($,Q),j=W.find((H)=>H.id===Z);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let f=Z.includes(":")?Z.split(":").at(-1)??Z:Z,X=W.filter(({id:H})=>{if(H===f)return!0;return H.endsWith(`:${f}`)}),Y=X.filter(({skill:H})=>H.disabled!==!0);if(Y.length===1){let{id:H,skill:B}=Y[0];return{id:H,skill:B}}if(Y.length>1)return{error:`Skill "${J}" is ambiguous. Use one of: ${Y.map(({id:H})=>H).join(", ")}`};if(X.length===1){let{skill:H}=X[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${J}" is ambiguous, and all matches are disabled: ${X.map(({id:H})=>H).join(", ")}`};let V=kR($,Q);return{error:V.length>0?`Skill "${J}" not found. Available skills: ${V.join(", ")}`:"No skills are currently available."}}function B9($,J=Promise.resolve(),Q){let Z=new Set,W=async(j,f)=>{await J;let X=IR($,j,Q);if("error"in X)return X.error;let{id:Y,skill:V}=X;if(Z.has(Y))return`Skill "${V.name}" is already running.`;Z.add(Y);try{let H=f?.trim(),B=H?`
154
+ ${Z}`;return Q||Z}function WR($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function jR($,J){return $.filter((Q)=>WR(Q.name,J))}function fR($,J){return y1(jR($,J))}function XR($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return{};return{beforeRun:async(Q)=>{for(let Z of J){let W=await Z.beforeRun?.(Q);if(W?.stop)return W}return},afterRun:async(Q)=>{for(let Z of J)await Z.afterRun?.(Q)},beforeModel:async(Q)=>{let Z=Q.request,W;for(let j of J){let f=await j.beforeModel?.({...Q,request:Z});if(!f)continue;if(f.stop)return f;W={...W,...f,options:tj(W?.options,f.options)},Z={...Z,...f.messages?{messages:f.messages}:{},...f.tools?{tools:f.tools}:{},...f.options?{options:tj(Z.options,f.options)}:{}}}return W},afterModel:async(Q)=>{for(let Z of J){let W=await Z.afterModel?.(Q);if(W?.stop)return W}return},beforeTool:async(Q)=>{let Z=Q.input,W;for(let j of J){let f=await j.beforeTool?.({...Q,input:Z});if(!f)continue;if(f.stop||f.skip)return f;if(W={...W,...f},Object.hasOwn(f,"input"))Z=f.input}return W},afterTool:async(Q)=>{let Z=Q.result,W;for(let j of J){let f=await j.afterTool?.({...Q,result:Z});if(!f)continue;if(f.stop)return f;if(W={...W,...f},f.result)Z=f.result}return W},onEvent:async(Q)=>{for(let Z of J)await Z.onEvent?.(Q)}}}class g1{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 j9;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,J={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=J.logger??$.logger,this.telemetry=J.telemetry??$.telemetry,this.createAgentRuntimeImpl=J.createAgentRuntimeImpl??eU,this.conversation=new J9($.initialMessages),this.messageBuilder=new tQ,this.contributionRegistry=$R({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Q=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new W9({maxConsecutiveMistakes:Q,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,f,X)=>YR(this.logger,j,f,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,f)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Z=$.execution?.loopDetection;this.loopDetectionDisabled=Z===!1;let W=Z===!1||Z===void 0?void 0:Z;this.loopTracker=new Z9(W)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let J=new Set(this.config.tools.map((Z)=>Z.name)),Q=[...this.config.tools];for(let Z of $)if(!J.has(Z.name))Q.push(Z),J.add(Z.name);this.config={...this.config,tools:Q}}updateConnection($){let J={...this.config};if($.providerId!==void 0)J.providerId=$.providerId;if($.modelId!==void 0)J.modelId=$.modelId;if($.apiKey!==void 0)J.apiKey=$.apiKey;if($.baseUrl!==void 0)J.baseUrl=$.baseUrl;if($.headers!==void 0)J.headers=$.headers;if($.providerConfig!==void 0)J.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)J.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=J}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let J=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=J,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(J)}async shutdown($,J){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,J,Q){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!1})}continue($,J,Q){return this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let J of this.contributionRegistry.getRegisteredRules()){let Q=await QR(J);if(Q)$.push(Q)}return ZR(this.config.systemPrompt,$)}executeRun($){let J;return J=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===J)this.activeRunPromise=null}),this.activeRunPromise=J,J}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let J=new Date,Q=$.userMessage;if(Q!==void 0){let F=await HR(Q,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Z=await this.composeSystemPrompt(),W=lj(this.config,this.logger,this.telemetry),j=new Map;for(let F of this.contributionRegistry.getRegisteredTools())j.set(F.name,F);let f=fR([...j.values()],this.config.toolPolicies),X=new Map;for(let F of f)X.set(F.name,F);for(let F of this.config.tools)X.set(F.name,F);let Y=this.conversation.getConversationId(),V=ej(this.config),H=Array.from(X.values()),B=T6(this.conversation.getMessages()),A=aj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:Y,parentAgentId:this.parentAgentId,model:W,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:V?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[a3]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(V,H),initialMessages:B,systemPrompt:Z}),K=this.createAgentRuntimeImpl(A);if(this.activeRuntime=K,this.abortRequested)K.abort(this.abortReason);let G=K.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,D;try{if($.isContinue)R=await K.continue(void 0);else R=await K.run("")}catch(F){D=F instanceof Error?F:Error(String(F))}finally{G();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=K2(R.messages);this.conversation.replaceMessages(F)}let U=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:D,startedAt:J,endedAt:U})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=XR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((J)=>J.hooks)]);return{...$,beforeModel:async(J)=>{let Q=await $.beforeModel?.(J);if(Q?.stop)return Q;let Z=Q?.messages??J.request.messages,W=await this.prepareMessagesForModelRequest(Z);return{...Q,messages:W}}}}createRuntimePrepareTurn($,J){let Q=this.config.prepareTurn;if(!Q)return;return async(Z)=>{let W=K2(Z.messages),j=await this.prepareProviderMessagesForApi(W),f=await Q({agentId:Z.agentId,conversationId:Z.conversationId??this.conversation.getConversationId(),parentAgentId:Z.parentAgentId??null,iteration:Z.iteration,messages:W,apiMessages:j,abortSignal:Z.signal??new AbortController().signal,systemPrompt:Z.systemPrompt??"",tools:J,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Z.emitStatusNotice});if(!f)return;return{...f.messages?{messages:T6(f.messages)}:{},...f.systemPrompt!==void 0?{systemPrompt:f.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let J=await this.prepareProviderMessagesForApi(M6($));return T6(J)}async prepareProviderMessagesForApi($){let J=$,Q=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Z of Q)J=await Z.build(J);return this.messageBuilder.buildForApi(J)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let J=this.toolStartedAt.get($.toolCall.toolCallId),Q=new Date,Z=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let W=$.message.content.find((Y)=>Y.type==="tool-result"),j=W?.type==="tool-result"&&W.isError===!0,f=j?JR(W?.type==="tool-result"?W.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Z,output:W?.type==="tool-result"?W.output:void 0,error:f,durationMs:J===void 0?0:Q.getTime()-J.getTime(),startedAt:J??Q,endedAt:Q};if(this.currentRunToolCalls.push(X),j){if(this.currentTurnFailedTools+=1,f)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${f}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let J=this.currentTurnFailedTools,Q=this.currentTurnSuccessfulTools;if(J>0&&Q===0){let Z=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${J} tool call(s) failed${Z?`: ${Z}`:""}`})}else if(Q>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let J of this.eventAdapter.translate($))this.emitLegacyEvent(J)}syncConversationFromRuntimeMessage($,J){if($.length>0){this.conversation.replaceMessages(K2($));return}if(J.length===0)return;let Q=new Set(this.conversation.getMessages().map((W)=>W.id).filter((W)=>typeof W==="string")),Z=K2(J).filter((W)=>!W.id||!Q.has(W.id));if(Z.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Z])}emitLegacyEvent($){for(let J of this.listeners)try{J($)}catch(Q){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Q})}}inspectLoopForToolCall($,J,Q){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Z=this.loopTracker.inspect({name:$,input:J});if(Z.kind==="ok")return;if(Z.kind==="soft"){if(Z.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Z.message}]});return}this.enqueueMistakeRecord({iteration:Q,reason:"tool_execution_failed",forceAtLimit:!0,details:Z.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let J=await this.mistakeTracker.record($);if(J.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:J.message}]}),this.activeRuntime?.abort(J.reason??J.message)})}buildLegacyResult($){let{runResult:J,thrownError:Q,startedAt:Z,endedAt:W}=$,j=W.getTime()-Z.getTime(),f=Q?"error":VR(J),X=J?.outputText||(J?.status==="failed"?J.error?.message:void 0)||"",Y=J?{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens>0?J.usage.cacheReadTokens:void 0,cacheWriteTokens:J.usage.cacheWriteTokens>0?J.usage.cacheWriteTokens:void 0,totalCost:J.usage.totalCost}:this.currentRunUsage,V=J?K2(J.messages):this.conversation.getMessages(),H=ej(this.config);if(Q)throw Q;return{text:X,usage:Y,messages:V,toolCalls:this.currentRunToolCalls,iterations:J?.iterations??0,finishReason:f,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Z,endedAt:W,durationMs:j}}}function YR($,J,Q,Z){if(!$)return;if(J==="debug"){$.debug(Q,Z);return}if(J==="error"&&$.error){$.error(Q,Z);return}let W=J==="warn"?"warn":J==="error"?"error":"info";$.log(Q,{...Z,severity:W})}function VR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function HR($,J,Q,Z){let{buildInitialUserContent:W}=await Promise.resolve().then(() => oj);return W($,J,Q,Z)}function ej($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let J=iQ($);if(J?.[$.modelId])return J[$.modelId];return}import{buildClineSystemPrompt as $f}from"@cline/shared";function Jf($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return $f({ide:J.clineIdeName?.trim()||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,rules:`# Team Teammate Role
155
+ ${Q}`,platform:J.clinePlatform,metadata:J.workspaceMetadata})}function Qf($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return $f({ide:J.clineIdeName||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,overridePrompt:Q,metadata:J.workspaceMetadata,platform:J.clinePlatform})}function G2($){let J={...$};return{getRuntimeConfig:()=>J,getConnectionConfig:()=>({providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking}),updateConnectionDefaults:(Q)=>{J={...J,...Q}}}}function f8($){let J=$.configProvider.getRuntimeConfig(),Q=$.kind==="teammate"?Jf($.prompt,J):Qf($.prompt,J);return{...$.configProvider.getConnectionConfig(),systemPrompt:Q,tools:$.tools,maxIterations:$.maxIterations??J.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:J.hooks,extensions:J.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:J.logger,role:$.role}}function F2($){let J=f8($),Q=new g1(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);return Q}var KR=f9.object({systemPrompt:f9.string().describe("System prompt defining the sub-agent's behavior"),task:f9.string().describe("Task for the sub-agent to complete")});function D2($){return BR({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:AR(KR),execute:async(J,Q)=>{let Z=$.createSubAgentTools?await $.createSubAgentTools(J,Q):$.subAgentTools??[],W=F2({kind:"subagent",prompt:J.systemPrompt,configProvider:$.configProvider,tools:Z,maxIterations:$.defaultMaxIterations,parentAgentId:Q.agentId,abortSignal:Q.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=W.getAgentId(),f=W.getConversationId(),X=Q.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:f,parentAgentId:X,input:J})}catch{}try{let Y=await W.run(J.task),V={text:Y.text,iterations:Y.iterations,finishReason:Y.finishReason,usage:{inputTokens:Y.usage.inputTokens,outputTokens:Y.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,result:V,agentResult:Y})}catch{}return V}catch(Y){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,error:Y instanceof Error?Y:Error(String(Y))})}catch{}throw Y}},timeoutMs:300000,retryable:!1})}import{createTool as W0,TEAM_AWAIT_TIMEOUT_MS as GR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as FR,TEAM_RUN_TEXT_PREVIEW_LIMIT as DR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as UR,TeamAttachOutcomeFragmentInputSchema as Zf,TeamAwaitRunsInputSchema as Wf,TeamBroadcastInputSchema as jf,TeamBroadcastToolResultSchema as RR,TeamCancelRunInputSchema as ff,TeamCancelRunToolResultSchema as zR,TeamCleanupInputSchema as Xf,TeamCleanupToolResultSchema as LR,TeamCreateOutcomeInputSchema as Yf,TeamCreateOutcomeToolResultSchema as _R,TeamFinalizeOutcomeInputSchema as Vf,TeamFinalizeOutcomeToolResultSchema as OR,TeamListOutcomesInputSchema as Hf,TeamListRunsInputSchema as Bf,TeamMailboxMessageToolResultSchema as TR,TeamMissionLogInputSchema as Af,TeamMissionLogToolResultSchema as MR,TeamOutcomeFragmentToolResultSchema as Kf,TeamOutcomeToolResultSchema as qR,TeamReadMailboxInputSchema as Gf,TeamReviewOutcomeFragmentInputSchema as Ff,TeamRunTaskInputSchema as Df,TeamRunTaskToolResultSchema as X9,TeamRunToolSummarySchema as Y9,TeamSendMessageInputSchema as Uf,TeamSendMessageToolResultSchema as PR,TeamShutdownTeammateInputSchema as Rf,TeamSimpleAgentStatusToolResultSchema as zf,TeamSpawnTeammateInputSchema as Lf,TeamStatusInputSchema as _f,TeamStatusToolResultSchema as NR,TeamTaskInputSchema as Of,TeamTaskToolResultSchema as X8,validateWithZod as E,zodToJsonSchema as j0}from"@cline/shared";function Tf($,J){let Q=$.replace(/\s+/g," ").trim();if(Q.length<=J)return Q;return`${Q.slice(0,Math.max(0,J-3)).trimEnd()}...`}function z$($,J){if($===void 0)throw Error(`Missing required field: ${J}`);return $}function wR($){let J=$.result;if(!J)return;return{textPreview:Tf(J.text,DR),iterations:J.iterations,finishReason:J.finishReason,durationMs:J.durationMs,usage:{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens,cacheWriteTokens:J.usage.cacheWriteTokens,totalCost:J.usage.totalCost}}}function P6($){return $?.toISOString()}function V9($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:Tf($.message,FR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:P6($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:P6($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:P6($.heartbeatAt),lastProgressAt:P6($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:wR($)}}function SR($){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 N6=["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 Mf($){let J=[];if($.createBaseTools)J.push(...$.createBaseTools());J.push(...Y8({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:f8({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:J,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function w6($){let J=$.leadAgentId??"lead",Q=$.restoredFromPersistence===!0,Z=Y8({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),W=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;Mf({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),W.push(j.agentId)}return{tools:Z,restoredFromPersistence:Q,restoredTeammates:W}}function Y8($){let J=$.allowSpawn??!0,Q=$.includeSpawnTool??!0,Z=$.includeManagementTools??!0,W=[];if(Q)W.push(W0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(Lf),execute:async(f)=>{let X=E(Lf,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!J)throw Error("Spawning teammates is disabled in this context.");let Y={agentId:X.agentId,rolePrompt:X.rolePrompt};if(Mf({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Y}),!Z)$.onLeadToolsUnlocked?.(Y8({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return E(zf,{agentId:X.agentId,status:"spawned"})}}));if(!Z)return W;W.push(W0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(Rf),execute:async(f)=>{let X=E(Rf,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),E(zf,{agentId:X.agentId,status:"stopped"})}})),W.push(W0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(_f),execute:async(f)=>{return E(_f,f),E(NR,$.runtime.getSnapshot())}})),W.push(W0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:j0(Of),execute:async(f)=>{let X=E(Of,f);switch(X.action){case"create":{let Y=new Set(UR.create??[]),V=Object.entries(f).filter(([B,A])=>Y.has(B)&&A!=null).map(([B])=>B),H=$.runtime.createTask({title:z$(X.title,"title"),description:z$(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return E(X8,{action:"create",taskId:H.id,status:H.status,...V.length>0?{ignoredFields:V,note:`Ignored fields for action=create: ${V.join(", ")}`}:{}})}case"list":return E(X8,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let Y=$.runtime.claimTask(z$(X.taskId,"taskId"),$.requesterId);return E(X8,{action:"claim",taskId:Y.id,status:Y.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let Y=$.runtime.completeTask(z$(X.taskId,"taskId"),$.requesterId,z$(X.summary,"summary"));return E(X8,{action:"complete",taskId:Y.id,status:Y.status})}case"block":{let Y=$.runtime.blockTask(z$(X.taskId,"taskId"),$.requesterId,z$(X.reason,"reason"));return E(X8,{action:"block",taskId:Y.id,status:Y.status})}}}}));let j=new Map;return W.push(W0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(Df),execute:async(f)=>{let X=E(Df,f);if(X.runMode==="async"){let H=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return E(X9,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${H.id}.`,runId:H.id})}let Y=j.get(X.agentId);if(Y){let H=await Y;return E(X9,{...H,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let V=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((H)=>E(X9,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(X.agentId)});return j.set(X.agentId,V),await V}})),W.push(W0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(ff),execute:async(f)=>{let X=E(ff,f),Y=$.runtime.cancelRun(X.runId,X.reason);return E(zR,{runId:Y.id,status:Y.status})}})),W.push(W0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(Bf),execute:async(f)=>E(Y9.array(),$.runtime.listRuns(E(Bf,f)).map(V9))})),W.push(W0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:j0(Wf),timeoutMs:GR,execute:async(f)=>{let X=E(Wf,f);if(X.runId){let H=await $.runtime.awaitRun(X.runId);return SR(H),E(Y9,V9(H))}let Y=await $.runtime.awaitAllRuns(),V=Y.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(V.length>0){let H=V.map((B)=>`${B.id}:${B.status}${B.error?`(${B.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return E(Y9.array(),Y.map(V9))}})),W.push(W0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(Uf),execute:async(f)=>{let X=E(Uf,f),Y=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return E(PR,{id:Y.id,toAgentId:Y.toAgentId})}})),W.push(W0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(jf),execute:async(f)=>{let X=E(jf,f),Y=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return E(RR,{delivered:Y.length})}})),W.push(W0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(Gf),execute:async(f)=>{let X=E(Gf,f);return E(TR.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),W.push(W0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(Af),execute:async(f)=>{let X=E(Af,f),Y=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return E(MR,{id:Y.id})}})),W.push(W0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(Xf),execute:async(f)=>{if(E(Xf,f),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),E(LR,{status:"cleaned"})}})),W.push(W0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(Yf),execute:async(f)=>{let X=E(Yf,f),Y=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return E(_R,{outcomeId:Y.id,status:Y.status,requiredSections:Y.requiredSections})}})),W.push(W0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(Zf),execute:async(f)=>{let X=E(Zf,f),Y=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return E(Kf,{fragmentId:Y.id,status:Y.status})}})),W.push(W0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(Ff),execute:async(f)=>{let X=E(Ff,f),Y=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return E(Kf,{fragmentId:Y.id,status:Y.status})}})),W.push(W0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(Vf),execute:async(f)=>{let X=E(Vf,f),Y=$.runtime.finalizeOutcome(X.outcomeId);return E(OR,{outcomeId:Y.id,status:Y.status})}})),W.push(W0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(Hf),execute:async(f)=>{return E(Hf,f),E(qR.array(),$.runtime.listOutcomes())}})),W}function qf($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}var CR=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:D2({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...N6]}],yR={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function ER($){return $==="plan"||$==="yolo"?$:"act"}function Nf($){let J=ER($.mode),Q=$1[x1({mode:J})],Z=Z8($.providerId??"",$.modelId??"",J,Q8);return{mode:J,flags:{...Q,...Z,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function Pf($,J){if(J.disabledToolIds?.has($))return!1;let{flags:Q}=Nf(J);if($==="spawn_agent")return Q.enableSpawnAgent===!0;if($==="teams")return Q.enableAgentTeams===!0;if($==="editor")return Q.enableEditor===!0||Q.enableApplyPatch===!0;let Z=yR[$];return Z?Q[Z]===!0:!1}function bR($,J){if($.id==="editor"){let{flags:Q}=Nf(J),Z=Q.enableApplyPatch===!0&&Q.enableEditor!==!0;return{...$,defaultEnabled:Pf($.id,J),headlessToolNames:[Z?"apply_patch":"editor"]}}return{...$,defaultEnabled:Pf($.id,J)}}function V8($={}){return CR.map((J)=>bR(J,$))}function wf($={}){return V8($).filter((J)=>J.defaultEnabled).map((J)=>J.id)}function Sf($){if(!$.enabled)return new Set;let J=V8($.availabilityContext),Q=new Set(J.map((Z)=>Z.id));if(!$.allowlist||$.allowlist.length===0)return new Set(J.filter((Z)=>Z.defaultEnabled).map((Z)=>Z.id));for(let Z of $.allowlist)if(!Q.has(Z))throw Error(`Unknown tool "${Z}". Available tools: ${J.map((W)=>W.id).join(", ")}`);return new Set($.allowlist)}function H9($,J={}){return V8(J).filter((Q)=>$.has(Q.id)).flatMap((Q)=>Q.headlessToolNames)}function Cf($,J={}){return H9($,J)}function H8($={}){let{executorOptions:J={},executors:Q,...Z}=$,W={...O6(J),...Q??{}};return B2({...Z,executors:W})}function S6($){return $.trim().replace(/^\/+/,"").toLowerCase()}function hR($){if(!$||$.length===0)return;let J=$.map(S6).filter((Q)=>Q.length>0);return J.length>0?new Set(J):void 0}function kR($,J,Q){if(!Q)return!0;let Z=S6($),W=S6(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function B8($,J){let Q=hR(J);return[...$.getSnapshot("skill").entries()].map(([W,j])=>{let f=j.item;return{id:W,name:f.name.trim(),description:f.description?.trim(),disabled:f.disabled===!0,skill:f}}).filter((W)=>kR(W.id,W.name,Q))}function IR($,J){return B8($,J).filter((Q)=>!Q.disabled).map((Q)=>Q.name.trim()).filter((Q)=>Q.length>0).sort((Q,Z)=>Q.localeCompare(Z))}function xR($,J,Q){let Z=S6(J);if(!Z)return{error:"Missing skill name."};let W=B8($,Q),j=W.find((H)=>H.id===Z);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let f=Z.includes(":")?Z.split(":").at(-1)??Z:Z,X=W.filter(({id:H})=>{if(H===f)return!0;return H.endsWith(`:${f}`)}),Y=X.filter(({skill:H})=>H.disabled!==!0);if(Y.length===1){let{id:H,skill:B}=Y[0];return{id:H,skill:B}}if(Y.length>1)return{error:`Skill "${J}" is ambiguous. Use one of: ${Y.map(({id:H})=>H).join(", ")}`};if(X.length===1){let{skill:H}=X[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${J}" is ambiguous, and all matches are disabled: ${X.map(({id:H})=>H).join(", ")}`};let V=IR($,Q);return{error:V.length>0?`Skill "${J}" not found. Available skills: ${V.join(", ")}`:"No skills are currently available."}}function B9($,J=Promise.resolve(),Q){let Z=new Set,W=async(j,f)=>{await J;let X=xR($,j,Q);if("error"in X)return X.error;let{id:Y,skill:V}=X;if(Z.has(Y))return`Skill "${V.name}" is already running.`;Z.add(Y);try{let H=f?.trim(),B=H?`
156
156
  <command-args>${H}</command-args>`:"",A=V.description?.trim()?`Description: ${V.description.trim()}
157
157
 
158
158
  `:"";return`<command-name>${V.name}</command-name>${B}
159
159
  <command-instructions>
160
160
  ${A}${V.instructions}
161
- </command-instructions>`}finally{Z.delete(Y)}};return Object.defineProperty(W,"configuredSkills",{get:()=>B8($,Q).map(({skill:j,...f})=>f),enumerable:!0,configurable:!1}),W}function Sf($){let J=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Z)=>Boolean(Z))},async setup(Z){if(await J,$.includeRules)Z.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>i3($.watcher)});if($.registerSkillsTool)Z.registerTool(H2(B9($.watcher,J,$.allowedSkillNames)));for(let W of o2($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Z.registerCommand({name:W.name,description:W.description,handler:(j)=>{let f=j.trim();return f?`${W.instructions}
161
+ </command-instructions>`}finally{Z.delete(Y)}};return Object.defineProperty(W,"configuredSkills",{get:()=>B8($,Q).map(({skill:j,...f})=>f),enumerable:!0,configurable:!1}),W}function yf($){let J=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Z)=>Boolean(Z))},async setup(Z){if(await J,$.includeRules)Z.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>n3($.watcher)});if($.registerSkillsTool)Z.registerTool(H2(B9($.watcher,J,$.allowedSkillNames)));for(let W of o2($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Z.registerCommand({name:W.name,description:W.description,handler:(j)=>{let f=j.trim();return f?`${W.instructions}
162
162
 
163
- ${f}`:W.instructions}})}}}class Cf{watcher;ready;stopped=!1;constructor($){this.watcher=u3($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([J,Q])=>({type:$,id:J,filePath:Q.filePath,item:Q.item}))}listRuntimeCommands(){return o2(this.watcher)}resolveRuntimeSlashCommand($){return p3($,this.watcher)}hasConfiguredSkills($){return B8(this.watcher,$).some((J)=>!J.disabled)}createSkillsExecutor($){return B9(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return Sf({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function U2($){return new Cf($)}import{readFile as xR,writeFile as gR}from"node:fs/promises";import Ef from"yaml";function mR($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q,j=Ef.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}function yf($,J){return`---
164
- ${Ef.stringify($).trimEnd()}
163
+ ${f}`:W.instructions}})}}}class Ef{watcher;ready;stopped=!1;constructor($){this.watcher=d3($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([J,Q])=>({type:$,id:J,filePath:Q.filePath,item:Q.item}))}listRuntimeCommands(){return o2(this.watcher)}resolveRuntimeSlashCommand($){return r3($,this.watcher)}hasConfiguredSkills($){return B8(this.watcher,$).some((J)=>!J.disabled)}createSkillsExecutor($){return B9(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return yf({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function U2($){return new Ef($)}import{readFile as gR,writeFile as mR}from"node:fs/promises";import hf from"yaml";function vR($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q,j=hf.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}function bf($,J){return`---
164
+ ${hf.stringify($).trimEnd()}
165
165
  ---
166
- ${J}`}function vR($,J){let{data:Q,body:Z,hadFrontmatter:W}=mR($);if(!W&&J)return $;if(J){if(delete Q.disabled,Q.enabled===!1)delete Q.enabled;if(Object.keys(Q).length===0)return Z;return yf(Q,Z)}return Q.disabled=!0,yf(Q,Z)}async function bf({filePath:$,enabled:J}){let Q=await xR($,"utf8"),Z=vR(Q,J);return await gR($,Z),{filePath:$,enabled:J,disabled:!J}}import{spawn as Kz}from"node:child_process";import{StringDecoder as nf}from"node:string_decoder";import{UnauthorizedError as df}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as Gz}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as Zz}from"node:crypto";import{UnauthorizedError as Wz}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as jz}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as fz}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as Xz}from"@modelcontextprotocol/sdk/client/streamableHttp.js";C6();var Yz="/mcp/oauth/callback",Vz=[1456,1457,1458],Hz=300000;function Bz($){if($ instanceof Error){let J=$.message.trim();if(J.length>0)return J}return String($)}function Az($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function E6($){let J={};try{J=F8($.serverName,{filePath:$.settingsPath})??{}}catch{J={}}let Q,Z,W=async(f)=>{let X=R2(f(J))??{};try{J=D8($.serverName,()=>X,{filePath:$.settingsPath})}catch{J=X}};return{provider:{get redirectUrl(){return J.redirectUrl??$.redirectUrl},get clientMetadata(){return Az(J.redirectUrl??$.redirectUrl)},state:()=>{return Z=Zz(),Z},clientInformation:()=>J.clientInformation,saveClientInformation:async(f)=>{await W((X)=>({...X,clientInformation:f,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>J.tokens,saveTokens:async(f)=>{await W((X)=>({...X,tokens:f,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(f)=>{Q=f.toString(),await $.onAuthorizationUrl?.(Q)},saveCodeVerifier:async(f)=>{await W((X)=>({...X,codeVerifier:f,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!J.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return J.codeVerifier},invalidateCredentials:async(f)=>{await W((X)=>{if(f==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...f==="client"?{clientInformation:void 0}:{},...f==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...f==="verifier"?{codeVerifier:void 0}:{},...f==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(f)=>{await W((X)=>({...X,discoveryState:f}))},discoveryState:()=>J.discoveryState},getLastAuthorizationUrl:()=>Q,getLastOAuthState:()=>Z,resetInteractiveState:async()=>{await W((f)=>({...f,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(f)=>{await W((X)=>({...X,lastError:f}))},clearError:async()=>{await W((f)=>({...f,lastError:void 0}))}}}function y6($){let J=$.registration.transport;if(J.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Q=J.headers?{headers:J.headers}:void 0;if(J.type==="sse")return new fz(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch});return new Xz(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch})}function cf($){return new jz({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function uf($){let J=$.serverName.trim();if(!J)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Q}=await Promise.resolve().then(() => (C6(),vf)),Z=Q({filePath:$.filePath}).find((Y)=>Y.name===J);if(!Z)throw Error(`MCP server "${J}" is not configured.`);if(Z.disabled)throw Error(`MCP server "${J}" is disabled. Enable it before running OAuth.`);if(Z.transport.type==="stdio")throw Error(`MCP server "${J}" uses stdio transport and does not support OAuth browser flow.`);let W=await Y1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:Vz,callbackPath:$.callbackPath??Yz,timeoutMs:$.timeoutMs??Hz,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!W.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=E6({settingsPath:$.filePath,serverName:J,redirectUrl:W.callbackUrl,onAuthorizationUrl:async(Y)=>{await $.openUrl?.(Y)}});await j.resetInteractiveState();let f=cf($),X;try{let Y=y6({registration:Z,oauthProvider:j.provider,fetch:$.fetch});try{return await f.connect(Y),await f.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" is already authorized.`}}catch(V){if(!(V instanceof Wz))throw V;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${J}" did not provide an authorization URL.`);let B=await W.waitForCallback();if(!B)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(B.error)throw Error(`OAuth authorization failed: ${B.error}`);if(!B.code)throw Error("OAuth callback did not include an authorization code.");let A=j.getLastOAuthState();if(!A)throw Error(`MCP server "${J}" did not start an OAuth stateful authorization flow.`);if(B.state!==A)throw Error("OAuth authorization failed: state mismatch.");await Y.finishAuth(B.code),X=cf($);let K=y6({registration:Z,oauthProvider:j.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" OAuth authorization completed.`}}}catch(Y){let V=Bz(Y);throw await j.markError(V),Error(V)}finally{await f.close().catch(()=>{return}),await X?.close().catch(()=>{return}),W.close()}}var Fz="2024-11-05",Dz=5000,Uz=1500,lf="http://127.0.0.1:1456/mcp/oauth/callback";function b6($){return $ instanceof Error?$.message:String($)}function pf($){let J=Buffer.from(JSON.stringify($),"utf8"),Q=Buffer.from(`Content-Length: ${J.byteLength}\r
166
+ ${J}`}function cR($,J){let{data:Q,body:Z,hadFrontmatter:W}=vR($);if(!W&&J)return $;if(J){if(delete Q.disabled,Q.enabled===!1)delete Q.enabled;if(Object.keys(Q).length===0)return Z;return bf(Q,Z)}return Q.disabled=!0,bf(Q,Z)}async function kf({filePath:$,enabled:J}){let Q=await gR($,"utf8"),Z=cR(Q,J);return await mR($,Z),{filePath:$,enabled:J,disabled:!J}}import{spawn as Gz}from"node:child_process";import{StringDecoder as sf}from"node:string_decoder";import{UnauthorizedError as pf}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as Fz}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as Wz}from"node:crypto";import{UnauthorizedError as jz}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as fz}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Xz}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as Yz}from"@modelcontextprotocol/sdk/client/streamableHttp.js";C6();var Vz="/mcp/oauth/callback",Hz=[1456,1457,1458],Bz=300000;function Az($){if($ instanceof Error){let J=$.message.trim();if(J.length>0)return J}return String($)}function Kz($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function E6($){let J={};try{J=F8($.serverName,{filePath:$.settingsPath})??{}}catch{J={}}let Q,Z,W=async(f)=>{let X=R2(f(J))??{};try{J=D8($.serverName,()=>X,{filePath:$.settingsPath})}catch{J=X}};return{provider:{get redirectUrl(){return J.redirectUrl??$.redirectUrl},get clientMetadata(){return Kz(J.redirectUrl??$.redirectUrl)},state:()=>{return Z=Wz(),Z},clientInformation:()=>J.clientInformation,saveClientInformation:async(f)=>{await W((X)=>({...X,clientInformation:f,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>J.tokens,saveTokens:async(f)=>{await W((X)=>({...X,tokens:f,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(f)=>{Q=f.toString(),await $.onAuthorizationUrl?.(Q)},saveCodeVerifier:async(f)=>{await W((X)=>({...X,codeVerifier:f,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!J.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return J.codeVerifier},invalidateCredentials:async(f)=>{await W((X)=>{if(f==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...f==="client"?{clientInformation:void 0}:{},...f==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...f==="verifier"?{codeVerifier:void 0}:{},...f==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(f)=>{await W((X)=>({...X,discoveryState:f}))},discoveryState:()=>J.discoveryState},getLastAuthorizationUrl:()=>Q,getLastOAuthState:()=>Z,resetInteractiveState:async()=>{await W((f)=>({...f,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(f)=>{await W((X)=>({...X,lastError:f}))},clearError:async()=>{await W((f)=>({...f,lastError:void 0}))}}}function y6($){let J=$.registration.transport;if(J.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Q=J.headers?{headers:J.headers}:void 0;if(J.type==="sse")return new Xz(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch});return new Yz(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch})}function df($){return new fz({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function lf($){let J=$.serverName.trim();if(!J)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Q}=await Promise.resolve().then(() => (C6(),uf)),Z=Q({filePath:$.filePath}).find((Y)=>Y.name===J);if(!Z)throw Error(`MCP server "${J}" is not configured.`);if(Z.disabled)throw Error(`MCP server "${J}" is disabled. Enable it before running OAuth.`);if(Z.transport.type==="stdio")throw Error(`MCP server "${J}" uses stdio transport and does not support OAuth browser flow.`);let W=await Y1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:Hz,callbackPath:$.callbackPath??Vz,timeoutMs:$.timeoutMs??Bz,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!W.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=E6({settingsPath:$.filePath,serverName:J,redirectUrl:W.callbackUrl,onAuthorizationUrl:async(Y)=>{await $.openUrl?.(Y)}});await j.resetInteractiveState();let f=df($),X;try{let Y=y6({registration:Z,oauthProvider:j.provider,fetch:$.fetch});try{return await f.connect(Y),await f.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" is already authorized.`}}catch(V){if(!(V instanceof jz))throw V;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${J}" did not provide an authorization URL.`);let B=await W.waitForCallback();if(!B)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(B.error)throw Error(`OAuth authorization failed: ${B.error}`);if(!B.code)throw Error("OAuth callback did not include an authorization code.");let A=j.getLastOAuthState();if(!A)throw Error(`MCP server "${J}" did not start an OAuth stateful authorization flow.`);if(B.state!==A)throw Error("OAuth authorization failed: state mismatch.");await Y.finishAuth(B.code),X=df($);let K=y6({registration:Z,oauthProvider:j.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" OAuth authorization completed.`}}}catch(Y){let V=Az(Y);throw await j.markError(V),Error(V)}finally{await f.close().catch(()=>{return}),await X?.close().catch(()=>{return}),W.close()}}var Dz="2024-11-05",Uz=5000,Rz=1500,rf="http://127.0.0.1:1456/mcp/oauth/callback";function b6($){return $ instanceof Error?$.message:String($)}function nf($){let J=Buffer.from(JSON.stringify($),"utf8"),Q=Buffer.from(`Content-Length: ${J.byteLength}\r
167
167
  \r
168
- `,"utf8");return Buffer.concat([Q,J])}function rf($){return Buffer.from(`${JSON.stringify($)}
169
- `,"utf8")}class D9{buffer="";decoder=new nf("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`\r
168
+ `,"utf8");return Buffer.concat([Q,J])}function af($){return Buffer.from(`${JSON.stringify($)}
169
+ `,"utf8")}class D9{buffer="";decoder=new sf("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`\r
170
170
  \r
171
- `);if(Q<0)break;let W=this.buffer.slice(0,Q).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!W)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(W[1],10),f=Q+4,X=f+j;if(this.buffer.length<X)break;J.push(this.buffer.slice(f,X)),this.buffer=this.buffer.slice(X)}return J}}class U9{buffer="";decoder=new nf("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`
172
- `);if(Q<0)break;let Z=this.buffer.slice(0,Q).trim();if(this.buffer=this.buffer.slice(Q+1),Z.length>0)J.push(Z)}return J}}class af{registration;process;nextRequestId=1;pending=new Map;framedParser=new D9;newlineParser=new U9;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],J;for(let Q of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Q);try{await this.request("initialize",{protocolVersion:Fz,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Uz),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Q;return}catch(Z){J=Z instanceof Error?Z:Error(String(Z))}}throw J??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((J)=>typeof J?.name==="string"&&typeof J.inputSchema==="object"&&J.inputSchema!==null).map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let J=this.registration.transport;if(J.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${J.type}`);this.framedParser=new D9,this.newlineParser=new U9,this.stderrBuffer="",this.protocolMode=$;let Q=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Z=Kz(J.command,J.args??[],{cwd:J.cwd,env:{...process.env,...J.env??{}},stdio:["pipe","pipe","pipe"],...Q});this.process=Z,Z.stdout.on("data",(W)=>this.handleStdout(W)),Z.stderr.on("data",(W)=>{if(this.process!==Z)return;if(this.stderrBuffer+=W.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Z.once("error",(W)=>{if(this.process!==Z)return;this.failAllPending(Error(`MCP process error: ${b6(W)}`))}),Z.once("exit",(W,j)=>{if(this.process!==Z)return;this.connected=!1,this.process=void 0;let f=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${W??"null"}, signal=${j??"null"}).${f}`))})}handleStdout($){try{let J=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Q of J){let Z=JSON.parse(Q);if(typeof Z.id!=="number")continue;let W=this.pending.get(Z.id);if(!W)continue;if(this.pending.delete(Z.id),clearTimeout(W.timeout),Z.error){let j=Z.error.message||`MCP request failed with code ${Z.error.code??"unknown"}`;W.reject(Error(j));continue}W.resolve(Z.result)}}catch(J){this.handleProtocolFailure(J)}}handleProtocolFailure($){let J=this.process;if(!J)return;this.connected=!1,this.process=void 0;let Q=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${b6($)}.${Q}`)),J.kill()}async request($,J,Q=Dz){let Z=this.process;if(!Z?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let W=this.nextRequestId++,j={jsonrpc:"2.0",id:W,method:$,...J?{params:J}:{}},f=new Promise((X,Y)=>{let V=setTimeout(()=>{this.pending.delete(W),Y(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Q);this.pending.set(W,{resolve:X,reject:Y,timeout:V})});try{Z.stdin.write(this.protocolMode==="framed"?pf(j):rf(j))}catch(X){let Y=this.pending.get(W);if(Y)clearTimeout(Y.timeout),this.pending.delete(W);throw X}return f}notify($,J){let Q=this.process;if(!Q?.stdin.writable)return;let Z={jsonrpc:"2.0",method:$,...J?{params:J}:{}};Q.stdin.write(this.protocolMode==="framed"?pf(Z):rf(Z))}failAllPending($){for(let[J,Q]of this.pending)clearTimeout(Q.timeout),this.pending.delete(J),Q.reject($)}}class sf{registration;options;client;authContext;constructor($,J){this.registration=$;this.options=J}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=E6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??lf});this.authContext=$;try{let J=new Gz({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Q=y6({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await J.connect(Q),await $.clearError(),this.client=J}catch(J){let Q=J instanceof df?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):b6(J);throw await $.markError(Q),Error(Q)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema&&typeof Q.inputSchema==="object"&&!Array.isArray(Q.inputSchema)?Q.inputSchema:{}}))}catch(J){return await this.handleOperationError(J)}}async callTool($){let J=await this.ensureConnectedClient();try{return await J.callTool({name:$.name,arguments:$.arguments??{}})}catch(Q){return await this.handleOperationError(Q)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let J=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${J} Run authorizeMcpServerOAuth for this server.`;return`${J} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let J=this.authContext??E6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??lf}),Q=$ instanceof df?this.formatUnauthorizedMessage(J.getLastAuthorizationUrl()):b6($);throw await J.markError(Q),Error(Q)}}function h6($={}){return(J)=>J.transport.type==="stdio"?new af(J):new sf(J,$)}C6();function h0(){return Date.now()}function Rz($){return $.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}class R8{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let J=this.servers.get($.name);if(!J){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:h0()});return}let Q=JSON.stringify(J.registration.transport)!==JSON.stringify($.transport);if(J.registration={...$},J.updatedAt=h0(),Q)await this.disconnectState(J),J.client=void 0,J.toolCache=void 0,J.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.connectState(J)})}async disconnectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J)})}async setServerDisabled($,J){await this.runExclusive($,async()=>{let Q=this.requireServer($);if(Q.registration={...Q.registration,disabled:J},Q.updatedAt=h0(),J)await this.disconnectState(Q)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,J)=>$.name.localeCompare(J.name))}async listTools($){let J=this.requireServer($),Q=J.toolCacheUpdatedAt??0;if(J.toolCache&&h0()-Q<=this.toolsCacheTtlMs)return J.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let J=this.requireServer($),Z=await(await this.ensureConnectedClient(J)).listTools(),W=Rz(Z);return J.toolCache=W,J.toolCacheUpdatedAt=h0(),J.updatedAt=h0(),W})}async callTool($){return this.runExclusive($.serverName,async()=>{let J=this.requireServer($.serverName),Q=await this.ensureConnectedClient(J);return J.updatedAt=h0(),Q.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let J of $)await this.unregisterServer(J)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=h0();try{let J=$.client??await this.clientFactory($.registration);await J.connect(),$.client=J,$.status="connected",$.lastError=void 0,$.updatedAt=h0()}catch(J){throw $.status="disconnected",$.lastError=J instanceof Error?J.message:String(J),$.updatedAt=h0(),J}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=h0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=h0()}}requireServer($){let J=this.servers.get($);if(!J)throw Error(`Unknown MCP server: ${$}`);return J}async runExclusive($,J){let Q=this.operationLocks.get($)??Promise.resolve(),Z,W=new Promise((f)=>{Z=f}),j=Q.catch(()=>{return}).then(()=>W);this.operationLocks.set($,j),await Q.catch(()=>{return});try{return await J()}finally{if(Z?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function z2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function of($){return z2($)&&Object.values($).every((J)=>typeof J==="string")}function zz($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function Lz($){if(!z2($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function _z($){let J=$.env?Object.entries($.env):[];if(J.length===0)return{ok:!0};let Q={};for(let[Z,W]of J){if(typeof W==="string"){Q[Z]=W;continue}let j=W.fromEnv?.trim()||Z,f=process.env[j];if(typeof f==="string"&&f.length>0){Q[Z]=f;continue}if(typeof W.value==="string"){Q[Z]=W.value;continue}if(W.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Q).length>0?Q:void 0}}function tf($){if(!z2($))return{name:"",loadError:"invalid MCP server registration"};let J=typeof $.name==="string"?$.name.trim():"";if(!J)return{name:J,loadError:"empty MCP server name"};let Q=$.env,Z=Q===void 0?void 0:Q;if(Z!==void 0){if(!z2(Z))return{name:J,loadError:"invalid env"};for(let[Y,V]of Object.entries(Z))if(typeof V!=="string"&&!Lz(V))return{name:J,loadError:`invalid env "${Y}"`}}let W=$.transport;if(!z2(W))return{name:J,loadError:"invalid MCP transport"};let j=W.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:J,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Z!==void 0)return{name:J,loadError:"top-level env is only supported for stdio MCP transports"};let f=z2($.metadata)?$.metadata:void 0;if(j==="stdio"){let Y=W.command;if(typeof Y!=="string"||!Y.trim())return{name:J,loadError:"stdio MCP transport requires command"};let V=W.args;if(V!==void 0&&!zz(V))return{name:J,loadError:"stdio MCP transport args must be strings"};let H=W.cwd;if(H!==void 0&&typeof H!=="string")return{name:J,loadError:"stdio MCP transport cwd must be a string"};let B=W.env;if(B!==void 0&&!of(B))return{name:J,loadError:"stdio MCP transport env must be strings"};let A=_z({name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:B},env:Z,metadata:f});if(!A.ok)return{name:J,loadError:A.reason};let K=B||A.env?{...B??{},...A.env??{}}:void 0;return{name:J,registration:{name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:K},metadata:f}}}if(typeof W.url!=="string"||!W.url.trim())return{name:J,loadError:`${j} MCP transport requires url`};let X=W.headers;if(X!==void 0&&!of(X))return{name:J,loadError:`${j} MCP transport headers must be strings`};return{name:J,registration:{name:J,transport:j==="sse"?{type:"sse",url:W.url,headers:X}:{type:"streamableHttp",url:W.url,headers:X},metadata:f}}}function R9($){let J=new Map;return $.map(({server:Q,owner:Z,ownerLabel:W})=>{let j=tf(Q);if(!j.registration)return{owner:Z,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let f=J.get(j.registration.name);if(J.has(j.registration.name)){let X=f?` already registered by ${f}`:"";return{owner:Z,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${X}`}}return J.set(j.registration.name,W),{owner:Z,name:j.registration.name,registration:j.registration}})}import{createHash as Oz}from"node:crypto";var ef=128,Tz=/[^a-zA-Z0-9_-]+/g,$X=8,Mz=1,qz="mcp_tool";function Pz($){return Oz("sha1").update($).digest("hex").slice(0,$X)}function Nz($){return $.replace(Tz,"_")}var k6=({serverName:$,toolName:J})=>{let Q=`${$}__${J}`,Z=Nz(Q);if(Z===Q&&Q.length<=ef)return Q;let W=Pz(Q),j=ef-Mz-$X;return`${Z.slice(0,j)||qz}_${W}`};function z9($){return{[($.nameTransform??k6)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function JX($){let J={};for(let Q of $.toolNames)Object.assign(J,z9({serverName:$.serverName,toolName:Q,nameTransform:$.nameTransform}));return J}import{createTool as wz}from"@cline/shared";function Sz($,J){let Q=J.description?.trim();if(Q)return Q;return`Execute MCP tool "${J.name}" from server "${$}".`}async function I6($){let J=await $.provider.listTools($.serverName),Q=$.nameTransform??k6;return J.map((Z)=>{let W=Q({serverName:$.serverName,toolName:Z.name});return wz({name:W,description:Sz($.serverName,Z),inputSchema:Z.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,f)=>$.provider.callTool({serverName:$.serverName,toolName:Z.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:f})})})}p0();import{stat as Cz}from"node:fs/promises";import{isAbsolute as yz,relative as Ez,resolve as QX}from"node:path";p0();function bz($,J){let Q=Ez(QX($),QX(J));return Q===""||!Q.startsWith("..")&&!yz(Q)}var hz=32,L2=new Map;function kz($,J){if(!L2.has($)&&L2.size>=hz){let Q=L2.keys().next().value;if(Q)L2.delete(Q)}L2.set($,J)}async function Iz($){let J=await Promise.all($.pluginPaths.map(async(Q)=>{try{let Z=await Cz(Q);return`${Q}:${Z.mtimeMs}:${Z.size}`}catch{return`${Q}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:J})}function ZX($,J){return $.map((Q)=>({...Q,enabled:!J.has(Q.name)}))}function xz($){return $.sort((J,Q)=>{let Z=J.name.localeCompare(Q.name);if(Z!==0)return Z;return J.path.localeCompare(Q.path)})}async function gz($,J){if(!$.setup)return{tools:[]};let Q=[],Z={registerTool:(W)=>Q.push(W),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(W)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Z,{workspaceInfo:J}),{tools:Q}}async function WX($){let J=n2({workspacePath:$.workspacePath,cwd:$.cwd}),Q=H1($.disabledToolNames);if(J.length===0)return{tools:[],failures:[],warnings:[]};let Z=await Iz({pluginPaths:J,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),W=L2.get(Z);if(W)return{tools:ZX(W.tools,Q),failures:W.failures,warnings:W.warnings};let j=[],f=[],X=[],Y;try{Y=await W2({pluginPaths:J,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),f=[...Y.failures],X=[...Y.warnings];for(let H of Y.extensions??[]){let B=H.__clinePluginPath;if(!B)continue;let A=bz($.workspacePath,B)?"workspace-plugin":"global-plugin",K;try{K=await gz(H,{rootPath:$.workspacePath})}catch(G){f.push({pluginPath:B,pluginName:H.name,phase:"setup",message:G instanceof Error?G.message:String(G),stack:G instanceof Error?G.stack:void 0});continue}for(let G of K.tools)j.push({name:G.name,pluginName:H.name,path:B,source:A,description:G.description?.trim()||void 0})}}catch(H){f=J.map((B)=>({pluginPath:B,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await Y?.shutdown().catch(()=>{})}let V=xz(j);return kz(Z,{tools:V,failures:f,warnings:X}),{tools:ZX(V,Q),failures:f,warnings:X}}async function L9($){return(await WX($)).tools}function g6($,J){if(!J)return"global";let Q=vz(J,$);return!Q.startsWith("..")&&!mz(Q)?"workspace":"global"}function z8($){return[...$].sort((J,Q)=>{let Z=(W)=>{switch(W){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(J.source!==Q.source)return Z(J.source)-Z(Q.source);return J.name.localeCompare(Q.name)})}function XX($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function fX($,J){if($.userInstructionService)return await J($.userInstructionService);let Q=XX($);if(!Q)return await J(void 0);let Z=$.cwd?.trim()||Q,W=U2({skills:{workspacePath:Q,includePluginSkills:!0,cwd:Z},rules:{workspacePath:Q},workflows:{workspacePath:Q}});try{return await W.start(),await J(W)}finally{W.stop()}}function cz($,J){if(!$)return;let Q=$.listRecords("skill");if(J.id){let Z=Q.find((W)=>W.id===J.id);if(Z)return Z}for(let Z of Q)if(Z.filePath===J.path||Z.item.name===J.name||Z.id===J.name)return Z;return}class _2{async list($={}){return await fX($,async(J)=>{let Q=XX($),Z=[],W=[],j=[],f=[],X=[];if(J){for(let V of J.listRecords("workflow")){let H=V.item;Z.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"workflow",source:g6(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("rule")){let H=V.item;W.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"rule",source:g6(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("skill")){let H=V.item;j.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"skill",source:g6(V.filePath,Q),description:H.description,toggleable:!0})}}if(Q)try{for(let V of await L9({workspacePath:Q,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))f.push({id:`${V.pluginName}:${V.name}:${V.path}`,name:V.name,path:V.path,enabled:V.enabled,kind:"tool",source:V.source,description:V.description,toggleable:!0})}catch{}let Y=H0();if(L$({filePath:Y}))try{for(let V of m1({filePath:Y}))X.push({id:V.name,name:V.name,path:Y,enabled:V.disabled!==!0,kind:"mcp",source:g6(Y,Q),description:V.transport.type,toggleable:!0})}catch{}return{workflows:z8(Z.filter((V)=>x6(V.path))),rules:z8(W.filter((V)=>x6(V.path))),skills:z8(j.filter((V)=>x6(V.path))),tools:z8(f),mcp:z8(X.filter((V)=>x6(V.path)))}})}async toggle($){if($.type==="skills")return await fX($,async(J)=>{let Q=cz(J,$),Z=Q?.filePath;if(!Z)throw Error(`Unable to resolve skill setting '${$.id??$.name??jX($.path??"")}'.`);let W=Q?.item&&"disabled"in Q.item?Q.item.disabled!==!0:void 0,j=$.enabled??(W!==void 0?!W:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??jX($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await bf({filePath:Z,enabled:j}),await J?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:J}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)ZQ($.name);else K3($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let J=$.name?.trim()||$.id?.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=$.path?.trim()||H0(),Z=$.enabled;if(Z===void 0){let W=m1({filePath:Q}).find((j)=>j.name===J);if(!W)throw Error(`Unknown MCP server: ${J}`);Z=W.disabled===!0}return G8({filePath:Q,name:J,disabled:!Z}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function L8(){return new _2}function YX($){return{async list(J){let Q=$;if(Q.listSettings)return await Q.listSettings(J);return await L8().list(J)},async toggle(J){let Q=$;if(Q.toggleSetting)return await Q.toggleSetting(J);return await L8().toggle(J)}}}function VX($){function J(){let Q=$.pendingPrompts;if(!Q)throw Error("Pending prompt service is not available.");return Q}return{list(Q){return J().list(Q)},update(Q){return J().update(Q)},delete(Q){return J().delete(Q)}}}function L0(...$){let J,Q;for(let W of $){if(!W)continue;if(W.toolExecutors)J={...J??{},...W.toolExecutors};if(W.requestToolApproval)Q=W.requestToolApproval}let Z=J&&Object.keys(J).length>0;if(!Z&&!Q)return;return{...Z?{toolExecutors:J}:{},...Q?{requestToolApproval:Q}:{}}}var _8="session_not_found";class _$ extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function O$($){return $ instanceof _$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function _9($){let{hooks:J,logger:Q,telemetry:Z,extensionContext:W,extraTools:j,extensions:f,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:H,...B}=$,A={};if(J)A.hooks=J;if(Q)A.logger=Q;if(Z)A.telemetry=Z;if(W)A.extensionContext=W;if(j)A.extraTools=j;if(f)A.extensions=f;if(X)A.onTeamEvent=X;if(Y)A.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)A.checkpoint=V;if(H?.compact)A.compaction=H;let K=Object.keys(A).length>0?A:void 0;return{config:{...B,...V?{checkpoint:{enabled:V.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...K?{localRuntime:K}:{}}}function HX($){let J=$.config;return"providerId"in J?{...$,config:{...J,...uz($.localRuntime)},localRuntime:$.localRuntime}:$}function O9($,J={}){let Q=_9($.config),Z=L0(J.defaultCapabilities,$.capabilities),W=dz(Q.localRuntime,$.localRuntime),j=J.withExtensionContext?.(W?.extensionContext);if(j)W={...W??{},extensionContext:j};return{...$,...Q,...W?{localRuntime:W}:{},...Z?{capabilities:Z}:{}}}function uz($){if(!$)return{};let{modelCatalogDefaults:J,userInstructionService:Q,configExtensions:Z,onTeamRestored:W,...j}=$;return j}function dz(...$){let J={};for(let Q of $)if(Q)Object.assign(J,Q);return Object.keys(J).length>0?J:void 0}F0();function BX($){let J=$.input.config.telemetry??$.telemetry;if(!J)return;J.capture({event:k.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??z0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function O8($){return!!$&&typeof $==="object"&&!Array.isArray($)}function T9($){let J=$?.trim();return J?J:void 0}function lz($,J){let Q=$?.trim();if(!Q)return J;let Z=Date.parse(Q);if(!Number.isFinite(Z))return J;return new Date(Z).toISOString()}function AX($,J){return new Date(new Date($).getTime()+Math.max(0,Math.floor(J))*1000).toISOString()}function KX($,J){return new Date(new Date($).getTime()-Math.max(0,Math.floor(J))*1000).toISOString()}function pz($,J){if(!$)return J;return new Date($).getTime()>=new Date(J).getTime()?$:J}function rz($,J){let Q=$.eventId.trim(),Z=$.eventType.trim(),W=$.source.trim(),j=T9($.subject),f=T9($.dedupeKey)??`${Z}:${W}:${j??Q}`;return{eventId:Q,eventType:Z,source:W,subject:j,occurredAt:lz($.occurredAt,J),workspaceRoot:T9($.workspaceRoot),payload:O8($.payload)?$.payload:void 0,attributes:O8($.attributes)?$.attributes:void 0,dedupeKey:f}}function M9($,J){if(!J)return;let Q=J.split("."),Z=$;for(let W of Q){if(!O8(Z))return;Z=Z[W]}return Z}function iz($,J){if($.attributes&&Object.hasOwn($.attributes,J))return $.attributes[J];if($.payload&&Object.hasOwn($.payload,J))return $.payload[J];let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Z=M9(Q,J);if(Z!==void 0)return Z;if($.attributes){let W=M9($.attributes,J);if(W!==void 0)return W}if($.payload)return M9($.payload,J);return}function m6($,J){if(Array.isArray(J))return J.some((Q)=>m6($,Q));if(Array.isArray($))return $.some((Q)=>m6(Q,J));if(O8(J)){if(!O8($))return!1;return Object.entries(J).every(([Q,Z])=>m6($[Q],Z))}return Object.is($,J)}function nz($,J){if(!J||Object.keys(J).length===0)return!0;return Object.entries(J).every(([Q,Z])=>m6(iz($,Q),Z))}class q9{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let J=new Date(this.nowFn()).toISOString(),Q=rz($,J),Z=this.store.insertEventLog(Q,{receivedAtIso:J});if(!Z.created)return this.logger?.debug("cron.event.duplicate",{eventId:Z.record.eventId,eventType:Z.record.eventType,source:Z.record.source}),{event:Z.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Z.record.dedupeKey}]};try{let W=this.store.listEventSpecsForType(Q.eventType),j=[],f=[],X=[];for(let H of W){if(!nz(Q,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Q.dedupeKey});continue}f.push(H);let B=this.materializeForSpec(H,Q,Z.record.receivedAt);if(B.run)X.push(B.run);else j.push({specId:H.specId,externalId:H.externalId,reason:B.reason,dedupeKey:Q.dedupeKey})}let Y=f.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Z.record.eventId,{status:Y,matchedSpecCount:f.length,queuedRunCount:X.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let V=this.store.getEventLog(Z.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Z.record.eventId,eventType:Z.record.eventType,status:Y,matchedSpecCount:f.length,queuedRunCount:X.length}),{event:V??Z.record,duplicate:!1,matchedSpecs:f,queuedRuns:X,suppressions:j}}catch(W){if(this.store.updateEventLogProcessing(Z.record.eventId,{status:"failed",error:W instanceof Error?W.message:String(W)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Z.record.eventId,eventType:Z.record.eventType,error:W});throw W}}materializeForSpec($,J,Q){let Z=J.dedupeKey??J.eventId,W=$.debounceSeconds??0;if(W>0){let Y=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Z});if(Y){let V=pz(Y.scheduledFor,AX(Q,W)),H=this.store.updateQueuedEventRunForDebounce({runId:Y.runId,triggerEventId:J.eventId,scheduledFor:V});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Z,sinceIso:KX(Q,j)}))return{reason:"dedupe_window"};let f=$.cooldownSeconds??0;if(f>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:KX(Q,f)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:J.eventId,scheduledFor:W>0?AX(Q,W):Q}),reason:"dedupe_window"}}}class T8{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},J=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Z of J)if(this.materializeOneOff(Z))$.oneOffQueued+=1;let Q=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Z of Q)try{if(this.materializeSchedule(Z))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as WL}from"node:path";import{buildClineSystemPrompt as jL}from"@cline/shared";import{nowIso as UX}from"@cline/shared/db";import{basename as az,resolve as sz}from"node:path";import{performance as GX}from"node:perf_hooks";import{processWorkspaceInfo as FX}from"@cline/shared";import oz from"simple-git";function T$($){return sz($)}async function c6($){return(await P9($)).info}function v6($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function P9($){let J=T$($),Q={rootPath:J,hint:az(J)},Z;try{let W=oz({baseDir:J});if(!await W.checkIsRepo())return{info:Q,vcsType:"none"};try{let f=await W.getRemotes(!0);if(f.length>0){let X=f.map((Y)=>{let V=Y.refs.fetch||Y.refs.push;return`${Y.name}: ${V}`});Q.associatedRemoteUrls=X}}catch(f){Z??=v6(f)}try{let f=(await W.revparse(["HEAD"])).trim();if(f.length>0)Q.latestGitCommitHash=f}catch(f){Z??=v6(f)}try{let f=(await W.branch()).current.trim();if(f.length>0)Q.latestGitBranchName=f}catch(f){Z??=v6(f)}return{info:Q,vcsType:"git",error:Z}}catch(W){return{info:Q,vcsType:"none",error:v6(W)}}}async function N9($){let J=await c6($);return FX(J)}async function DX($){let J=GX.now(),Q=await P9($),Z=GX.now()-J,W=Q.info;return{workspaceInfo:W,workspaceMetadata:FX(W),durationMs:Z,vcsType:Q.vcsType,initError:Q.error}}import{mkdirSync as tz,writeFileSync as ez}from"node:fs";import{join as $L}from"node:path";import{resolveCronReportsDir as JL}from"@cline/shared/storage";function v1($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function M$($,J){if(J===void 0||J===null)return;return`${$}: ${v1(J)}`}function QL($,J,Q){let Z=[`runId: ${v1($.runId)}`,`specId: ${v1(J.specId)}`,`externalId: ${v1(J.externalId)}`,`title: ${v1(J.title)}`,`triggerKind: ${v1($.triggerKind)}`,`status: ${v1($.status)}`,`sourcePath: ${v1(J.sourcePath)}`],W=[M$("sessionId",$.sessionId),M$("startedAt",$.startedAt),M$("completedAt",$.completedAt),M$("triggerEventId",$.triggerEventId),M$("triggerEventType",Q?.eventType),M$("triggerEventSource",Q?.source),M$("triggerEventSubject",Q?.subject)];for(let j of W)if(j)Z.push(j);return`---
171
+ `);if(Q<0)break;let W=this.buffer.slice(0,Q).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!W)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(W[1],10),f=Q+4,X=f+j;if(this.buffer.length<X)break;J.push(this.buffer.slice(f,X)),this.buffer=this.buffer.slice(X)}return J}}class U9{buffer="";decoder=new sf("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`
172
+ `);if(Q<0)break;let Z=this.buffer.slice(0,Q).trim();if(this.buffer=this.buffer.slice(Q+1),Z.length>0)J.push(Z)}return J}}class of{registration;process;nextRequestId=1;pending=new Map;framedParser=new D9;newlineParser=new U9;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],J;for(let Q of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Q);try{await this.request("initialize",{protocolVersion:Dz,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Rz),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Q;return}catch(Z){J=Z instanceof Error?Z:Error(String(Z))}}throw J??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((J)=>typeof J?.name==="string"&&typeof J.inputSchema==="object"&&J.inputSchema!==null).map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let J=this.registration.transport;if(J.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${J.type}`);this.framedParser=new D9,this.newlineParser=new U9,this.stderrBuffer="",this.protocolMode=$;let Q=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Z=Gz(J.command,J.args??[],{cwd:J.cwd,env:{...process.env,...J.env??{}},stdio:["pipe","pipe","pipe"],...Q});this.process=Z,Z.stdout.on("data",(W)=>this.handleStdout(W)),Z.stderr.on("data",(W)=>{if(this.process!==Z)return;if(this.stderrBuffer+=W.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Z.once("error",(W)=>{if(this.process!==Z)return;this.failAllPending(Error(`MCP process error: ${b6(W)}`))}),Z.once("exit",(W,j)=>{if(this.process!==Z)return;this.connected=!1,this.process=void 0;let f=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${W??"null"}, signal=${j??"null"}).${f}`))})}handleStdout($){try{let J=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Q of J){let Z=JSON.parse(Q);if(typeof Z.id!=="number")continue;let W=this.pending.get(Z.id);if(!W)continue;if(this.pending.delete(Z.id),clearTimeout(W.timeout),Z.error){let j=Z.error.message||`MCP request failed with code ${Z.error.code??"unknown"}`;W.reject(Error(j));continue}W.resolve(Z.result)}}catch(J){this.handleProtocolFailure(J)}}handleProtocolFailure($){let J=this.process;if(!J)return;this.connected=!1,this.process=void 0;let Q=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${b6($)}.${Q}`)),J.kill()}async request($,J,Q=Uz){let Z=this.process;if(!Z?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let W=this.nextRequestId++,j={jsonrpc:"2.0",id:W,method:$,...J?{params:J}:{}},f=new Promise((X,Y)=>{let V=setTimeout(()=>{this.pending.delete(W),Y(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Q);this.pending.set(W,{resolve:X,reject:Y,timeout:V})});try{Z.stdin.write(this.protocolMode==="framed"?nf(j):af(j))}catch(X){let Y=this.pending.get(W);if(Y)clearTimeout(Y.timeout),this.pending.delete(W);throw X}return f}notify($,J){let Q=this.process;if(!Q?.stdin.writable)return;let Z={jsonrpc:"2.0",method:$,...J?{params:J}:{}};Q.stdin.write(this.protocolMode==="framed"?nf(Z):af(Z))}failAllPending($){for(let[J,Q]of this.pending)clearTimeout(Q.timeout),this.pending.delete(J),Q.reject($)}}class tf{registration;options;client;authContext;constructor($,J){this.registration=$;this.options=J}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=E6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??rf});this.authContext=$;try{let J=new Fz({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Q=y6({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await J.connect(Q),await $.clearError(),this.client=J}catch(J){let Q=J instanceof pf?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):b6(J);throw await $.markError(Q),Error(Q)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema&&typeof Q.inputSchema==="object"&&!Array.isArray(Q.inputSchema)?Q.inputSchema:{}}))}catch(J){return await this.handleOperationError(J)}}async callTool($){let J=await this.ensureConnectedClient();try{return await J.callTool({name:$.name,arguments:$.arguments??{}})}catch(Q){return await this.handleOperationError(Q)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let J=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${J} Run authorizeMcpServerOAuth for this server.`;return`${J} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let J=this.authContext??E6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??rf}),Q=$ instanceof pf?this.formatUnauthorizedMessage(J.getLastAuthorizationUrl()):b6($);throw await J.markError(Q),Error(Q)}}function h6($={}){return(J)=>J.transport.type==="stdio"?new of(J):new tf(J,$)}C6();function h0(){return Date.now()}function zz($){return $.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}class R8{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let J=this.servers.get($.name);if(!J){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:h0()});return}let Q=JSON.stringify(J.registration.transport)!==JSON.stringify($.transport);if(J.registration={...$},J.updatedAt=h0(),Q)await this.disconnectState(J),J.client=void 0,J.toolCache=void 0,J.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.connectState(J)})}async disconnectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J)})}async setServerDisabled($,J){await this.runExclusive($,async()=>{let Q=this.requireServer($);if(Q.registration={...Q.registration,disabled:J},Q.updatedAt=h0(),J)await this.disconnectState(Q)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,J)=>$.name.localeCompare(J.name))}async listTools($){let J=this.requireServer($),Q=J.toolCacheUpdatedAt??0;if(J.toolCache&&h0()-Q<=this.toolsCacheTtlMs)return J.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let J=this.requireServer($),Z=await(await this.ensureConnectedClient(J)).listTools(),W=zz(Z);return J.toolCache=W,J.toolCacheUpdatedAt=h0(),J.updatedAt=h0(),W})}async callTool($){return this.runExclusive($.serverName,async()=>{let J=this.requireServer($.serverName),Q=await this.ensureConnectedClient(J);return J.updatedAt=h0(),Q.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let J of $)await this.unregisterServer(J)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=h0();try{let J=$.client??await this.clientFactory($.registration);await J.connect(),$.client=J,$.status="connected",$.lastError=void 0,$.updatedAt=h0()}catch(J){throw $.status="disconnected",$.lastError=J instanceof Error?J.message:String(J),$.updatedAt=h0(),J}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=h0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=h0()}}requireServer($){let J=this.servers.get($);if(!J)throw Error(`Unknown MCP server: ${$}`);return J}async runExclusive($,J){let Q=this.operationLocks.get($)??Promise.resolve(),Z,W=new Promise((f)=>{Z=f}),j=Q.catch(()=>{return}).then(()=>W);this.operationLocks.set($,j),await Q.catch(()=>{return});try{return await J()}finally{if(Z?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function z2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function ef($){return z2($)&&Object.values($).every((J)=>typeof J==="string")}function Lz($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function _z($){if(!z2($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function Oz($){let J=$.env?Object.entries($.env):[];if(J.length===0)return{ok:!0};let Q={};for(let[Z,W]of J){if(typeof W==="string"){Q[Z]=W;continue}let j=W.fromEnv?.trim()||Z,f=process.env[j];if(typeof f==="string"&&f.length>0){Q[Z]=f;continue}if(typeof W.value==="string"){Q[Z]=W.value;continue}if(W.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Q).length>0?Q:void 0}}function $X($){if(!z2($))return{name:"",loadError:"invalid MCP server registration"};let J=typeof $.name==="string"?$.name.trim():"";if(!J)return{name:J,loadError:"empty MCP server name"};let Q=$.env,Z=Q===void 0?void 0:Q;if(Z!==void 0){if(!z2(Z))return{name:J,loadError:"invalid env"};for(let[Y,V]of Object.entries(Z))if(typeof V!=="string"&&!_z(V))return{name:J,loadError:`invalid env "${Y}"`}}let W=$.transport;if(!z2(W))return{name:J,loadError:"invalid MCP transport"};let j=W.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:J,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Z!==void 0)return{name:J,loadError:"top-level env is only supported for stdio MCP transports"};let f=z2($.metadata)?$.metadata:void 0;if(j==="stdio"){let Y=W.command;if(typeof Y!=="string"||!Y.trim())return{name:J,loadError:"stdio MCP transport requires command"};let V=W.args;if(V!==void 0&&!Lz(V))return{name:J,loadError:"stdio MCP transport args must be strings"};let H=W.cwd;if(H!==void 0&&typeof H!=="string")return{name:J,loadError:"stdio MCP transport cwd must be a string"};let B=W.env;if(B!==void 0&&!ef(B))return{name:J,loadError:"stdio MCP transport env must be strings"};let A=Oz({name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:B},env:Z,metadata:f});if(!A.ok)return{name:J,loadError:A.reason};let K=B||A.env?{...B??{},...A.env??{}}:void 0;return{name:J,registration:{name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:K},metadata:f}}}if(typeof W.url!=="string"||!W.url.trim())return{name:J,loadError:`${j} MCP transport requires url`};let X=W.headers;if(X!==void 0&&!ef(X))return{name:J,loadError:`${j} MCP transport headers must be strings`};return{name:J,registration:{name:J,transport:j==="sse"?{type:"sse",url:W.url,headers:X}:{type:"streamableHttp",url:W.url,headers:X},metadata:f}}}function R9($){let J=new Map;return $.map(({server:Q,owner:Z,ownerLabel:W})=>{let j=$X(Q);if(!j.registration)return{owner:Z,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let f=J.get(j.registration.name);if(J.has(j.registration.name)){let X=f?` already registered by ${f}`:"";return{owner:Z,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${X}`}}return J.set(j.registration.name,W),{owner:Z,name:j.registration.name,registration:j.registration}})}import{createHash as Tz}from"node:crypto";var JX=128,Mz=/[^a-zA-Z0-9_-]+/g,QX=8,qz=1,Pz="mcp_tool";function Nz($){return Tz("sha1").update($).digest("hex").slice(0,QX)}function wz($){return $.replace(Mz,"_")}var k6=({serverName:$,toolName:J})=>{let Q=`${$}__${J}`,Z=wz(Q);if(Z===Q&&Q.length<=JX)return Q;let W=Nz(Q),j=JX-qz-QX;return`${Z.slice(0,j)||Pz}_${W}`};function z9($){return{[($.nameTransform??k6)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function ZX($){let J={};for(let Q of $.toolNames)Object.assign(J,z9({serverName:$.serverName,toolName:Q,nameTransform:$.nameTransform}));return J}import{createTool as Sz}from"@cline/shared";function Cz($,J){let Q=J.description?.trim();if(Q)return Q;return`Execute MCP tool "${J.name}" from server "${$}".`}async function I6($){let J=await $.provider.listTools($.serverName),Q=$.nameTransform??k6;return J.map((Z)=>{let W=Q({serverName:$.serverName,toolName:Z.name});return Sz({name:W,description:Cz($.serverName,Z),inputSchema:Z.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,f)=>$.provider.callTool({serverName:$.serverName,toolName:Z.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:f})})})}p0();import{stat as yz}from"node:fs/promises";import{isAbsolute as Ez,relative as bz,resolve as WX}from"node:path";p0();function hz($,J){let Q=bz(WX($),WX(J));return Q===""||!Q.startsWith("..")&&!Ez(Q)}var kz=32,L2=new Map;function Iz($,J){if(!L2.has($)&&L2.size>=kz){let Q=L2.keys().next().value;if(Q)L2.delete(Q)}L2.set($,J)}async function xz($){let J=await Promise.all($.pluginPaths.map(async(Q)=>{try{let Z=await yz(Q);return`${Q}:${Z.mtimeMs}:${Z.size}`}catch{return`${Q}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:J})}function jX($,J){return $.map((Q)=>({...Q,enabled:!J.has(Q.name)}))}function gz($){return $.sort((J,Q)=>{let Z=J.name.localeCompare(Q.name);if(Z!==0)return Z;return J.path.localeCompare(Q.path)})}async function mz($,J){if(!$.setup)return{tools:[]};let Q=[],Z={registerTool:(W)=>Q.push(W),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(W)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Z,{workspaceInfo:J}),{tools:Q}}async function fX($){let J=n2({workspacePath:$.workspacePath,cwd:$.cwd}),Q=H1($.disabledToolNames);if(J.length===0)return{tools:[],failures:[],warnings:[]};let Z=await xz({pluginPaths:J,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),W=L2.get(Z);if(W)return{tools:jX(W.tools,Q),failures:W.failures,warnings:W.warnings};let j=[],f=[],X=[],Y;try{Y=await W2({pluginPaths:J,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),f=[...Y.failures],X=[...Y.warnings];for(let H of Y.extensions??[]){let B=H.__clinePluginPath;if(!B)continue;let A=hz($.workspacePath,B)?"workspace-plugin":"global-plugin",K;try{K=await mz(H,{rootPath:$.workspacePath})}catch(G){f.push({pluginPath:B,pluginName:H.name,phase:"setup",message:G instanceof Error?G.message:String(G),stack:G instanceof Error?G.stack:void 0});continue}for(let G of K.tools)j.push({name:G.name,pluginName:H.name,path:B,source:A,description:G.description?.trim()||void 0})}}catch(H){f=J.map((B)=>({pluginPath:B,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await Y?.shutdown().catch(()=>{})}let V=gz(j);return Iz(Z,{tools:V,failures:f,warnings:X}),{tools:jX(V,Q),failures:f,warnings:X}}async function L9($){return(await fX($)).tools}function g6($,J){if(!J)return"global";let Q=cz(J,$);return!Q.startsWith("..")&&!vz(Q)?"workspace":"global"}function z8($){return[...$].sort((J,Q)=>{let Z=(W)=>{switch(W){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(J.source!==Q.source)return Z(J.source)-Z(Q.source);return J.name.localeCompare(Q.name)})}function VX($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function YX($,J){if($.userInstructionService)return await J($.userInstructionService);let Q=VX($);if(!Q)return await J(void 0);let Z=$.cwd?.trim()||Q,W=U2({skills:{workspacePath:Q,includePluginSkills:!0,cwd:Z},rules:{workspacePath:Q},workflows:{workspacePath:Q}});try{return await W.start(),await J(W)}finally{W.stop()}}function uz($,J){if(!$)return;let Q=$.listRecords("skill");if(J.id){let Z=Q.find((W)=>W.id===J.id);if(Z)return Z}for(let Z of Q)if(Z.filePath===J.path||Z.item.name===J.name||Z.id===J.name)return Z;return}class _2{async list($={}){return await YX($,async(J)=>{let Q=VX($),Z=[],W=[],j=[],f=[],X=[];if(J){for(let V of J.listRecords("workflow")){let H=V.item;Z.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"workflow",source:g6(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("rule")){let H=V.item;W.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"rule",source:g6(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("skill")){let H=V.item;j.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"skill",source:g6(V.filePath,Q),description:H.description,toggleable:!0})}}if(Q)try{for(let V of await L9({workspacePath:Q,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))f.push({id:`${V.pluginName}:${V.name}:${V.path}`,name:V.name,path:V.path,enabled:V.enabled,kind:"tool",source:V.source,description:V.description,toggleable:!0})}catch{}let Y=H0();if(L$({filePath:Y}))try{for(let V of m1({filePath:Y}))X.push({id:V.name,name:V.name,path:Y,enabled:V.disabled!==!0,kind:"mcp",source:g6(Y,Q),description:V.transport.type,toggleable:!0})}catch{}return{workflows:z8(Z.filter((V)=>x6(V.path))),rules:z8(W.filter((V)=>x6(V.path))),skills:z8(j.filter((V)=>x6(V.path))),tools:z8(f),mcp:z8(X.filter((V)=>x6(V.path)))}})}async toggle($){if($.type==="skills")return await YX($,async(J)=>{let Q=uz(J,$),Z=Q?.filePath;if(!Z)throw Error(`Unable to resolve skill setting '${$.id??$.name??XX($.path??"")}'.`);let W=Q?.item&&"disabled"in Q.item?Q.item.disabled!==!0:void 0,j=$.enabled??(W!==void 0?!W:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??XX($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await kf({filePath:Z,enabled:j}),await J?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:J}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)ZQ($.name);else G3($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let J=$.name?.trim()||$.id?.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=$.path?.trim()||H0(),Z=$.enabled;if(Z===void 0){let W=m1({filePath:Q}).find((j)=>j.name===J);if(!W)throw Error(`Unknown MCP server: ${J}`);Z=W.disabled===!0}return G8({filePath:Q,name:J,disabled:!Z}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function L8(){return new _2}function HX($){return{async list(J){let Q=$;if(Q.listSettings)return await Q.listSettings(J);return await L8().list(J)},async toggle(J){let Q=$;if(Q.toggleSetting)return await Q.toggleSetting(J);return await L8().toggle(J)}}}function BX($){function J(){let Q=$.pendingPrompts;if(!Q)throw Error("Pending prompt service is not available.");return Q}return{list(Q){return J().list(Q)},update(Q){return J().update(Q)},delete(Q){return J().delete(Q)}}}function L0(...$){let J,Q;for(let W of $){if(!W)continue;if(W.toolExecutors)J={...J??{},...W.toolExecutors};if(W.requestToolApproval)Q=W.requestToolApproval}let Z=J&&Object.keys(J).length>0;if(!Z&&!Q)return;return{...Z?{toolExecutors:J}:{},...Q?{requestToolApproval:Q}:{}}}var _8="session_not_found";class _$ extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function O$($){return $ instanceof _$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function _9($){let{hooks:J,logger:Q,telemetry:Z,extensionContext:W,extraTools:j,extensions:f,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:H,...B}=$,A={};if(J)A.hooks=J;if(Q)A.logger=Q;if(Z)A.telemetry=Z;if(W)A.extensionContext=W;if(j)A.extraTools=j;if(f)A.extensions=f;if(X)A.onTeamEvent=X;if(Y)A.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)A.checkpoint=V;if(H?.compact)A.compaction=H;let K=Object.keys(A).length>0?A:void 0;return{config:{...B,...V?{checkpoint:{enabled:V.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...K?{localRuntime:K}:{}}}function AX($){let J=$.config;return"providerId"in J?{...$,config:{...J,...dz($.localRuntime)},localRuntime:$.localRuntime}:$}function O9($,J={}){let Q=_9($.config),Z=L0(J.defaultCapabilities,$.capabilities),W=lz(Q.localRuntime,$.localRuntime),j=J.withExtensionContext?.(W?.extensionContext);if(j)W={...W??{},extensionContext:j};return{...$,...Q,...W?{localRuntime:W}:{},...Z?{capabilities:Z}:{}}}function dz($){if(!$)return{};let{modelCatalogDefaults:J,userInstructionService:Q,configExtensions:Z,onTeamRestored:W,...j}=$;return j}function lz(...$){let J={};for(let Q of $)if(Q)Object.assign(J,Q);return Object.keys(J).length>0?J:void 0}F0();function KX($){let J=$.input.config.telemetry??$.telemetry;if(!J)return;J.capture({event:k.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??z0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function O8($){return!!$&&typeof $==="object"&&!Array.isArray($)}function T9($){let J=$?.trim();return J?J:void 0}function pz($,J){let Q=$?.trim();if(!Q)return J;let Z=Date.parse(Q);if(!Number.isFinite(Z))return J;return new Date(Z).toISOString()}function GX($,J){return new Date(new Date($).getTime()+Math.max(0,Math.floor(J))*1000).toISOString()}function FX($,J){return new Date(new Date($).getTime()-Math.max(0,Math.floor(J))*1000).toISOString()}function rz($,J){if(!$)return J;return new Date($).getTime()>=new Date(J).getTime()?$:J}function iz($,J){let Q=$.eventId.trim(),Z=$.eventType.trim(),W=$.source.trim(),j=T9($.subject),f=T9($.dedupeKey)??`${Z}:${W}:${j??Q}`;return{eventId:Q,eventType:Z,source:W,subject:j,occurredAt:pz($.occurredAt,J),workspaceRoot:T9($.workspaceRoot),payload:O8($.payload)?$.payload:void 0,attributes:O8($.attributes)?$.attributes:void 0,dedupeKey:f}}function M9($,J){if(!J)return;let Q=J.split("."),Z=$;for(let W of Q){if(!O8(Z))return;Z=Z[W]}return Z}function nz($,J){if($.attributes&&Object.hasOwn($.attributes,J))return $.attributes[J];if($.payload&&Object.hasOwn($.payload,J))return $.payload[J];let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Z=M9(Q,J);if(Z!==void 0)return Z;if($.attributes){let W=M9($.attributes,J);if(W!==void 0)return W}if($.payload)return M9($.payload,J);return}function m6($,J){if(Array.isArray(J))return J.some((Q)=>m6($,Q));if(Array.isArray($))return $.some((Q)=>m6(Q,J));if(O8(J)){if(!O8($))return!1;return Object.entries(J).every(([Q,Z])=>m6($[Q],Z))}return Object.is($,J)}function az($,J){if(!J||Object.keys(J).length===0)return!0;return Object.entries(J).every(([Q,Z])=>m6(nz($,Q),Z))}class q9{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let J=new Date(this.nowFn()).toISOString(),Q=iz($,J),Z=this.store.insertEventLog(Q,{receivedAtIso:J});if(!Z.created)return this.logger?.debug("cron.event.duplicate",{eventId:Z.record.eventId,eventType:Z.record.eventType,source:Z.record.source}),{event:Z.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Z.record.dedupeKey}]};try{let W=this.store.listEventSpecsForType(Q.eventType),j=[],f=[],X=[];for(let H of W){if(!az(Q,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Q.dedupeKey});continue}f.push(H);let B=this.materializeForSpec(H,Q,Z.record.receivedAt);if(B.run)X.push(B.run);else j.push({specId:H.specId,externalId:H.externalId,reason:B.reason,dedupeKey:Q.dedupeKey})}let Y=f.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Z.record.eventId,{status:Y,matchedSpecCount:f.length,queuedRunCount:X.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let V=this.store.getEventLog(Z.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Z.record.eventId,eventType:Z.record.eventType,status:Y,matchedSpecCount:f.length,queuedRunCount:X.length}),{event:V??Z.record,duplicate:!1,matchedSpecs:f,queuedRuns:X,suppressions:j}}catch(W){if(this.store.updateEventLogProcessing(Z.record.eventId,{status:"failed",error:W instanceof Error?W.message:String(W)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Z.record.eventId,eventType:Z.record.eventType,error:W});throw W}}materializeForSpec($,J,Q){let Z=J.dedupeKey??J.eventId,W=$.debounceSeconds??0;if(W>0){let Y=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Z});if(Y){let V=rz(Y.scheduledFor,GX(Q,W)),H=this.store.updateQueuedEventRunForDebounce({runId:Y.runId,triggerEventId:J.eventId,scheduledFor:V});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Z,sinceIso:FX(Q,j)}))return{reason:"dedupe_window"};let f=$.cooldownSeconds??0;if(f>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:FX(Q,f)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:J.eventId,scheduledFor:W>0?GX(Q,W):Q}),reason:"dedupe_window"}}}class T8{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},J=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Z of J)if(this.materializeOneOff(Z))$.oneOffQueued+=1;let Q=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Z of Q)try{if(this.materializeSchedule(Z))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as jL}from"node:path";import{buildClineSystemPrompt as fL}from"@cline/shared";import{nowIso as zX}from"@cline/shared/db";import{basename as sz,resolve as oz}from"node:path";import{performance as DX}from"node:perf_hooks";import{processWorkspaceInfo as UX}from"@cline/shared";import tz from"simple-git";function T$($){return oz($)}async function c6($){return(await P9($)).info}function v6($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function P9($){let J=T$($),Q={rootPath:J,hint:sz(J)},Z;try{let W=tz({baseDir:J});if(!await W.checkIsRepo())return{info:Q,vcsType:"none"};try{let f=await W.getRemotes(!0);if(f.length>0){let X=f.map((Y)=>{let V=Y.refs.fetch||Y.refs.push;return`${Y.name}: ${V}`});Q.associatedRemoteUrls=X}}catch(f){Z??=v6(f)}try{let f=(await W.revparse(["HEAD"])).trim();if(f.length>0)Q.latestGitCommitHash=f}catch(f){Z??=v6(f)}try{let f=(await W.branch()).current.trim();if(f.length>0)Q.latestGitBranchName=f}catch(f){Z??=v6(f)}return{info:Q,vcsType:"git",error:Z}}catch(W){return{info:Q,vcsType:"none",error:v6(W)}}}async function N9($){let J=await c6($);return UX(J)}async function RX($){let J=DX.now(),Q=await P9($),Z=DX.now()-J,W=Q.info;return{workspaceInfo:W,workspaceMetadata:UX(W),durationMs:Z,vcsType:Q.vcsType,initError:Q.error}}import{mkdirSync as ez,writeFileSync as $L}from"node:fs";import{join as JL}from"node:path";import{resolveCronReportsDir as QL}from"@cline/shared/storage";function v1($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function M$($,J){if(J===void 0||J===null)return;return`${$}: ${v1(J)}`}function ZL($,J,Q){let Z=[`runId: ${v1($.runId)}`,`specId: ${v1(J.specId)}`,`externalId: ${v1(J.externalId)}`,`title: ${v1(J.title)}`,`triggerKind: ${v1($.triggerKind)}`,`status: ${v1($.status)}`,`sourcePath: ${v1(J.sourcePath)}`],W=[M$("sessionId",$.sessionId),M$("startedAt",$.startedAt),M$("completedAt",$.completedAt),M$("triggerEventId",$.triggerEventId),M$("triggerEventType",Q?.eventType),M$("triggerEventSource",Q?.source),M$("triggerEventSubject",Q?.subject)];for(let j of W)if(j)Z.push(j);return`---
173
173
  ${Z.join(`
174
174
  `)}
175
175
  ---
176
- `}function ZL($){let J=[];if($.triggerEvent){let Q=$.triggerEvent,Z=[`- eventId: ${Q.eventId}`,`- eventType: ${Q.eventType}`,`- source: ${Q.source}`,Q.subject?`- subject: ${Q.subject}`:"",`- occurredAt: ${Q.occurredAt}`,Q.dedupeKey?`- dedupeKey: ${Q.dedupeKey}`:"",Q.attributes?`- attributes: ${JSON.stringify(Q.attributes)}`:""].filter((W)=>W.length>0);J.push(`## Trigger Event
176
+ `}function WL($){let J=[];if($.triggerEvent){let Q=$.triggerEvent,Z=[`- eventId: ${Q.eventId}`,`- eventType: ${Q.eventType}`,`- source: ${Q.source}`,Q.subject?`- subject: ${Q.subject}`:"",`- occurredAt: ${Q.occurredAt}`,Q.dedupeKey?`- dedupeKey: ${Q.dedupeKey}`:"",Q.attributes?`- attributes: ${JSON.stringify(Q.attributes)}`:""].filter((W)=>W.length>0);J.push(`## Trigger Event
177
177
 
178
178
  ${Z.join(`
179
179
  `)}
@@ -192,17 +192,17 @@ ${Z.join(`
192
192
  ${Q.join(`
193
193
  `)}
194
194
  `)}return J.join(`
195
- `)}function w9($){let J=JL($.specs);tz(J,{recursive:!0});let Q=$L(J,`${$.run.runId}.md`),Z=`${QL($.run,$.spec,$.data.triggerEvent)}
196
- ${ZL($.data)}`;return ez(Q,Z,"utf8"),Q}class S9{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,J,Q){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Z=Math.max(1,Math.floor(Q)),W=this.activeExecutions.get($)??new Set;if(W.size>=Z)return!1;return W.add(J),this.activeExecutions.set($,W),!0}release($,J){let Q=this.activeExecutions.get($);if(!Q)return;if(Q.delete(J),Q.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let J of this.activeExecutions.values())$+=J.size;return $}}var fL=15000,XL=90,RX=["rules","skills","plugins"];function YL($,J){return new Set($.extensions??RX).has(J)}function VL($,J){if($.tools===void 0)return{"*":{autoApprove:!0}};let Q={"*":{enabled:!1,autoApprove:!0}};for(let Z of $.tools)Q[Z]={enabled:!0,autoApprove:!0};if(J==="yolo")Q[D0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Q}function HL($){let J=$?.trim();if(!J)return;return["# Notes Directory",`Use ${J} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
197
- `)}class C9 extends Error{constructor($){super($);this.name="TimeoutError"}}async function BL($,J){if(J<=0)return $;let Q,Z=new Promise((W,j)=>{Q=setTimeout(()=>{j(new C9("cron run timed out"))},J)});try{return await Promise.race([$,Z])}finally{if(Q)clearTimeout(Q)}}class M8{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 S9($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??XL)*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??fL);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let J=[...this.activeRuns.entries()];await Promise.all(J.map(async([Q,Z])=>{if(Z.sessionId)try{await this.options.runtimeHandlers.abortSession(Z.sessionId)}catch{}try{this.store.requeueRun({runId:Q,claimToken:Z.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:UX(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((J)=>this.executeClaim(J)))}catch($){let J=this.options.logger;if(J)if(J.error)J.error("cron.runner.tick.failed",{error:$});else J.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,J])=>{let Q=this.store.getRun($);return Q?[{...Q,...J}]:[]})}async executeClaim($){let J=$.run,Q=this.store.getSpec(J.specId);if(!Q){this.store.completeRun(J.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Q.enabled||Q.removed){this.store.completeRun(J.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Z=Q.maxParallel&&Q.maxParallel>0?Q.maxParallel:1;if(!this.limiter.acquire(Q.specId,J.runId,Z)){this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Q.specId,J.runId),this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(J.runId,{claimToken:$.claimToken});let j=J.triggerEventId?this.store.getEventLog(J.triggerEventId):void 0,f,X,Y=Date.now(),V;if(Q.timeoutSeconds&&Q.timeoutSeconds>0)V=Y+Q.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Q);if(f=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!f)throw Error("runtime returned empty sessionId");this.activeRuns.set(J.runId,{claimToken:$.claimToken,sessionId:f}),this.store.attachSessionIdToRun(J.runId,f);let A={config:H,prompt:this.buildPrompt(Q,j)},K=this.options.runtimeHandlers.sendSession(f,A),G=V?Math.max(1,V-Date.now()):0,D=(await BL(K,G)).result,U=Date.now(),F=w9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"done"},spec:Q,data:{finalText:D.text,usage:D.usage,toolCalls:D.toolCalls,durationMs:U-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"done",sessionId:f,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Q,J.runId),this.store.updateSpecLastRunAt(Q.specId,UX())}catch(H){let B=H instanceof C9;if(f&&B)try{await this.options.runtimeHandlers.abortSession(f)}catch{}let A=H instanceof Error?H.message:String(H),K=Date.now(),G=w9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"failed"},spec:Q,data:{error:A,durationMs:K-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"failed",sessionId:f,reportPath:G,error:A,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Q,J.runId)}finally{if(X?.(),f)try{await this.options.runtimeHandlers.stopSession(f)}catch{}this.activeRuns.delete(J.runId),this.limiter.release(Q.specId,J.runId)}}publishScheduleExecutionEvent($,J,Q){if(J.source!=="hub-schedule"||!this.options.eventPublisher)return;let Z=this.store.getRun(Q);if(!Z)return;let W=Z.status==="done"?"success":Z.status==="cancelled"?"aborted":Z.status==="running"?"running":Z.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:J.externalId,executionId:Z.runId,sessionId:Z.sessionId,triggeredAt:new Date(Z.scheduledFor??Z.createdAt).getTime(),startedAt:Z.startedAt?new Date(Z.startedAt).getTime():void 0,endedAt:Z.completedAt?new Date(Z.completedAt).getTime():void 0,status:W,errorMessage:Z.error})}buildPrompt($,J){let Q=$.prompt??"";if(!J)return Q;let Z={eventId:J.eventId,eventType:J.eventType,source:J.source,subject:J.subject,occurredAt:J.occurredAt,workspaceRoot:J.workspaceRoot,dedupeKey:J.dedupeKey,attributes:J.attributes,payload:J.payload};return`${Q}
195
+ `)}function w9($){let J=QL($.specs);ez(J,{recursive:!0});let Q=JL(J,`${$.run.runId}.md`),Z=`${ZL($.run,$.spec,$.data.triggerEvent)}
196
+ ${WL($.data)}`;return $L(Q,Z,"utf8"),Q}class S9{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,J,Q){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Z=Math.max(1,Math.floor(Q)),W=this.activeExecutions.get($)??new Set;if(W.size>=Z)return!1;return W.add(J),this.activeExecutions.set($,W),!0}release($,J){let Q=this.activeExecutions.get($);if(!Q)return;if(Q.delete(J),Q.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let J of this.activeExecutions.values())$+=J.size;return $}}var XL=15000,YL=90,LX=["rules","skills","plugins"];function VL($,J){return new Set($.extensions??LX).has(J)}function HL($,J){if($.tools===void 0)return{"*":{autoApprove:!0}};let Q={"*":{enabled:!1,autoApprove:!0}};for(let Z of $.tools)Q[Z]={enabled:!0,autoApprove:!0};if(J==="yolo")Q[D0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Q}function BL($){let J=$?.trim();if(!J)return;return["# Notes Directory",`Use ${J} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
197
+ `)}class C9 extends Error{constructor($){super($);this.name="TimeoutError"}}async function AL($,J){if(J<=0)return $;let Q,Z=new Promise((W,j)=>{Q=setTimeout(()=>{j(new C9("cron run timed out"))},J)});try{return await Promise.race([$,Z])}finally{if(Q)clearTimeout(Q)}}class M8{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 S9($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??YL)*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??XL);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let J=[...this.activeRuns.entries()];await Promise.all(J.map(async([Q,Z])=>{if(Z.sessionId)try{await this.options.runtimeHandlers.abortSession(Z.sessionId)}catch{}try{this.store.requeueRun({runId:Q,claimToken:Z.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:zX(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((J)=>this.executeClaim(J)))}catch($){let J=this.options.logger;if(J)if(J.error)J.error("cron.runner.tick.failed",{error:$});else J.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,J])=>{let Q=this.store.getRun($);return Q?[{...Q,...J}]:[]})}async executeClaim($){let J=$.run,Q=this.store.getSpec(J.specId);if(!Q){this.store.completeRun(J.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Q.enabled||Q.removed){this.store.completeRun(J.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Z=Q.maxParallel&&Q.maxParallel>0?Q.maxParallel:1;if(!this.limiter.acquire(Q.specId,J.runId,Z)){this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Q.specId,J.runId),this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(J.runId,{claimToken:$.claimToken});let j=J.triggerEventId?this.store.getEventLog(J.triggerEventId):void 0,f,X,Y=Date.now(),V;if(Q.timeoutSeconds&&Q.timeoutSeconds>0)V=Y+Q.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Q);if(f=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!f)throw Error("runtime returned empty sessionId");this.activeRuns.set(J.runId,{claimToken:$.claimToken,sessionId:f}),this.store.attachSessionIdToRun(J.runId,f);let A={config:H,prompt:this.buildPrompt(Q,j)},K=this.options.runtimeHandlers.sendSession(f,A),G=V?Math.max(1,V-Date.now()):0,D=(await AL(K,G)).result,U=Date.now(),F=w9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"done"},spec:Q,data:{finalText:D.text,usage:D.usage,toolCalls:D.toolCalls,durationMs:U-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"done",sessionId:f,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Q,J.runId),this.store.updateSpecLastRunAt(Q.specId,zX())}catch(H){let B=H instanceof C9;if(f&&B)try{await this.options.runtimeHandlers.abortSession(f)}catch{}let A=H instanceof Error?H.message:String(H),K=Date.now(),G=w9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"failed"},spec:Q,data:{error:A,durationMs:K-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"failed",sessionId:f,reportPath:G,error:A,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Q,J.runId)}finally{if(X?.(),f)try{await this.options.runtimeHandlers.stopSession(f)}catch{}this.activeRuns.delete(J.runId),this.limiter.release(Q.specId,J.runId)}}publishScheduleExecutionEvent($,J,Q){if(J.source!=="hub-schedule"||!this.options.eventPublisher)return;let Z=this.store.getRun(Q);if(!Z)return;let W=Z.status==="done"?"success":Z.status==="cancelled"?"aborted":Z.status==="running"?"running":Z.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:J.externalId,executionId:Z.runId,sessionId:Z.sessionId,triggeredAt:new Date(Z.scheduledFor??Z.createdAt).getTime(),startedAt:Z.startedAt?new Date(Z.startedAt).getTime():void 0,endedAt:Z.completedAt?new Date(Z.completedAt).getTime():void 0,status:W,errorMessage:Z.error})}buildPrompt($,J){let Q=$.prompt??"";if(!J)return Q;let Z={eventId:J.eventId,eventType:J.eventType,source:J.source,subject:J.subject,occurredAt:J.occurredAt,workspaceRoot:J.workspaceRoot,dedupeKey:J.dedupeKey,attributes:J.attributes,payload:J.payload};return`${Q}
198
198
 
199
199
  Trigger event:
200
- ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Q=setInterval(()=>{let Z=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Z))clearInterval(Q)},J);return()=>clearInterval(Q)}async buildSystemPrompt($,J,Q,Z){let W=HL($.notesDirectory),j=J6(void 0,W),f=await N9(J),X=jL({ide:"Cline Cron",workspaceRoot:J,workspaceName:WL(J),metadata:f,rules:$.systemPrompt?void 0:j,mode:Q,providerId:Z,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?J6(X,j)??X:X}async buildStartRequest($){let J=($.workspaceRoot??"").trim(),Q=($.providerId??"").trim(),Z=($.modelId??"").trim(),W=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():J;if(!J)throw Error("cron spec requires workspaceRoot");let f=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:J,cwd:j,provider:Q,model:Z,mode:f,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,J,f,Q),maxIterations:$.maxIterations,enableTools:W?.enableTools??!0,enableSpawn:W?.enableSpawn??!0,enableTeams:W?.enableTeams??!0,autoApproveTools:W?.autoApproveTools??!0,toolPolicies:VL($,f),configExtensions:RX.filter((X)=>YL($,X))}}}import{existsSync as hL,readdirSync as kL,readFileSync as IL,statSync as xL}from"node:fs";import{relative as gL}from"node:path";import{resolveCronSpecsDir as mL}from"@cline/shared/storage";function q8($,J,Q,Z){let W=new Set;function j(f){let X=f.toLowerCase();if(Z){let V=Z.indexOf(X);if(V!==-1)return V+J}let Y=Number(f);if(!Number.isInteger(Y)||Y<J||Y>Q)throw Error(`Invalid cron value "${f}" for range [${J}-${Q}]`);return Y}for(let f of $.split(",")){if(f==="*"){for(let V=J;V<=Q;V+=1)W.add(V);continue}let X=f.indexOf("/");if(X!==-1){let V=f.slice(0,X),H=Number(f.slice(X+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${f.slice(X+1)}"`);let B=J,A=Q;if(V!=="*"){let K=V.indexOf("-");if(K!==-1)B=j(V.slice(0,K)),A=j(V.slice(K+1));else B=j(V)}if(B>A)throw Error(`Invalid cron range "${V}"`);for(let K=B;K<=A;K+=H)W.add(K);continue}let Y=f.indexOf("-");if(Y!==-1){let V=j(f.slice(0,Y)),H=j(f.slice(Y+1));if(V>H)throw Error(`Invalid cron range "${f}"`);for(let B=V;B<=H;B+=1)W.add(B);continue}W.add(j(f))}return[...W].sort((f,X)=>f-X)}var AL=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],LX=["sun","mon","tue","wed","thu","fri","sat"];function P8($,J,Q){let Z=$[J];if(typeof Z!=="string")throw Error(`Invalid cron pattern "${Q}": missing field ${J+1}`);return Z}function y9($,J){let Q=$[0];if(typeof Q!=="number")throw Error(`Invalid cron pattern: no values parsed for ${J}`);return Q}function E9($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${J.length}`);return{minutes:q8(P8(J,0,$),0,59),hours:q8(P8(J,1,$),0,23),daysOfMonth:q8(P8(J,2,$),1,31),months:q8(P8(J,3,$),1,12,AL),daysOfWeek:q8(P8(J,4,$),0,6,LX)}}function b9($){E9($)}function _X($,J,Q=Date.now()){q$($,Q,J)}var zX=new Map,KL=new Map(LX.map(($,J)=>[$,J]));function OX($){let J=$?.trim();return J?J:void 0}function TX($){let J=zX.get($);if(J)return J;let Q=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return zX.set($,Q),Q}function GL($){let J=OX($);if(!J)return;TX(J).format(new Date)}function FL($,J){let Q=TX(J).formatToParts(new Date($)),Z=new Map(Q.map((f)=>[f.type,f.value])),W=Z.get("weekday")?.toLowerCase().slice(0,3)??"",j=KL.get(W);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${J}"`);return{month:Number(Z.get("month")),dayOfMonth:Number(Z.get("day")),dayOfWeek:j,hour:Number(Z.get("hour")),minute:Number(Z.get("minute"))}}function DL($){let J=new Date($);return{month:J.getMonth()+1,dayOfMonth:J.getDate(),dayOfWeek:J.getDay(),hour:J.getHours(),minute:J.getMinutes()}}function UL($,J){return $.months.includes(J.month)&&$.daysOfMonth.includes(J.dayOfMonth)&&$.daysOfWeek.includes(J.dayOfWeek)&&$.hours.includes(J.hour)&&$.minutes.includes(J.minute)}function RL($,J,Q){let Z=E9($),W=new Date(J);W.setSeconds(0,0);let j=W.getTime()+60000,f=new Date(J);f.setFullYear(f.getFullYear()+4);let X=f.getTime();while(j<=X){if(UL(Z,FL(j,Q)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Q}"`)}function q$($,J,Q){let Z=OX(Q);if(Z)return GL(Z),RL($,J,Z);let W=E9($),j=new Date(J);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let f=new Date(J);f.setFullYear(f.getFullYear()+4);while(j<=f){let{month:X,dayOfMonth:Y,dayOfWeek:V,hour:H,minute:B}=DL(j.getTime());if(!W.months.includes(X)){let A=W.months.find((G)=>G>X)??y9(W.months,"months"),K=A<=X?1:0;j=new Date(j.getFullYear()+K,A-1,1,0,0,0,0);continue}if(!W.daysOfMonth.includes(Y)||!W.daysOfWeek.includes(V)){j=new Date(j.getFullYear(),j.getMonth(),Y+1,0,0,0,0);continue}if(!W.hours.includes(H)){let A=W.hours.find((G)=>G>H)??y9(W.hours,"hours"),K=A<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+K,A,0,0,0);continue}if(!W.minutes.includes(B)){let A=W.minutes.find((G)=>G>B)??y9(W.minutes,"minutes"),K=A<=B?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+K,A,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as zL}from"node:crypto";import LL from"yaml";function _L($){let J=$.replace(/\\/g,"/");if(J.startsWith("events/")&&J.endsWith(".event.md"))return"event";if(J.endsWith(".cron.md"))return"schedule";return"one_off"}function OL($){let J=$.replace(/\r\n/g,`
200
+ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Q=setInterval(()=>{let Z=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Z))clearInterval(Q)},J);return()=>clearInterval(Q)}async buildSystemPrompt($,J,Q,Z){let W=BL($.notesDirectory),j=J6(void 0,W),f=await N9(J),X=fL({ide:"Cline Cron",workspaceRoot:J,workspaceName:jL(J),metadata:f,rules:$.systemPrompt?void 0:j,mode:Q,providerId:Z,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?J6(X,j)??X:X}async buildStartRequest($){let J=($.workspaceRoot??"").trim(),Q=($.providerId??"").trim(),Z=($.modelId??"").trim(),W=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():J;if(!J)throw Error("cron spec requires workspaceRoot");let f=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:J,cwd:j,provider:Q,model:Z,mode:f,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,J,f,Q),maxIterations:$.maxIterations,enableTools:W?.enableTools??!0,enableSpawn:W?.enableSpawn??!0,enableTeams:W?.enableTeams??!0,autoApproveTools:W?.autoApproveTools??!0,toolPolicies:HL($,f),configExtensions:LX.filter((X)=>VL($,X))}}}import{existsSync as kL,readdirSync as IL,readFileSync as xL,statSync as gL}from"node:fs";import{relative as mL}from"node:path";import{resolveCronSpecsDir as vL}from"@cline/shared/storage";function q8($,J,Q,Z){let W=new Set;function j(f){let X=f.toLowerCase();if(Z){let V=Z.indexOf(X);if(V!==-1)return V+J}let Y=Number(f);if(!Number.isInteger(Y)||Y<J||Y>Q)throw Error(`Invalid cron value "${f}" for range [${J}-${Q}]`);return Y}for(let f of $.split(",")){if(f==="*"){for(let V=J;V<=Q;V+=1)W.add(V);continue}let X=f.indexOf("/");if(X!==-1){let V=f.slice(0,X),H=Number(f.slice(X+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${f.slice(X+1)}"`);let B=J,A=Q;if(V!=="*"){let K=V.indexOf("-");if(K!==-1)B=j(V.slice(0,K)),A=j(V.slice(K+1));else B=j(V)}if(B>A)throw Error(`Invalid cron range "${V}"`);for(let K=B;K<=A;K+=H)W.add(K);continue}let Y=f.indexOf("-");if(Y!==-1){let V=j(f.slice(0,Y)),H=j(f.slice(Y+1));if(V>H)throw Error(`Invalid cron range "${f}"`);for(let B=V;B<=H;B+=1)W.add(B);continue}W.add(j(f))}return[...W].sort((f,X)=>f-X)}var KL=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],OX=["sun","mon","tue","wed","thu","fri","sat"];function P8($,J,Q){let Z=$[J];if(typeof Z!=="string")throw Error(`Invalid cron pattern "${Q}": missing field ${J+1}`);return Z}function y9($,J){let Q=$[0];if(typeof Q!=="number")throw Error(`Invalid cron pattern: no values parsed for ${J}`);return Q}function E9($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${J.length}`);return{minutes:q8(P8(J,0,$),0,59),hours:q8(P8(J,1,$),0,23),daysOfMonth:q8(P8(J,2,$),1,31),months:q8(P8(J,3,$),1,12,KL),daysOfWeek:q8(P8(J,4,$),0,6,OX)}}function b9($){E9($)}function TX($,J,Q=Date.now()){q$($,Q,J)}var _X=new Map,GL=new Map(OX.map(($,J)=>[$,J]));function MX($){let J=$?.trim();return J?J:void 0}function qX($){let J=_X.get($);if(J)return J;let Q=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return _X.set($,Q),Q}function FL($){let J=MX($);if(!J)return;qX(J).format(new Date)}function DL($,J){let Q=qX(J).formatToParts(new Date($)),Z=new Map(Q.map((f)=>[f.type,f.value])),W=Z.get("weekday")?.toLowerCase().slice(0,3)??"",j=GL.get(W);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${J}"`);return{month:Number(Z.get("month")),dayOfMonth:Number(Z.get("day")),dayOfWeek:j,hour:Number(Z.get("hour")),minute:Number(Z.get("minute"))}}function UL($){let J=new Date($);return{month:J.getMonth()+1,dayOfMonth:J.getDate(),dayOfWeek:J.getDay(),hour:J.getHours(),minute:J.getMinutes()}}function RL($,J){return $.months.includes(J.month)&&$.daysOfMonth.includes(J.dayOfMonth)&&$.daysOfWeek.includes(J.dayOfWeek)&&$.hours.includes(J.hour)&&$.minutes.includes(J.minute)}function zL($,J,Q){let Z=E9($),W=new Date(J);W.setSeconds(0,0);let j=W.getTime()+60000,f=new Date(J);f.setFullYear(f.getFullYear()+4);let X=f.getTime();while(j<=X){if(RL(Z,DL(j,Q)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Q}"`)}function q$($,J,Q){let Z=MX(Q);if(Z)return FL(Z),zL($,J,Z);let W=E9($),j=new Date(J);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let f=new Date(J);f.setFullYear(f.getFullYear()+4);while(j<=f){let{month:X,dayOfMonth:Y,dayOfWeek:V,hour:H,minute:B}=UL(j.getTime());if(!W.months.includes(X)){let A=W.months.find((G)=>G>X)??y9(W.months,"months"),K=A<=X?1:0;j=new Date(j.getFullYear()+K,A-1,1,0,0,0,0);continue}if(!W.daysOfMonth.includes(Y)||!W.daysOfWeek.includes(V)){j=new Date(j.getFullYear(),j.getMonth(),Y+1,0,0,0,0);continue}if(!W.hours.includes(H)){let A=W.hours.find((G)=>G>H)??y9(W.hours,"hours"),K=A<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+K,A,0,0,0);continue}if(!W.minutes.includes(B)){let A=W.minutes.find((G)=>G>B)??y9(W.minutes,"minutes"),K=A<=B?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+K,A,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as LL}from"node:crypto";import _L from"yaml";function OL($){let J=$.replace(/\\/g,"/");if(J.startsWith("events/")&&J.endsWith(".event.md"))return"event";if(J.endsWith(".cron.md"))return"schedule";return"one_off"}function TL($){let J=$.replace(/\r\n/g,`
201
201
  `);if(!J.startsWith(`---
202
202
  `))return{frontmatter:void 0,body:$};let Q=J.slice(4),Z=Q.indexOf(`
203
203
  ---`);if(Z===-1)return{frontmatter:void 0,body:$};let W=Q.slice(0,Z),j=Q.slice(Z+4);if(j.startsWith(`
204
- `))j=j.slice(1);return{frontmatter:W,body:j}}function k0($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function TL($){if(!Array.isArray($))return;let J=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);return J.length>0?J:void 0}function I9($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function ML($){let J=I9($);if(!J)return;let Q=k0(J.providerId),Z=k0(J.modelId);if(Q===void 0&&Z===void 0)return;return{providerId:Q,modelId:Z}}function qL($){if(typeof $!=="string")return;let J=$.trim().toLowerCase();if(J==="act"||J==="plan"||J==="yolo")return J;return}function qX($,J={}){let Q=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Q)return;let Z=[...new Set(Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0))];if(Array.isArray($)&&J.preserveEmptyArray)return Z;return Z.length>0?Z:void 0}var PL=new Set(X2);function NL($){let J=qX($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!PL.has(Z));if(Q.length>0)throw Error(`unknown tool(s): ${Q.join(", ")}`);return J}var wL=new Set(["rules","skills","plugins"]);function SL($){let J=qX($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!wL.has(Z));if(Q.length>0)throw Error(`unknown extension(s): ${Q.join(", ")}`);return J}function h9($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function k9($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function x9($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Q)=>x9(Q)).join(",")}]`;let J=Object.entries($).filter(([,Q])=>Q!==void 0);return J.sort(([Q],[Z])=>Q<Z?-1:Q>Z?1:0),`{${J.map(([Q,Z])=>`${JSON.stringify(Q)}:${x9(Z)}`).join(",")}}`}function PX($,J){let Q=zL("sha256");return Q.update(x9($)),Q.update(`
205
- `),Q.update(J),Q.digest("hex")}function CL($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var yL=["schedule","timezone"],EL=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],bL=["cwd"];function MX($,J,Q,Z,W){return{externalId:$,relativePath:$,triggerKind:J,body:Q,contentHash:PX(Z,Q),error:W}}function J1($,J,Q,Z,W,j){return{externalId:$,relativePath:J,triggerKind:Q,body:Z,contentHash:W,error:j}}function NX($){let J=$.relativePath.replace(/\\/g,"/"),Q=_L(J),{frontmatter:Z,body:W}=OL($.raw),j={};if(Z!==void 0&&Z.trim().length>0)try{let F=LL.parse(Z);if(F&&typeof F==="object"&&!Array.isArray(F))j=F;else if(F!==null&&F!==void 0)return MX(J,Q,W,{},"frontmatter must be a YAML mapping")}catch(F){return MX(J,Q,W,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let f=PX(j,W),X=k0(j.id),Y=X??J;if(Q!=="schedule"){for(let F of yL)if(j[F]!==void 0)return J1(Y,J,Q,W,f,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of bL)if(j[F]!==void 0)return J1(Y,J,Q,W,f,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Q!=="event"){for(let F of EL)if(j[F]!==void 0)return J1(Y,J,Q,W,f,`field "${F}" is only allowed on .event.md specs`)}let V=k0(j.prompt),H=W.trim(),B=V??(H.length>0?H:void 0);if(!B)return J1(Y,J,Q,W,f,"prompt is required (frontmatter `prompt` or markdown body)");let A=k0(j.workspaceRoot);if(!A)return J1(Y,J,Q,W,f,"workspaceRoot is required");let K,G;try{K=NL(j.tools),G=SL(j.extensions)}catch(F){return J1(Y,J,Q,W,f,F instanceof Error?F.message:String(F))}let R=qL(j.mode);if(j.mode!==void 0&&R===void 0)return J1(Y,J,Q,W,f,"mode must be one of: act, plan, yolo");let D={id:X,title:k0(j.title)??X??CL(J),prompt:B,workspaceRoot:A,mode:R??"yolo",systemPrompt:k0(j.systemPrompt),modelSelection:ML(j.modelSelection),maxIterations:h9(j.maxIterations),timeoutSeconds:h9(j.timeoutSeconds),tools:K,notesDirectory:k0(j.notesDirectory),extensions:G,source:k0(j.source)??"user",tags:TL(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:I9(j.metadata)},U;if(Q==="schedule"){let F=k0(j.schedule);if(!F)return J1(Y,J,Q,W,f,"schedule is required for *.cron.md specs");let O=k0(j.timezone);try{_X(F,O)}catch(L){return J1(Y,J,Q,W,f,L instanceof Error?L.message:String(L))}U={...D,triggerKind:"schedule",schedule:F,timezone:O}}else if(Q==="event"){let F=k0(j.event);if(!F)return J1(Y,J,Q,W,f,"event is required for .event.md specs");U={...D,triggerKind:"event",event:F,filters:I9(j.filters),debounceSeconds:k9(j.debounceSeconds),dedupeWindowSeconds:k9(j.dedupeWindowSeconds),cooldownSeconds:k9(j.cooldownSeconds),maxParallel:h9(j.maxParallel)}}else U={...D,triggerKind:"one_off"};return{externalId:Y,relativePath:J,triggerKind:Q,body:W,contentHash:f,spec:U}}function vL($,J){return gL($,J).replace(/\\/g,"/")}function cL($){if(!hL($))return[];let J=[],Q=[$];while(Q.length>0){let Z=Q.pop();if(!Z)continue;let W;try{W=kL(Z,{withFileTypes:!0})}catch{continue}for(let j of W){let f=`${Z}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Q.push(f);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;J.push(f)}}return J}class g9{store;cronDir;constructor($){this.store=$.store,this.cronDir=mL($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},J=cL(this.cronDir),Q=new Set;for(let W of J){let j=vL(this.cronDir,W);Q.add(j),$.scanned+=1;let f=await this.reconcileFile(j,W);if(f){if($.changes.push(f),$.upserted+=1,f.parse.error)$.invalidParses+=1}}let Z=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let W of Z)if(!Q.has(W.sourcePath))this.handleFileDeleted(W),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,J){let Q=this.store.getSpecBySourcePath($),Z,W;try{Z=IL(J,"utf8"),W=xL(J).mtimeMs}catch{return}let f=NX({relativePath:$,raw:Z}),X=this.store.upsertSpec({externalId:f.externalId,sourcePath:$,triggerKind:f.triggerKind,sourceMtimeMs:W,sourceHash:f.contentHash,parseStatus:f.error?"invalid":"valid",parseError:f.error,spec:f.spec});if(!f.error&&f.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!Q||Q.removed||!Q.enabled||Q.scheduleExpr!==X.record.scheduleExpr||Q.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:f}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let J of $)this.applyScheduleNextRunAt(J,{forceReset:!1})}applyScheduleNextRunAt($,J){if(!$.scheduleExpr)return;if(!J.forceReset&&$.nextRunAt)return;try{let Q=Date.now(),Z=$.lastRunAt?Math.max(Q,new Date($.lastRunAt).getTime()):Q,W=q$($.scheduleExpr,Z,$.timezone),j=new Date(W).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as uL,mkdirSync as dL,watch as lL}from"node:fs";import{relative as pL,resolve as rL}from"node:path";var iL=250;class m9{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??iL),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{dL($,{recursive:!0}),this.watcher=lL($,{recursive:!0},(J,Q)=>{if(!Q)return;let Z=String(Q).replace(/\\/g,"/");if(!Z.endsWith(".md"))return;if(Z.startsWith("reports/"))return;this.scheduleReconcile(Z)}),this.watcher.on("error",this.onError)}catch(J){this.onError(J)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let J=this.pending.get($);if(J)clearTimeout(J);let Q=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Q)}async reconcileNow($){try{let J=rL(this.reconciler.getCronDir(),$);if(!uL(J)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Q=pL(this.reconciler.getCronDir(),J).replace(/\\/g,"/");await this.reconciler.reconcileFile(Q,J),await this.onReconciled()}catch(J){this.onError(J)}}}import{randomUUID as N8}from"node:crypto";import{asOptionalString as h,asString as r,loadSqliteDb as aL,nowIso as B0}from"@cline/shared/db";import{resolveCronDbPath as sL}from"@cline/shared/storage";var nL=[`CREATE TABLE IF NOT EXISTS cron_specs (
204
+ `))j=j.slice(1);return{frontmatter:W,body:j}}function k0($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function ML($){if(!Array.isArray($))return;let J=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);return J.length>0?J:void 0}function I9($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function qL($){let J=I9($);if(!J)return;let Q=k0(J.providerId),Z=k0(J.modelId);if(Q===void 0&&Z===void 0)return;return{providerId:Q,modelId:Z}}function PL($){if(typeof $!=="string")return;let J=$.trim().toLowerCase();if(J==="act"||J==="plan"||J==="yolo")return J;return}function NX($,J={}){let Q=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Q)return;let Z=[...new Set(Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0))];if(Array.isArray($)&&J.preserveEmptyArray)return Z;return Z.length>0?Z:void 0}var NL=new Set(X2);function wL($){let J=NX($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!NL.has(Z));if(Q.length>0)throw Error(`unknown tool(s): ${Q.join(", ")}`);return J}var SL=new Set(["rules","skills","plugins"]);function CL($){let J=NX($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!SL.has(Z));if(Q.length>0)throw Error(`unknown extension(s): ${Q.join(", ")}`);return J}function h9($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function k9($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function x9($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Q)=>x9(Q)).join(",")}]`;let J=Object.entries($).filter(([,Q])=>Q!==void 0);return J.sort(([Q],[Z])=>Q<Z?-1:Q>Z?1:0),`{${J.map(([Q,Z])=>`${JSON.stringify(Q)}:${x9(Z)}`).join(",")}}`}function wX($,J){let Q=LL("sha256");return Q.update(x9($)),Q.update(`
205
+ `),Q.update(J),Q.digest("hex")}function yL($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var EL=["schedule","timezone"],bL=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],hL=["cwd"];function PX($,J,Q,Z,W){return{externalId:$,relativePath:$,triggerKind:J,body:Q,contentHash:wX(Z,Q),error:W}}function J1($,J,Q,Z,W,j){return{externalId:$,relativePath:J,triggerKind:Q,body:Z,contentHash:W,error:j}}function SX($){let J=$.relativePath.replace(/\\/g,"/"),Q=OL(J),{frontmatter:Z,body:W}=TL($.raw),j={};if(Z!==void 0&&Z.trim().length>0)try{let F=_L.parse(Z);if(F&&typeof F==="object"&&!Array.isArray(F))j=F;else if(F!==null&&F!==void 0)return PX(J,Q,W,{},"frontmatter must be a YAML mapping")}catch(F){return PX(J,Q,W,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let f=wX(j,W),X=k0(j.id),Y=X??J;if(Q!=="schedule"){for(let F of EL)if(j[F]!==void 0)return J1(Y,J,Q,W,f,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of hL)if(j[F]!==void 0)return J1(Y,J,Q,W,f,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Q!=="event"){for(let F of bL)if(j[F]!==void 0)return J1(Y,J,Q,W,f,`field "${F}" is only allowed on .event.md specs`)}let V=k0(j.prompt),H=W.trim(),B=V??(H.length>0?H:void 0);if(!B)return J1(Y,J,Q,W,f,"prompt is required (frontmatter `prompt` or markdown body)");let A=k0(j.workspaceRoot);if(!A)return J1(Y,J,Q,W,f,"workspaceRoot is required");let K,G;try{K=wL(j.tools),G=CL(j.extensions)}catch(F){return J1(Y,J,Q,W,f,F instanceof Error?F.message:String(F))}let R=PL(j.mode);if(j.mode!==void 0&&R===void 0)return J1(Y,J,Q,W,f,"mode must be one of: act, plan, yolo");let D={id:X,title:k0(j.title)??X??yL(J),prompt:B,workspaceRoot:A,mode:R??"yolo",systemPrompt:k0(j.systemPrompt),modelSelection:qL(j.modelSelection),maxIterations:h9(j.maxIterations),timeoutSeconds:h9(j.timeoutSeconds),tools:K,notesDirectory:k0(j.notesDirectory),extensions:G,source:k0(j.source)??"user",tags:ML(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:I9(j.metadata)},U;if(Q==="schedule"){let F=k0(j.schedule);if(!F)return J1(Y,J,Q,W,f,"schedule is required for *.cron.md specs");let O=k0(j.timezone);try{TX(F,O)}catch(L){return J1(Y,J,Q,W,f,L instanceof Error?L.message:String(L))}U={...D,triggerKind:"schedule",schedule:F,timezone:O}}else if(Q==="event"){let F=k0(j.event);if(!F)return J1(Y,J,Q,W,f,"event is required for .event.md specs");U={...D,triggerKind:"event",event:F,filters:I9(j.filters),debounceSeconds:k9(j.debounceSeconds),dedupeWindowSeconds:k9(j.dedupeWindowSeconds),cooldownSeconds:k9(j.cooldownSeconds),maxParallel:h9(j.maxParallel)}}else U={...D,triggerKind:"one_off"};return{externalId:Y,relativePath:J,triggerKind:Q,body:W,contentHash:f,spec:U}}function cL($,J){return mL($,J).replace(/\\/g,"/")}function uL($){if(!kL($))return[];let J=[],Q=[$];while(Q.length>0){let Z=Q.pop();if(!Z)continue;let W;try{W=IL(Z,{withFileTypes:!0})}catch{continue}for(let j of W){let f=`${Z}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Q.push(f);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;J.push(f)}}return J}class g9{store;cronDir;constructor($){this.store=$.store,this.cronDir=vL($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},J=uL(this.cronDir),Q=new Set;for(let W of J){let j=cL(this.cronDir,W);Q.add(j),$.scanned+=1;let f=await this.reconcileFile(j,W);if(f){if($.changes.push(f),$.upserted+=1,f.parse.error)$.invalidParses+=1}}let Z=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let W of Z)if(!Q.has(W.sourcePath))this.handleFileDeleted(W),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,J){let Q=this.store.getSpecBySourcePath($),Z,W;try{Z=xL(J,"utf8"),W=gL(J).mtimeMs}catch{return}let f=SX({relativePath:$,raw:Z}),X=this.store.upsertSpec({externalId:f.externalId,sourcePath:$,triggerKind:f.triggerKind,sourceMtimeMs:W,sourceHash:f.contentHash,parseStatus:f.error?"invalid":"valid",parseError:f.error,spec:f.spec});if(!f.error&&f.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!Q||Q.removed||!Q.enabled||Q.scheduleExpr!==X.record.scheduleExpr||Q.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:f}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let J of $)this.applyScheduleNextRunAt(J,{forceReset:!1})}applyScheduleNextRunAt($,J){if(!$.scheduleExpr)return;if(!J.forceReset&&$.nextRunAt)return;try{let Q=Date.now(),Z=$.lastRunAt?Math.max(Q,new Date($.lastRunAt).getTime()):Q,W=q$($.scheduleExpr,Z,$.timezone),j=new Date(W).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as dL,mkdirSync as lL,watch as pL}from"node:fs";import{relative as rL,resolve as iL}from"node:path";var nL=250;class m9{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??nL),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{lL($,{recursive:!0}),this.watcher=pL($,{recursive:!0},(J,Q)=>{if(!Q)return;let Z=String(Q).replace(/\\/g,"/");if(!Z.endsWith(".md"))return;if(Z.startsWith("reports/"))return;this.scheduleReconcile(Z)}),this.watcher.on("error",this.onError)}catch(J){this.onError(J)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let J=this.pending.get($);if(J)clearTimeout(J);let Q=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Q)}async reconcileNow($){try{let J=iL(this.reconciler.getCronDir(),$);if(!dL(J)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Q=rL(this.reconciler.getCronDir(),J).replace(/\\/g,"/");await this.reconciler.reconcileFile(Q,J),await this.onReconciled()}catch(J){this.onError(J)}}}import{randomUUID as N8}from"node:crypto";import{asOptionalString as h,asString as r,loadSqliteDb as sL,nowIso as B0}from"@cline/shared/db";import{resolveCronDbPath as oL}from"@cline/shared/storage";var aL=[`CREATE TABLE IF NOT EXISTS cron_specs (
206
206
  spec_id TEXT PRIMARY KEY,
207
207
  external_id TEXT NOT NULL,
208
208
  source_path TEXT NOT NULL UNIQUE,
@@ -293,17 +293,17 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
293
293
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
294
294
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
295
295
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
296
- ON cron_specs(source_path);`];function wX($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let J of nL)$.exec(J)}function u6($){if(!$)return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function v9($,J={}){if(!$)return;try{let Q=JSON.parse($);if(!Array.isArray(Q))return;let Z=Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if(J.preserveEmpty)return Z;return Z.length>0?Z:void 0}catch{return}}function P$($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function c1($){return{specId:r($.spec_id),externalId:r($.external_id),sourcePath:r($.source_path),triggerKind:r($.trigger_kind),sourceMtimeMs:P$($.source_mtime_ms),sourceHash:h($.source_hash),parseStatus:r($.parse_status)==="invalid"?"invalid":"valid",parseError:h($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:r($.title),prompt:h($.prompt),workspaceRoot:h($.workspace_root),scheduleExpr:h($.schedule_expr),timezone:h($.timezone),eventType:h($.event_type),filters:u6(h($.filters_json)),debounceSeconds:P$($.debounce_seconds),dedupeWindowSeconds:P$($.dedupe_window_seconds),cooldownSeconds:P$($.cooldown_seconds),mode:h($.mode),systemPrompt:h($.system_prompt),providerId:h($.provider_id),modelId:h($.model_id),maxIterations:P$($.max_iterations),timeoutSeconds:P$($.timeout_seconds),maxParallel:P$($.max_parallel),tools:v9(h($.tools_json),{preserveEmpty:!0}),notesDirectory:h($.notes_directory),extensions:v9(h($.extensions_json),{preserveEmpty:!0}),source:h($.source),tags:v9(h($.tags_json)),metadata:u6(h($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:h($.last_materialized_run_id),lastRunAt:h($.last_run_at),nextRunAt:h($.next_run_at),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function c9($){return{runId:r($.run_id),specId:r($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:r($.trigger_kind),status:r($.status),claimToken:h($.claim_token),claimStartedAt:h($.claim_started_at),claimUntilAt:h($.claim_until_at),scheduledFor:h($.scheduled_for),triggerEventId:h($.trigger_event_id),startedAt:h($.started_at),completedAt:h($.completed_at),sessionId:h($.session_id),reportPath:h($.report_path),error:h($.error),attemptCount:Number($.attempt_count??0),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function SX($){return{eventId:r($.event_id),eventType:r($.event_type),source:r($.source),subject:h($.subject),occurredAt:r($.occurred_at),receivedAt:r($.received_at),workspaceRoot:h($.workspace_root),dedupeKey:h($.dedupe_key),payload:u6(h($.payload_json)),attributes:u6(h($.attributes_json)),processingStatus:r($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:h($.error),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function CX($){return $?JSON.stringify($):null}var oL=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function yX($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function tL($,J,Q,Z){for(let W of oL){let j=$[W],f=J[W];if(yX(j)!==yX(f))return!0}if(Q===!1&&Z===!0)return!0;return!1}function eL($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function $_($){return`hub/schedules/${$}.cron.md`}function J_($){let J={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(J).length>0?J:void 0}function u9($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((J)=>J.trim().length>0),enabled:$.enabled!==!1,metadata:J_($)}}function EX($){return JSON.stringify(u9($))}function Q_($,J){let Q=$.metadata?{...$.metadata}:{},Z=J.createdBy===null?void 0:J.createdBy!==void 0?J.createdBy:typeof Q.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,W=J.cwd!==void 0?J.cwd:typeof Q.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,j=J.runtimeOptions!==void 0?J.runtimeOptions:Q.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0;return delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions,{name:J.name??$.title,cronPattern:J.cronPattern??$.scheduleExpr??"",prompt:J.prompt??$.prompt??"",workspaceRoot:J.workspaceRoot??$.workspaceRoot??"",cwd:W,modelSelection:J.modelSelection!==void 0?J.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:J.enabled??$.enabled,mode:J.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:J.systemPrompt===null?void 0:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,maxIterations:J.maxIterations===null?void 0:J.maxIterations!==void 0?J.maxIterations:$.maxIterations,timeoutSeconds:J.timeoutSeconds===null?void 0:J.timeoutSeconds!==void 0?J.timeoutSeconds:$.timeoutSeconds,maxParallel:J.maxParallel??$.maxParallel??1,createdBy:Z,tags:J.tags??$.tags,runtimeOptions:j,metadata:J.metadata!==void 0?J.metadata:Object.keys(Q).length>0?Q:void 0}}class w8{db;constructor($={}){let J=$.dbPath??sL();this.db=aL(J),wX(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return J?c1(J):void 0}getSpec($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return J?c1(J):void 0}getSpecByExternalId($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return J?c1(J):void 0}listSpecs($={}){let J=[],Q=[];if($.triggerKind)J.push("trigger_kind = ?"),Q.push($.triggerKind);if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.parseStatus)J.push("parse_status = ?"),Q.push($.parseStatus);if(!$.includeRemoved)J.push("removed = 0");let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Z} ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((f)=>c1(f))}createHubSchedule($){let J=`sched_${N8()}`,Q=this.upsertSpec({externalId:J,sourcePath:$_(J),triggerKind:"schedule",sourceHash:EX($),parseStatus:"valid",spec:u9($)});this.initializeScheduleNextRun(Q.record.specId);let Z=this.getSpec(Q.record.specId);if(!Z)throw Error("failed to create hub schedule");return Z}getHubSchedule($){let J=this.db.prepare(`SELECT * FROM cron_specs
296
+ ON cron_specs(source_path);`];function CX($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let J of aL)$.exec(J)}function u6($){if(!$)return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function v9($,J={}){if(!$)return;try{let Q=JSON.parse($);if(!Array.isArray(Q))return;let Z=Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if(J.preserveEmpty)return Z;return Z.length>0?Z:void 0}catch{return}}function P$($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function c1($){return{specId:r($.spec_id),externalId:r($.external_id),sourcePath:r($.source_path),triggerKind:r($.trigger_kind),sourceMtimeMs:P$($.source_mtime_ms),sourceHash:h($.source_hash),parseStatus:r($.parse_status)==="invalid"?"invalid":"valid",parseError:h($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:r($.title),prompt:h($.prompt),workspaceRoot:h($.workspace_root),scheduleExpr:h($.schedule_expr),timezone:h($.timezone),eventType:h($.event_type),filters:u6(h($.filters_json)),debounceSeconds:P$($.debounce_seconds),dedupeWindowSeconds:P$($.dedupe_window_seconds),cooldownSeconds:P$($.cooldown_seconds),mode:h($.mode),systemPrompt:h($.system_prompt),providerId:h($.provider_id),modelId:h($.model_id),maxIterations:P$($.max_iterations),timeoutSeconds:P$($.timeout_seconds),maxParallel:P$($.max_parallel),tools:v9(h($.tools_json),{preserveEmpty:!0}),notesDirectory:h($.notes_directory),extensions:v9(h($.extensions_json),{preserveEmpty:!0}),source:h($.source),tags:v9(h($.tags_json)),metadata:u6(h($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:h($.last_materialized_run_id),lastRunAt:h($.last_run_at),nextRunAt:h($.next_run_at),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function c9($){return{runId:r($.run_id),specId:r($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:r($.trigger_kind),status:r($.status),claimToken:h($.claim_token),claimStartedAt:h($.claim_started_at),claimUntilAt:h($.claim_until_at),scheduledFor:h($.scheduled_for),triggerEventId:h($.trigger_event_id),startedAt:h($.started_at),completedAt:h($.completed_at),sessionId:h($.session_id),reportPath:h($.report_path),error:h($.error),attemptCount:Number($.attempt_count??0),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function yX($){return{eventId:r($.event_id),eventType:r($.event_type),source:r($.source),subject:h($.subject),occurredAt:r($.occurred_at),receivedAt:r($.received_at),workspaceRoot:h($.workspace_root),dedupeKey:h($.dedupe_key),payload:u6(h($.payload_json)),attributes:u6(h($.attributes_json)),processingStatus:r($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:h($.error),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function EX($){return $?JSON.stringify($):null}var tL=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function bX($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function eL($,J,Q,Z){for(let W of tL){let j=$[W],f=J[W];if(bX(j)!==bX(f))return!0}if(Q===!1&&Z===!0)return!0;return!1}function $_($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function J_($){return`hub/schedules/${$}.cron.md`}function Q_($){let J={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(J).length>0?J:void 0}function u9($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((J)=>J.trim().length>0),enabled:$.enabled!==!1,metadata:Q_($)}}function hX($){return JSON.stringify(u9($))}function Z_($,J){let Q=$.metadata?{...$.metadata}:{},Z=J.createdBy===null?void 0:J.createdBy!==void 0?J.createdBy:typeof Q.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,W=J.cwd!==void 0?J.cwd:typeof Q.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,j=J.runtimeOptions!==void 0?J.runtimeOptions:Q.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0;return delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions,{name:J.name??$.title,cronPattern:J.cronPattern??$.scheduleExpr??"",prompt:J.prompt??$.prompt??"",workspaceRoot:J.workspaceRoot??$.workspaceRoot??"",cwd:W,modelSelection:J.modelSelection!==void 0?J.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:J.enabled??$.enabled,mode:J.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:J.systemPrompt===null?void 0:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,maxIterations:J.maxIterations===null?void 0:J.maxIterations!==void 0?J.maxIterations:$.maxIterations,timeoutSeconds:J.timeoutSeconds===null?void 0:J.timeoutSeconds!==void 0?J.timeoutSeconds:$.timeoutSeconds,maxParallel:J.maxParallel??$.maxParallel??1,createdBy:Z,tags:J.tags??$.tags,runtimeOptions:j,metadata:J.metadata!==void 0?J.metadata:Object.keys(Q).length>0?Q:void 0}}class w8{db;constructor($={}){let J=$.dbPath??oL();this.db=sL(J),CX(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return J?c1(J):void 0}getSpec($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return J?c1(J):void 0}getSpecByExternalId($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return J?c1(J):void 0}listSpecs($={}){let J=[],Q=[];if($.triggerKind)J.push("trigger_kind = ?"),Q.push($.triggerKind);if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.parseStatus)J.push("parse_status = ?"),Q.push($.parseStatus);if(!$.includeRemoved)J.push("removed = 0");let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Z} ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((f)=>c1(f))}createHubSchedule($){let J=`sched_${N8()}`,Q=this.upsertSpec({externalId:J,sourcePath:J_(J),triggerKind:"schedule",sourceHash:hX($),parseStatus:"valid",spec:u9($)});this.initializeScheduleNextRun(Q.record.specId);let Z=this.getSpec(Q.record.specId);if(!Z)throw Error("failed to create hub schedule");return Z}getHubSchedule($){let J=this.db.prepare(`SELECT * FROM cron_specs
297
297
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
298
298
  ORDER BY created_at ASC LIMIT 1`).get($);return J?c1(J):void 0}listHubSchedules($={}){let J=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Q=[];if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)J.push("tags_json LIKE ?"),Q.push(`%"${j.trim()}"%`);let Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
299
299
  WHERE ${J.join(" AND ")}
300
- ORDER BY created_at DESC LIMIT ?`).all(...Q,Z).map((j)=>c1(j))}updateHubSchedule($,J){let Q=this.getHubSchedule($);if(!Q)return;let Z=Q_(Q,J),W=this.upsertSpec({externalId:$,sourcePath:Q.sourcePath,triggerKind:"schedule",sourceHash:EX(Z),parseStatus:"valid",spec:u9(Z)});if(J.cronPattern!==void 0||J.enabled!==void 0)this.initializeScheduleNextRun(W.record.specId);return this.getSpec(W.record.specId)}deleteHubSchedule($){let J=this.getHubSchedule($);if(!J)return!1;return this.markSpecRemoved(J.specId),this.cancelQueuedRunsForSpec(J.specId),!0}enqueueHubScheduleRun($,J="manual"){let Q=this.getHubSchedule($);if(!Q||!Q.enabled||Q.removed||Q.parseStatus!=="valid")return;return this.enqueueRun({specId:Q.specId,specRevision:Q.revision,triggerKind:J,scheduledFor:B0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
300
+ ORDER BY created_at DESC LIMIT ?`).all(...Q,Z).map((j)=>c1(j))}updateHubSchedule($,J){let Q=this.getHubSchedule($);if(!Q)return;let Z=Z_(Q,J),W=this.upsertSpec({externalId:$,sourcePath:Q.sourcePath,triggerKind:"schedule",sourceHash:hX(Z),parseStatus:"valid",spec:u9(Z)});if(J.cronPattern!==void 0||J.enabled!==void 0)this.initializeScheduleNextRun(W.record.specId);return this.getSpec(W.record.specId)}deleteHubSchedule($){let J=this.getHubSchedule($);if(!J)return!1;return this.markSpecRemoved(J.specId),this.cancelQueuedRunsForSpec(J.specId),!0}enqueueHubScheduleRun($,J="manual"){let Q=this.getHubSchedule($);if(!Q||!Q.enabled||Q.removed||Q.parseStatus!=="valid")return;return this.enqueueRun({specId:Q.specId,specRevision:Q.revision,triggerKind:J,scheduledFor:B0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
301
301
  WHERE trigger_kind = 'event'
302
302
  AND event_type = ?
303
303
  AND enabled = 1
304
304
  AND removed = 0
305
305
  AND parse_status = 'valid'
306
- ORDER BY created_at ASC`).all($).map((Q)=>c1(Q))}upsertSpec($){let J=B0(),Q=this.getSpecBySourcePath($.sourcePath),Z=$.spec,W={title:Z?.title??Q?.title??eL($.sourcePath),prompt:Z?.prompt,workspaceRoot:Z?.workspaceRoot,scheduleExpr:Z?.triggerKind==="schedule"?Z.schedule:void 0,timezone:Z?.triggerKind==="schedule"?Z.timezone:void 0,eventType:Z?.triggerKind==="event"?Z.event:void 0,filters:Z?.triggerKind==="event"?Z.filters:void 0,debounceSeconds:Z?.triggerKind==="event"?Z.debounceSeconds:void 0,dedupeWindowSeconds:Z?.triggerKind==="event"?Z.dedupeWindowSeconds:void 0,cooldownSeconds:Z?.triggerKind==="event"?Z.cooldownSeconds:void 0,mode:Z?.mode,systemPrompt:Z?.systemPrompt,providerId:Z?.modelSelection?.providerId,modelId:Z?.modelSelection?.modelId,maxIterations:Z?.maxIterations,timeoutSeconds:Z?.timeoutSeconds,maxParallel:Z&&"maxParallel"in Z?Z.maxParallel:void 0,tools:Z?.tools,notesDirectory:Z?.notesDirectory,extensions:Z?.extensions,source:Z?.source},j=$.parseStatus==="valid"&&(Z?.enabled??!0);if(!Q){let H=`cspec_${N8()}`;this.insertSpecRow(H,$,W,j,J);let B=this.getSpec(H);if(!B)throw Error("failed to insert cron_spec row");return{record:B,created:!0,revisionChanged:!0}}let X=Q.sourceHash!==$.sourceHash&&tL(Q,W,Q.enabled,j),Y=X?Q.revision+1:Q.revision;this.updateSpecRow(Q.specId,$,W,j,Y,J);let V=this.getSpec(Q.specId);if(!V)throw Error("failed to reload cron_spec after update");return{record:V,created:!1,revisionChanged:X}}insertSpecRow($,J,Q,Z,W){let j=J.spec;this.db.prepare(`INSERT INTO cron_specs (
306
+ ORDER BY created_at ASC`).all($).map((Q)=>c1(Q))}upsertSpec($){let J=B0(),Q=this.getSpecBySourcePath($.sourcePath),Z=$.spec,W={title:Z?.title??Q?.title??$_($.sourcePath),prompt:Z?.prompt,workspaceRoot:Z?.workspaceRoot,scheduleExpr:Z?.triggerKind==="schedule"?Z.schedule:void 0,timezone:Z?.triggerKind==="schedule"?Z.timezone:void 0,eventType:Z?.triggerKind==="event"?Z.event:void 0,filters:Z?.triggerKind==="event"?Z.filters:void 0,debounceSeconds:Z?.triggerKind==="event"?Z.debounceSeconds:void 0,dedupeWindowSeconds:Z?.triggerKind==="event"?Z.dedupeWindowSeconds:void 0,cooldownSeconds:Z?.triggerKind==="event"?Z.cooldownSeconds:void 0,mode:Z?.mode,systemPrompt:Z?.systemPrompt,providerId:Z?.modelSelection?.providerId,modelId:Z?.modelSelection?.modelId,maxIterations:Z?.maxIterations,timeoutSeconds:Z?.timeoutSeconds,maxParallel:Z&&"maxParallel"in Z?Z.maxParallel:void 0,tools:Z?.tools,notesDirectory:Z?.notesDirectory,extensions:Z?.extensions,source:Z?.source},j=$.parseStatus==="valid"&&(Z?.enabled??!0);if(!Q){let H=`cspec_${N8()}`;this.insertSpecRow(H,$,W,j,J);let B=this.getSpec(H);if(!B)throw Error("failed to insert cron_spec row");return{record:B,created:!0,revisionChanged:!0}}let X=Q.sourceHash!==$.sourceHash&&eL(Q,W,Q.enabled,j),Y=X?Q.revision+1:Q.revision;this.updateSpecRow(Q.specId,$,W,j,Y,J);let V=this.getSpec(Q.specId);if(!V)throw Error("failed to reload cron_spec after update");return{record:V,created:!1,revisionChanged:X}}insertSpecRow($,J,Q,Z,W){let j=J.spec;this.db.prepare(`INSERT INTO cron_specs (
307
307
  spec_id, external_id, source_path, trigger_kind,
308
308
  source_mtime_ms, source_hash, parse_status, parse_error,
309
309
  enabled, removed, title, prompt, workspace_root,
@@ -341,9 +341,9 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
341
341
  payload_json, attributes_json, processing_status,
342
342
  matched_spec_count, queued_run_count, suppressed_count,
343
343
  error, created_at, updated_at
344
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(W,j,f,$.subject?.trim()||null,X,Z,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,CX($.payload),CX($.attributes),"received",0,0,0,null,Q,Q).changes??0,V=this.getEventLog(W);if(!V)throw Error("failed to insert cron_event_log row");return{record:V,created:Y===1}}getEventLog($){let J=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return J?SX(J):void 0}listEventLogs($={}){let J=[],Q=[];if($.eventType)J.push("event_type = ?"),Q.push($.eventType);if($.source)J.push("source = ?"),Q.push($.source);if($.processingStatus)J.push("processing_status = ?"),Q.push($.processingStatus);let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Z}
344
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(W,j,f,$.subject?.trim()||null,X,Z,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,EX($.payload),EX($.attributes),"received",0,0,0,null,Q,Q).changes??0,V=this.getEventLog(W);if(!V)throw Error("failed to insert cron_event_log row");return{record:V,created:Y===1}}getEventLog($){let J=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return J?yX(J):void 0}listEventLogs($={}){let J=[],Q=[];if($.eventType)J.push("event_type = ?"),Q.push($.eventType);if($.source)J.push("source = ?"),Q.push($.source);if($.processingStatus)J.push("processing_status = ?"),Q.push($.processingStatus);let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Z}
345
345
  ORDER BY received_at DESC, created_at DESC
346
- LIMIT ?`).all(...Q,W).map((f)=>SX(f))}updateEventLogProcessing($,J){return(this.db.prepare(`UPDATE cron_event_log SET
346
+ LIMIT ?`).all(...Q,W).map((f)=>yX(f))}updateEventLogProcessing($,J){return(this.db.prepare(`UPDATE cron_event_log SET
347
347
  processing_status = ?,
348
348
  matched_spec_count = COALESCE(?, matched_spec_count),
349
349
  queued_run_count = COALESCE(?, queued_run_count),
@@ -438,13 +438,13 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
438
438
  error = ?,
439
439
  scheduled_for = COALESCE(?, scheduled_for),
440
440
  updated_at = ?
441
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,B0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,B0(),$)}}class S8{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new w8({dbPath:$.dbPath});let J=$.specs;this.reconciler=new g9({store:this.store,specs:J}),this.materializer=new T8({store:this.store}),this.eventIngress=new q9({store:this.store,logger:$.logger}),this.runner=new M8({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:J,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new m9({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let Z=$.logger;if(Z)if(Z.error)Z.error("cron.watcher.failed",{error:Q});else Z.log("cron.watcher.failed",{error:Q})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}import{readdir as G_,readFile as uX}from"node:fs/promises";import{join as dX}from"node:path";import{formatDisplayUserInput as F_,normalizeUserInput as D_}from"@cline/shared";import{resolveSessionDataDir as lX}from"@cline/shared/storage";import{mkdirSync as j_,writeFileSync as f_}from"node:fs";import{dirname as X_}from"node:path";import{normalizeUserInput as Y_}from"@cline/shared";import{nanoid as V_}from"nanoid";import{nanoid as Z_}from"nanoid";function C8($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function d6($,J){let Q=C8($),Z=C8(J),W=`${Q}__${Z}`;return W.length>180?W.slice(0,180):W}function d9($,J){let Q=C8($),Z=C8(J);return`${Q}__teamtask__${Z}__${Z_(6)}`}function y8($){let Q=$.indexOf("__teamtask__");if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+12),j=W.lastIndexOf("__");if(j<=0)return null;let f=W.slice(0,j),X=W.slice(j+2);if(!Z||!f||!X)return null;return{rootSessionId:Z,agentId:f,teamTaskId:X}}function l6($){if(y8($))return null;let J="__",Q=$.indexOf(J);if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+J.length);if(!Z||!W)return null;return{rootSessionId:Z,agentId:W}}function l9($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let J=String($.reason??"").toLowerCase();if(J.includes("cancel")||J.includes("abort")||J.includes("interrupt"))return"cancelled";if(J.includes("fail")||J.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as i}from"zod";var W_=i.enum($Q),P0=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:W_,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 bX($){if(!$)return!1;return Object.values($).some((J)=>typeof J==="function")}function r9($,J){let Q=[...$??[],...J??[]];if(Q.length===0)return;let Z=[],W=new Set;for(let j of Q){if(W.has(j.name))continue;W.add(j.name),Z.push(j)}return Z}function hX($){return JSON.stringify($,(J,Q)=>{if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};return Q})}function G1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function p9($,J){let Q={...$};Q.id=G1(Q.id)??V_();let Z=Q.modelInfo&&typeof Q.modelInfo==="object"?{...Q.modelInfo}:void 0,W={id:G1(Z?.id)??G1(Q.modelId)??G1(J?.id),provider:G1(Z?.provider)??G1(Q.providerId)??G1(J?.provider),family:G1(Z?.family)??G1(J?.family)};if(delete Q.providerId,delete Q.modelId,W.id&&W.provider)Q.modelInfo={id:W.id,provider:W.provider,...W.family?{family:W.family}:{}};else delete Q.modelInfo;return Q}function p6($){return $.map((J)=>p9(J))}function r6($,J,Q=[]){let Z=$.map((Y,V)=>{let H=Q[V],A=H?.role===Y.role&&JSON.stringify(H.content)===JSON.stringify(Y.content)?{...H,...Y}:{...Y};return p9(A)}),W=Q.length,j=[];for(let Y=W;Y<Z.length;Y+=1)if(Z[Y]?.role==="assistant")j.push(Y);if(j.length===0){let Y=[...Z].reverse().findIndex((V)=>V.role==="assistant");if(Y===-1)return Z;j.push(Z.length-1-Y)}let f=j[j.length-1],X=j.some((Y)=>Z[Y]?.metrics);for(let Y of j){let V=Z[Y],H=V.metrics;if(!H&&Y===f&&!X){let B=J.usage;H={inputTokens:B.inputTokens,outputTokens:B.outputTokens,cacheReadTokens:B.cacheReadTokens??0,cacheWriteTokens:B.cacheWriteTokens??0,cost:B.totalCost}}Z[Y]={...p9(V,{id:J.model.id,provider:J.model.provider,family:J.model.info?.family}),...H?{metrics:H}:{},ts:V.ts??J.endedAt.getTime()}}return Z}function E8($){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 H_=120;function N$($){let J=$?.trim();return J?J.slice(0,H_):void 0}function i9($){let J=Y_($??"").trim();if(!J)return;return N$(J.split(`
442
- `)[0]?.trim())}function u1($){if(!$)return;let J={...$},Q=N$(typeof J.title==="string"?J.title:void 0);if(Q)J.title=Q;else delete J.title;return Object.keys(J).length>0?J:void 0}function b8($){let J=u1($.metadata)??{},Q=$.title!==void 0?N$($.title):i9($.prompt);if(Q)J.title=Q;return Object.keys(J).length>0?J:void 0}function n9($){let J=y8($);if(J)return{agent:"teammate",sessionId:J.rootSessionId,taskType:"team"};let Q=l6($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function a9($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:p6($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function kX($,J,Q){j_(X_($),{recursive:!0}),f_($,`${JSON.stringify(a9({updatedAt:J,context:Q,messages:[]}),null,2)}
443
- `,"utf8")}function IX($,J){return P0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:J?.endedAt??$.endedAt??void 0,exit_code:J?.exitCode??$.exitCode??void 0,status:J?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:J?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function xX($,J,Q){let Z=0;while(!0){let W=await $();if(W===void 0)return{updated:!1};let j=await J(W);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Z+=1,Z>=Q)return j;continue}return j}}import{existsSync as B_}from"node:fs";import{readFile as A_}from"node:fs/promises";import{formatDisplayUserInput as gX}from"@cline/shared";class h8{listeners=new Set;subscribe($,J){let Q={listener:$,sessionId:J?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let J=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J)continue;Q.listener($)}}get size(){return this.listeners.size}}async function d1($){let J=$?.trim();if(!J||!B_(J))return[];try{let Q=(await A_(J,"utf8")).trim();if(!Q)return[];let Z=JSON.parse(Q);if(Array.isArray(Z))return mX(Z);if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let W=Z.messages;if(Array.isArray(W))return mX(W)}return[]}catch{return[]}}function K_($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:gX($.content)};return{...$,content:$.content.map((J)=>{if(J.type!=="text"||typeof J.text!=="string")return J;return{...J,text:gX(J.text)}})}}function mX($){return $.map(K_)}function s9($){return $?{...$}:void 0}async function vX($,J){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await J.queueSpawnRequest($);let Z=await J.upsertSubagentSessionFromHook($);if(!Z)return;await J.appendSubagentHookAudit(Z,$),await J.applySubagentStatus(Z,$)}function k8($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function I0($){let J=k8($);if(!J)return;return J.toLowerCase()==="unknown"?void 0:J}function i6($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function U_($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function t9($){let J=$??200;return Number.isFinite(J)?Math.max(0,Math.floor(J)):200}function R_($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function z_($){return $.isSubagent!==!0&&!k8($.parentSessionId)}function L_($){let J=$.match(/\d{13,}/g);if(!J||J.length===0)return 0;let Q=0;for(let Z of J){let W=Number.parseInt(Z,10);if(Number.isFinite(W)&&W>Q)Q=W}return Q}function e9($){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 __($){let J=t9($);if(J===0)return[];let Q=lX(),W=(await G_(Q,{withFileTypes:!0}).catch(()=>[])).filter((f)=>f.isDirectory()).map((f)=>({entry:f,recency:L_(f.name.trim())})).sort((f,X)=>X.recency-f.recency||X.entry.name.localeCompare(f.entry.name));return(await Promise.all(W.map(async({entry:f})=>{let X=f.name.trim();if(!X)return;let Y=dX(Q,X,`${X}.json`),V=await uX(Y,"utf8").catch(()=>{return});if(!V)return;let H;try{H=JSON.parse(V)}catch{return}let B=P0.safeParse(H);if(!B.success)return;return e9(B.data)}))).filter((f)=>Boolean(f)).sort((f,X)=>X.startedAt.localeCompare(f.startedAt)).slice(0,J)}async function O_($,J,Q){let Z=t9(J);if(Z===0)return await $.listSessions(0),[];let W=Q.includeSubagents?Z:R_(Z),j=await $.listSessions(W);return(Q.includeSubagents?j:j.filter(z_)).slice(0,Z)}function T_($){if(typeof $==="string")return $.trim();let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q;if(Z.type!=="text")continue;let W=Z.text?.trim();if(W)J.push(W)}return J.join(`
444
- `).trim()}function cX($){return $.replace(/\s+/g," ").trim()}function M_($,J){if($.length<=J)return $;return`${$.slice(0,Math.max(0,J-3)).trimEnd()}...`}function q_($){for(let J of["user","assistant"])for(let Q of $){if(Q.role!==J)continue;let Z=cX(T_(Q.content));if(!Z)continue;let W=J==="user"?cX(F_(Z)):Z,j=D_(W.split(`
445
- `)[0]??W);return M_(j,50)}return}function P_($){let J=0;for(let Q of $)J+=i6(Q.metrics?.cost)??0;return J}function N_($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=I0(W.modelInfo?.provider);if(!Q)Q=I0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function w_($){return I0($?.provider)??I0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function S_($){return I0($?.model)??I0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function o9($,J){let Q=U_($.metadata),Z=k8(J?.title)??k8(Q?.title),W=i6(J?.totalCost)??i6(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:I0(J?.provider)??I0($.provider)??w_(Q)??"",model:I0(J?.model)??I0($.model)??S_(Q)??"",metadata:j}}function C_($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function y_($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!C_(Q)}async function E_($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return y_(Q,Z)?{...Q,status:"idle"}:Q}))}async function b_($,J){return await Promise.all(J.map(async(Q)=>{let Z=o9(Q),W=Boolean(k8(Z.metadata?.title)),j=Boolean(I0(Z.provider)),f=Boolean(I0(Z.model)),X=i6(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=N_(V),B=P_(V);return o9(Q,{title:W?void 0:q_(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||B<=0?void 0:B})}))}async function $Z($,J={}){let Q=t9(J.limit),Z=J.includeSubagents===!0,W=await O_($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await __(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await E_($,X);if(J.hydrate===!1)return Y.map((V)=>o9(V));return await b_($,Y)}async function h_($){let J=$.trim();if(!J)return;let Q=dX(lX(),J,`${J}.json`),Z=await uX(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=P0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function k_($,J={}){let Q=new Map;return await $Z({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map(E8)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await h_(W);return await d1(j)}},J)}import{captureSdkError as qH}from"@cline/shared";import{createSessionId as IO,isHubProtocolCompatible as xO,resolveClineBuildEnv as gO,resolveHubCommandTimeoutMs as mO}from"@cline/shared";import{spawn as AO}from"node:child_process";import{closeSync as KO,mkdirSync as GO,openSync as FO}from"node:fs";import{basename as DO,dirname as UO,join as RO}from"node:path";import{fileURLToPath as zO}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as LO,isHubDaemonProcess as jY,isHubProtocolCompatible as _O,resolveClineBuildEnv as fY,withResolvedClineBuildEnv as OO}from"@cline/shared";import{createHash as I_,randomBytes as x_}from"node:crypto";import{existsSync as g_}from"node:fs";import{chmod as m_,mkdir as JZ,readFile as aX,rm as QZ,writeFile as sX}from"node:fs/promises";import{dirname as oX,join as ZZ}from"node:path";import{resolveClineDataDir as x8,resolveClineDir as cg}from"@cline/shared/storage";var rX="0.0.47-nightly.1781580004";var I8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:rX,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var v_="CLINE_HUB_DISCOVERY_PATH",c_="CLINE_HUB_BUILD_ID",iX=30000,u_=15000,d_=100;function l_($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function p_($){return I_("sha256").update($).digest("hex").slice(0,12)}function r_($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function tX(){return x_(32).toString("hex")}function i_($){return new Promise((J)=>setTimeout(J,$))}function n_($){return`${$}.lock`}async function a_($){try{let J=JSON.parse(await aX(ZZ($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function nX($){await QZ($,{recursive:!0,force:!0}).catch(()=>{return})}function eX(){return process.env[c_]?.trim()||String(I8.version)}function w$($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${p_($)}`,Q=process.env[v_]?.trim()||ZZ(x8(),"locks","hub","owners",`${l_(J)}.json`);return{ownerId:J,discoveryPath:Q}}function dg($=`hub-${Date.now().toString(36)}`){return w$($)}async function A0($){try{let J=JSON.parse(await aX($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function $Y($,J){await JZ(oX($),{recursive:!0}),await QZ($,{force:!0}).catch(()=>{return}),await sX($,`${JSON.stringify(J,null,2)}
446
- `,{encoding:"utf8",mode:384}),await m_($,384)}async function n0($){await QZ($,{force:!0}).catch(()=>{return})}async function JY($,J){let Q=n_($);await JZ(oX(Q),{recursive:!0});let Z=Date.now()+u_;while(!0)try{await JZ(Q,{recursive:!1}),await sX(ZZ(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
447
- `,"utf8");try{return await J()}finally{await nX(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await a_(Q),X=f?Date.now()-Date.parse(f.acquiredAt):iX+1;if(!f||!r_(f.pid)||X>iX){await nX(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await i_(d_)}}async function S$($,J){try{let Q=await fetch(J?.authToken?s_($):QY($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function F1($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function QY($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function s_($){let J=new URL(QY($));return J.pathname="/status",J.toString()}function lg($){return g_($)}import{CLINE_HUB_DEV_PORT as o_,CLINE_HUB_PORT as t_,resolveClineBuildEnv as e_}from"@cline/shared";var $O="CLINE_HUB_HOST",JO="CLINE_HUB_PORT",QO="CLINE_HUB_PATHNAME",ZO="127.0.0.1",WO=t_,jO="/hub";function ZY($){return e_($)==="development"?o_:WO}function fO($={}){return($.env??process.env)[$O]?.trim()||ZO}function n6($={}){let Q=($.env??process.env)[JO]?.trim();if(!Q)return ZY($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return ZY($);return Z}function XO($={}){return($.env??process.env)[QO]?.trim()||jO}function l1($={},J={}){return{host:$.host??fO(J),port:$.port??n6(J),pathname:$.pathname??XO(J)}}import{join as YO}from"node:path";var VO="shared:cline",HO="CLINE_HUB_DISCOVERY_PATH",BO="hub-production";function og($){let J=T$($.trim());return w$(`workspace:${J||$.trim()}`)}function D1($=VO){return w$($)}function p1(){return{ownerId:BO,discoveryPath:process.env[HO]?.trim()||YO(x8(),"locks","hub","production.json")}}var TO=8000,MO=200,qO=3000,PO=100,NO=[100,250,500,1000,2000],wO="--cline-hub-daemon";function SO($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function CO(){try{let $=RO(x8(),"logs","hub-daemon.log");return GO(UO($),{recursive:!0}),{fd:FO($,"a"),logPath:$}}catch{return}}function XY(){return fY()==="production"?p1():D1()}function C$($){return _O($).compatible}function WY($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function y$($,J){try{return await S$($,{authToken:J})}catch{return}}async function yO($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await y$($))?.url)return!0;await new Promise((W)=>setTimeout(W,PO))}return!1}async function a6($,J){if(await WZ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await yO($.url,qO);return await n0(J).catch(()=>{return}),Q}async function g8($,J){if(C$($))return!0;return a6($,J)}async function YY($){if(fY()!=="production")return;let J=D1();if(J.discoveryPath===$.discoveryPath)return;let Q=await A0(J.discoveryPath);if(Q?.url)await a6(Q,J.discoveryPath);else await n0(J.discoveryPath).catch(()=>{return})}function EO(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return zO(new URL(`./entry.${$}`,import.meta.url))}function bO($,J){let Q=EO(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=DO(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[wO]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...SO(J)],cwd:$,env:{...OO(process.env),CLINE_NO_INTERACTIVE:"1",[LO]:"1"}}}function hO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function kO($,J={}){if(jY())return;let Q=bO($,J),Z=CO();try{AO(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)KO(Z.fd)}}async function s6($,J={}){for(let Q=0;;Q++)try{kO($,J);return}catch(Z){let W=NO[Q];if(!hO(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function VY($,J={}){if(jY())return;let Q=XY(),Z=l1(J),W=F1(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;YY(Q).catch(()=>{return}).then(()=>A0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await a6(f,Q.discoveryPath)&&!j)return}else{let H=await y$(f.url,f.authToken);if(H?.url&&C$(H)&&await r1(H.url,{authToken:f.authToken}))return;if(H?.url)await g8({...H,authToken:f.authToken},Q.discoveryPath);else await n0(Q.discoveryPath).catch(()=>{return})}let Y=await y$(W);if(Y?.url){if(C$(Y)){if(!j||!X)return}else if(!await g8({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await s6($,V)}).catch(()=>{})}async function Ym($,J={}){let Q=XY(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=l1(J),j=F1(W.host,W.port,W.pathname),f=(K)=>{if(!Z)O2(K.url,K.authToken);return K};await YY(Q).catch(()=>{return});let X=await A0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await a6(X,Q.discoveryPath);else{let G=await y$(X.url,K);if(G?.url&&C$(G)&&await r1(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await g8({...G,authToken:K},Q.discoveryPath);else await n0(Q.discoveryPath).catch(()=>{return})}}let V=await y$(j);if(V?.url){let K=WY(V,X,j);if(C$(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await g8(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await s6($,B);let A=Date.now()+TO;while(Date.now()<A){let K=await A0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await y$(K.url,K.authToken);if(R?.url&&C$(R)&&await r1(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await y$(j);if(G?.url&&!C$(G)){let R=WY(G,K,j);if(!await g8(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,MO))}throw Error("Timed out waiting for detached hub startup.")}function t6(){return gO()==="production"?p1():D1()}function vO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function GY($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return GY($.data);return String($)}function cO($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function HY($){let J=$,Q=cO(J.reason);return new x0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:jZ,{closeCode:J.code,closeReason:Q||void 0})}function uO($,J){if($ instanceof x0)return $;if($ instanceof Error)return new x0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new x0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new x0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new x0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var dO=8000,lO=200,BY="*",AY=8000,pO="cline-hub-auth.",FY=new Map,DY=new Set,rO=3000,iO=3000,nO=100,jZ="Hub connection closed",aO=250,sO=5000,KY=0.5;class x0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function oO($){return $ instanceof x0}class o6 extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function UY($,J){return $ instanceof o6&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function RY($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=YZ($.toString());return Q?FY.get(Q):void 0}function tO($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function YZ($){if(!tO($))return;let J=new URL(T2($));return J.search="",J.hash="",J.toString()}function fZ($){let J=YZ($);return!!J&&DY.has(J)}function O2($,J){let Q=YZ($);if(Q){if(DY.add(Q),J?.trim())FY.set(Q,J)}return $}class U1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new x0("hub_connection_closed",jZ);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),J=this.options.authToken?.trim()||RY($);$.hash="";let Z=new(vO())($.toString(),J?[`${pO}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new x0("hub_connect_timeout",`Timed out connecting to hub after ${AY}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},AY);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=uO(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=HY(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(GY(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=HY(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=IO("hubreq_"),j=mO($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new o6($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(W,{resolve:(B)=>{if(H)clearTimeout(H);Y(B)},reject:(B)=>{if(H)clearTimeout(H);V(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===_8){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new _$(Y,X.error.message)}throw new o6($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!fZ(this.currentUrl)||!oO($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await m8({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(aO*2**this.reconnectAttempt,sO),J=Math.round($*(1-KY)+Math.random()*$*KY);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!fZ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await m8({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 x0("hub_connection_closed",jZ),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new x0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??BY}subscriptionSessionIdFromKey($){return $===BY?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function T2($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function r1($,J){let Q=new U1({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function XZ($,J){let Q=T2($),Z=await S$(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!xO(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await r1(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function eO($){let J=Date.now()+dO;while(Date.now()<J){let Q=await A0($.discoveryPath);if(Q?.url){let Z=await XZ(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return O2(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,lO))}return}async function $T($){let J=Date.now()+iO;while(Date.now()<J){if(!(await S$($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,nO))}return!1}function JT($,J){try{return T2($)===T2(J)}catch{return!1}}function QT($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function ZT($,J,Q){let Z=new U1({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:rO});return!QT(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function VZ($={}){if($.endpoint?.trim()){let W=await XZ($.endpoint);return W.status==="compatible"?W.url:void 0}let J=t6(),Q=await A0(J.discoveryPath);if(!Q?.url)return;let Z=await XZ(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return O2(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await n0(J.discoveryPath).catch(()=>{return});return}async function m8($={}){let J=await VZ($);if(J&&await r1(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=t6();return await s6($.workspaceRoot??process.cwd()),await eO(Q)}async function WZ($,J){let Q=new URL($),Z=J?.trim()||RY(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function WT($=t6()){let J=await A0($.discoveryPath);if(!J?.url)return!1;try{if(await WZ(J.url,J.authToken))return!0}catch{}return!1}async function zY($){if(!fZ($.url))return;let J=t6(),Q=await A0(J.discoveryPath);if(!Q?.url||!JT(Q.url,$.url))return;if(!await ZT(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await WT())return;if(!await $T(Q.url))return;return await n0(J.discoveryPath).catch(()=>{return}),await m8({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as LY,createSessionId as _Y,HUB_CHECKPOINT_CAPABILITY as YT,HUB_COMPACTION_CAPABILITY as VT,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as HT,HUB_HOOK_CAPABILITY_PREFIX as BT,HUB_MISTAKE_LIMIT_CAPABILITY as AT,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as KT,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as GT,isHubToolExecutorName as FT}from"@cline/shared";function jT($){return $?JSON.parse(JSON.stringify($)):void 0}function fT($){return $?JSON.parse(JSON.stringify($)):void 0}function XT($){let J=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Z=(Array.isArray(J?.history)?J.history:[]).filter((f)=>!!f&&typeof f==="object"&&!Array.isArray(f)).flatMap((f)=>{let X=typeof f.ref==="string"?f.ref.trim():"",Y=Number(f.createdAt),V=Number(f.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...f.kind==="stash"||f.kind==="commit"?{kind:f.kind}:{}}]}),W=Z.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Z.length===0)return;return{...j?{enabled:j}:{},...W?{latest:W}:{},history:Z}}function i1($){let{session:J}=$,Q=jT(J.metadata);return{version:1,sessionId:J.sessionId,source:J.source,status:J.status,createdAt:J.startedAt,updatedAt:J.updatedAt,endedAt:J.endedAt??null,exitCode:J.exitCode??null,interactive:J.interactive,workspace:{cwd:J.cwd,root:J.workspaceRoot},model:{providerId:J.provider,modelId:J.model},capabilities:{enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams},lineage:{...J.parentSessionId?{parentSessionId:J.parentSessionId}:{},...J.parentAgentId?{parentAgentId:J.parentAgentId}:{},...J.agentId?{agentId:J.agentId}:{},...J.conversationId?{conversationId:J.conversationId}:{},isSubagent:J.isSubagent},...J.teamName?{team:{name:J.teamName}}:{},...J.prompt?{prompt:J.prompt}:{},...Q?{metadata:Q}:{},...J.messagesPath?{artifacts:{messagesPath:J.messagesPath}}:{},...$.messages?{messages:fT($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Z=XT(Q);return Z?{checkpoint:Z}:{}})()}}function HZ($){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 M2($){if(!$)return;return JSON.parse(JSON.stringify($))}var DT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function OY($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function TY($){if(!$)return;let{userInstructionService:J,...Q}=$;return JSON.parse(JSON.stringify(Q))}function MY($){let J=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof J.agentId==="string"?J.agentId:"",conversationId:typeof J.conversationId==="string"?J.conversationId:"",iteration:typeof J.iteration==="number"?J.iteration:0,metadata:J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}}function E$($,J,Q){$.manifest.push(J),$.handlers.set(J.capabilityName,Q)}function qY($,J){let Q={manifest:[],handlers:new Map};for(let W of Object.keys(J.toolExecutors??{}).filter(FT)){let j=J.toolExecutors?.[W];if(typeof j!=="function")continue;E$(Q,{kind:"toolExecutor",executor:W,capabilityName:`${KT}${W}`},async({payload:f,abortSignal:X})=>{let Y=Array.isArray(f.args)?[...f.args]:[],V={...MY(f.context),signal:X};return{result:await j(...Y,V)}})}for(let W of $?.extraTools??[])E$(Q,{kind:"tool",name:W.name,description:W.description,inputSchema:M2(W.inputSchema)??{},...W.lifecycle?{lifecycle:M2(W.lifecycle)}:{},capabilityName:`${HT}${W.name}`},async({payload:j,abortSignal:f,progress:X})=>{let Y={...MY(j.context),signal:f};return{result:await W.execute(j.input,{...Y,emitUpdate:(H)=>{X({update:H})}})}});let Z=$?.hooks;if(Z)for(let W of DT){let j=Z[W];if(typeof j!=="function")continue;E$(Q,{kind:"hook",name:W,capabilityName:`${BT}${W}`},async({payload:f})=>({control:await j(f.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;E$(Q,{kind:"compaction",capabilityName:VT,config:OY($.compaction)},async({payload:j})=>({result:await W(j.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;E$(Q,{kind:"checkpoint",capabilityName:YT,config:OY($.checkpoint)},async({payload:j})=>({result:await W(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;E$(Q,{kind:"mistakeLimit",capabilityName:AT},async({payload:j})=>({result:await W(j.context)}))}if($?.userInstructionService){let W=$.userInstructionService;E$(Q,{kind:"userInstructionService",capabilityName:GT},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Q}function SY($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let J=$.message;if(typeof J==="string"&&J.trim())return J.trim()}return}function UT($){return SY($)??"Capability request was cancelled."}function RT($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function zT($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function LT($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=typeof J.inputTokens==="number"?J.inputTokens:void 0,Z=typeof J.outputTokens==="number"?J.outputTokens:void 0;if(Q===void 0||Z===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:typeof J.cacheReadTokens==="number"?J.cacheReadTokens:0,cacheWriteTokens:typeof J.cacheWriteTokens==="number"?J.cacheWriteTokens:0,totalCost:typeof J.totalCost==="number"?J.totalCost:0}}function PY($){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 BZ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function n1($,J){return BZ($?.[J])??0}function _T($){let J=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Z=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=Z?.teamRole==="teammate"||Z?.teamRole==="lead"?Z.teamRole:void 0;return{event:{type:"usage",agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,inputTokens:n1(J,"inputTokens"),outputTokens:n1(J,"outputTokens"),cacheReadTokens:n1(J,"cacheReadTokens"),cacheWriteTokens:n1(J,"cacheWriteTokens"),cost:BZ(J?.totalCost),totalInputTokens:n1(Q,"inputTokens"),totalOutputTokens:n1(Q,"outputTokens"),totalCacheReadTokens:n1(Q,"cacheReadTokens"),totalCacheWriteTokens:n1(Q,"cacheWriteTokens"),totalCost:BZ(Q?.totalCost)},teamAgentId:typeof Z?.teamAgentId==="string"?Z.teamAgentId:void 0,teamRole:W}}function OT($){let J=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??J?.finishReason,Z=zT(Q)?Q:Q==="failed"?"error":"completed",W=LT($?.usage??J?.usage);return{type:"done",reason:Z,text:typeof $?.text==="string"?$.text:typeof J?.text==="string"?J.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof J?.iterations==="number"?J.iterations:0,usage:W}}function e6($,J){return $.error?.message??`hub command failed: ${J}`}function v8($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function CY($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof J?.agentId==="string"?J.agentId:void 0),parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,isSubagent:typeof J?.isSubagent==="boolean"?J.isSubagent:!1,source:typeof J?.source==="string"?J.source:z0.CORE,pid:typeof J?.pid==="number"?J.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:v8($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:v8($.status)==="completed"?0:v8($.status)==="failed"?1:void 0,status:v8($.status),interactive:J?.interactive===!0,provider:typeof J?.provider==="string"?J.provider:"hub",model:typeof J?.model==="string"?J.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof J?.teamName==="string"?J.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??J?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??J?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??J?.enableTeams===!0,prompt:typeof J?.prompt==="string"?J.prompt:void 0,metadata:J,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,hookPath:typeof J?.hookPath==="string"?J.hookPath:void 0}}function a1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;return J.version===1&&typeof J.sessionId==="string"?JSON.parse(JSON.stringify(J)):void 0}function TT($){let J=a1($?.snapshot);if(J)return HZ(J);let Q=$?.session;return Q?CY(Q):void 0}function NY($,J,Q){let Z=Q?.workspaceRoot?.trim()||J.config.workspaceRoot||J.config.cwd;return P0.parse({version:1,session_id:$,source:J.source??z0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:v8(Q?.status),interactive:J.interactive===!0,provider:J.config.providerId,model:J.config.modelId,cwd:Q?.cwd?.trim()||J.config.cwd,workspace_root:Z,team_name:J.config.teamName,enable_tools:J.config.enableTools,enable_spawn:J.config.enableSpawnAgent,enable_teams:J.config.enableAgentTeams,prompt:J.prompt?.trim()||void 0,metadata:J.sessionMetadata&&Object.keys(J.sessionMetadata).length>0?J.sessionMetadata:void 0})}function wY($,J){return P0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??J.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class b${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new h8;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,J){this.clientContext=J,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd},this.defaultCapabilities=L0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new U1({...this.clientOptions,url:$})}async replaceClient($){let J=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(J.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!UY($,"session.create"))return!1;let J=await zY({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!J)return!1;return await this.replaceClient(J),!0}registerPlannedSession($,J,Q){if(this.sessionCapabilities.set($,J),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let J=this.resolveCapabilities($),Q=qY($.localRuntime,J),Z=$.config.sessionId?.trim()||_Y(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:M2({...$.config,sessionId:Z}),metadata:{...$.sessionMetadata??{},source:$.source??z0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:M2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Z,J,Q.handlers);let j;try{j=await W()}catch(V){if(this.cleanupPlannedSession(Z),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Z,J,Q.handlers);try{j=await W()}catch(H){throw this.cleanupPlannedSession(Z),H}}else throw V}let f=a1(j.payload?.snapshot),X=j.payload?.session,Y=(f?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Z),Error("Hub runtime did not return a session id.");if(Y!==Z)this.cleanupPlannedSession(Z),this.registerPlannedSession(Y,J,Q.handlers);return{sessionId:Y,manifest:f?wY(f,$):NY(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let Z=$.start,W=Z?this.resolveCapabilities(Z):void 0,j=Z?qY(Z.localRuntime,W??{}):{manifest:[],handlers:new Map},f=Z?Z.config.sessionId?.trim()||_Y():void 0;if(f&&W)this.sessionCapabilities.set(f,W);if(f&&j.handlers.size>0)this.sessionClientContributionHandlers.set(f,j.handlers),this.ensureSessionSubscription(f);let X;try{X=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.config.workspaceRoot?.trim()||Z.config.cwd,cwd:Z.config.cwd??$.cwd,sessionConfig:M2({...Z.config,sessionId:f}),metadata:{...Z.sessionMetadata??{},source:Z.source??z0.CORE,provider:Z.config.providerId,model:Z.config.modelId,enableTools:Z.config.enableTools,enableSpawn:Z.config.enableSpawnAgent,enableTeams:Z.config.enableAgentTeams,teamName:Z.config.teamName,prompt:Z.prompt,interactive:Z.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Z.localRuntime?.configExtensions?{configExtensions:Z.localRuntime.configExtensions}:{}},toolPolicies:M2(Z.toolPolicies)}:{}},J)}catch(K){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error(K)}let Y=a1(X.payload?.snapshot),V=X.payload?.session,H=(Y?.sessionId??V?.sessionId)?.trim();if(Q&&!H){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error("Hub checkpoint restore returned no session id")}if(H&&f&&H!==f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&j.handlers.size>0)this.sessionClientContributionHandlers.set(H,j.handlers);if(H)this.ensureSessionSubscription(H);let B=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,A=X.payload?.checkpoint;if(!A)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:Y?wY(Y,Z??{}):NY(H,Z??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:B,checkpoint:A}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(J.payload?.prompts)?J.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,updated:J.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,removed:J.payload?.removed===!0}}async getAccumulatedUsage($){let J=await this.client.command("session.get",{includeSnapshot:!0},$),Q=a1(J.payload?.snapshot);if(Q){let f=Q.usage?{...Q.usage}:void 0,X=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return f||X?{usage:f,aggregateUsage:X}:void 0}let Z=J.payload?.session,W=PY(Z?.usage),j=PY(Z?.aggregateUsage);return W||j?{usage:W,aggregateUsage:j}:void 0}async abort($,J){await this.client.command("run.abort",{sessionId:$,reason:SY(J)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,J]of this.sessionSubscriptions){J();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(O$(Q))return;throw Q}return TT(J.payload)}async listSessions($=100){let J=await this.client.command("session.list",{limit:$}),Q=Array.isArray(J.payload?.snapshots)?J.payload.snapshots.flatMap((W)=>{let j=a1(W);return j?[HZ(j)]:[]}):[];if(Q.length>0)return Q;return(J.payload?.sessions??[]).map(CY)}async listSettings($){let J=await this.client.command("settings.list",TY($));if(!J.ok)throw Error(e6(J,"settings.list"));return J.payload?.snapshot}async toggleSetting($){let J=await this.client.command("settings.toggle",TY($));if(!J.ok)throw Error(e6(J,"settings.toggle"));return{snapshot:J.payload?.snapshot,changedTypes:Array.isArray(J.payload?.changedTypes)?J.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,J){let Q={...J.metadata??{}};if(typeof J.prompt==="string")Q.prompt=J.prompt;if(typeof J.title==="string")Q.title=J.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw LY(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(e6(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:J,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(e6(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,J){return this.events.subscribe($,J)}ensureSessionSubscription($){let J=$.trim();if(!J||this.sessionSubscriptions.has(J))return;let Q=this.client.subscribe((Z)=>{this.handleHubEvent(Z)},{sessionId:J});this.sessionSubscriptions.set(J,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let J=$.trim();if(!J)return;this.sessionSubscriptions.get(J)?.(),this.sessionSubscriptions.delete(J),this.agentDoneEmittedForCurrentRunBySession.delete(J)}resolveCapabilities($){return L0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:OT($.payload)}})}handleHubEvent($){let J=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!J)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(J);let Q=a1($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",Z=$.payload?.redacted===!0;if(!Q&&!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:Z}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:J,payload:$.payload});return}case"usage.updated":{let Q=_T($.payload);this.events.emit({type:"agent_event",payload:{sessionId:J,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:J,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"tool",toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Q=a1($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:J,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:J,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=a1($.payload?.snapshot),Z=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:J,payload:{...$.payload,reason:Z}}),Q?.interactive===!0&&Z0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:J,reason:Z,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,J,Q){try{LY(this.telemetry,{component:"core",operation:$,error:J,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let J=$.sessionId?.trim();if(!J)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let Z=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Z)return;let j=this.sessionClientContributionHandlers.get(J)?.get(W);if(!j){await this.client.command("capability.respond",{requestId:Z,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${J}.`},J).catch(()=>{});return}let f=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Z,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Z,payload:V},J).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let V=await j({payload:f,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!0,payload:V},J)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!1,error:V instanceof Error?V.message:String(V)},J)}finally{this.activeCapabilityAbortControllers.delete(Z)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let J=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!J)return;let Q=this.activeCapabilityAbortControllers.get(J);if(!Q)return;Q.abort(UT($.payload.error))}async handleApprovalRequested($){let J=$.sessionId?.trim();if(!J)return;let Q=this.sessionCapabilities.get(J)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let Z=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Z||!W||!j)return;let f=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=RT($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:J,toolCallId:W,toolName:j,toolInput:X});let Y=await Promise.resolve(Q({sessionId:J,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:J,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:j,input:X,policy:f})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Z,approved:Y.approved,reason:Y.reason},J).catch(()=>{})}}class $J extends b${constructor($){super({url:T2($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as MT,mkdirSync as qT}from"node:fs";import{join as PT}from"node:path";import{asBool as c8,asOptionalString as Q1,asString as R1,ensureSessionSchema as NT,loadSqliteDb as wT,nowIso as JJ,toBoolInt as u8}from"@cline/shared/db";import{resolveDbDataDir as ST}from"@cline/shared/storage";class s1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??ST()}init(){this.getRawDb()}ensureSessionsDir(){if(!MT(this.sessionsDirPath))qT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return PT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=wT(this.sessionDbPath());return NT($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}create($){let J=JJ();this.run(`INSERT OR REPLACE INTO sessions (
441
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,B0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,B0(),$)}}class S8{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new w8({dbPath:$.dbPath});let J=$.specs;this.reconciler=new g9({store:this.store,specs:J}),this.materializer=new T8({store:this.store}),this.eventIngress=new q9({store:this.store,logger:$.logger}),this.runner=new M8({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:J,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new m9({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let Z=$.logger;if(Z)if(Z.error)Z.error("cron.watcher.failed",{error:Q});else Z.log("cron.watcher.failed",{error:Q})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}import{readdir as F_,readFile as lX}from"node:fs/promises";import{join as pX}from"node:path";import{formatDisplayUserInput as D_,normalizeUserInput as U_}from"@cline/shared";import{resolveSessionDataDir as rX}from"@cline/shared/storage";import{mkdirSync as f_,writeFileSync as X_}from"node:fs";import{dirname as Y_}from"node:path";import{normalizeUserInput as V_}from"@cline/shared";import{nanoid as H_}from"nanoid";import{nanoid as W_}from"nanoid";function C8($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function d6($,J){let Q=C8($),Z=C8(J),W=`${Q}__${Z}`;return W.length>180?W.slice(0,180):W}function d9($,J){let Q=C8($),Z=C8(J);return`${Q}__teamtask__${Z}__${W_(6)}`}function y8($){let Q=$.indexOf("__teamtask__");if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+12),j=W.lastIndexOf("__");if(j<=0)return null;let f=W.slice(0,j),X=W.slice(j+2);if(!Z||!f||!X)return null;return{rootSessionId:Z,agentId:f,teamTaskId:X}}function l6($){if(y8($))return null;let J="__",Q=$.indexOf(J);if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+J.length);if(!Z||!W)return null;return{rootSessionId:Z,agentId:W}}function l9($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let J=String($.reason??"").toLowerCase();if(J.includes("cancel")||J.includes("abort")||J.includes("interrupt"))return"cancelled";if(J.includes("fail")||J.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as i}from"zod";var j_=i.enum($Q),P0=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:j_,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 kX($){if(!$)return!1;return Object.values($).some((J)=>typeof J==="function")}function r9($,J){let Q=[...$??[],...J??[]];if(Q.length===0)return;let Z=[],W=new Set;for(let j of Q){if(W.has(j.name))continue;W.add(j.name),Z.push(j)}return Z}function IX($){return JSON.stringify($,(J,Q)=>{if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};return Q})}function G1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function p9($,J){let Q={...$};Q.id=G1(Q.id)??H_();let Z=Q.modelInfo&&typeof Q.modelInfo==="object"?{...Q.modelInfo}:void 0,W={id:G1(Z?.id)??G1(Q.modelId)??G1(J?.id),provider:G1(Z?.provider)??G1(Q.providerId)??G1(J?.provider),family:G1(Z?.family)??G1(J?.family)};if(delete Q.providerId,delete Q.modelId,W.id&&W.provider)Q.modelInfo={id:W.id,provider:W.provider,...W.family?{family:W.family}:{}};else delete Q.modelInfo;return Q}function p6($){return $.map((J)=>p9(J))}function r6($,J,Q=[]){let Z=$.map((Y,V)=>{let H=Q[V],A=H?.role===Y.role&&JSON.stringify(H.content)===JSON.stringify(Y.content)?{...H,...Y}:{...Y};return p9(A)}),W=Q.length,j=[];for(let Y=W;Y<Z.length;Y+=1)if(Z[Y]?.role==="assistant")j.push(Y);if(j.length===0){let Y=[...Z].reverse().findIndex((V)=>V.role==="assistant");if(Y===-1)return Z;j.push(Z.length-1-Y)}let f=j[j.length-1],X=j.some((Y)=>Z[Y]?.metrics);for(let Y of j){let V=Z[Y],H=V.metrics;if(!H&&Y===f&&!X){let B=J.usage;H={inputTokens:B.inputTokens,outputTokens:B.outputTokens,cacheReadTokens:B.cacheReadTokens??0,cacheWriteTokens:B.cacheWriteTokens??0,cost:B.totalCost}}Z[Y]={...p9(V,{id:J.model.id,provider:J.model.provider,family:J.model.info?.family}),...H?{metrics:H}:{},ts:V.ts??J.endedAt.getTime()}}return Z}function E8($){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 B_=120;function N$($){let J=$?.trim();return J?J.slice(0,B_):void 0}function i9($){let J=V_($??"").trim();if(!J)return;return N$(J.split(`
442
+ `)[0]?.trim())}function u1($){if(!$)return;let J={...$},Q=N$(typeof J.title==="string"?J.title:void 0);if(Q)J.title=Q;else delete J.title;return Object.keys(J).length>0?J:void 0}function b8($){let J=u1($.metadata)??{},Q=$.title!==void 0?N$($.title):i9($.prompt);if(Q)J.title=Q;return Object.keys(J).length>0?J:void 0}function n9($){let J=y8($);if(J)return{agent:"teammate",sessionId:J.rootSessionId,taskType:"team"};let Q=l6($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function a9($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:p6($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function xX($,J,Q){f_(Y_($),{recursive:!0}),X_($,`${JSON.stringify(a9({updatedAt:J,context:Q,messages:[]}),null,2)}
443
+ `,"utf8")}function gX($,J){return P0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:J?.endedAt??$.endedAt??void 0,exit_code:J?.exitCode??$.exitCode??void 0,status:J?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:J?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function mX($,J,Q){let Z=0;while(!0){let W=await $();if(W===void 0)return{updated:!1};let j=await J(W);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Z+=1,Z>=Q)return j;continue}return j}}import{existsSync as A_}from"node:fs";import{readFile as K_}from"node:fs/promises";import{formatDisplayUserInput as vX}from"@cline/shared";class h8{listeners=new Set;subscribe($,J){let Q={listener:$,sessionId:J?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let J=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J)continue;Q.listener($)}}get size(){return this.listeners.size}}async function d1($){let J=$?.trim();if(!J||!A_(J))return[];try{let Q=(await K_(J,"utf8")).trim();if(!Q)return[];let Z=JSON.parse(Q);if(Array.isArray(Z))return cX(Z);if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let W=Z.messages;if(Array.isArray(W))return cX(W)}return[]}catch{return[]}}function G_($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:vX($.content)};return{...$,content:$.content.map((J)=>{if(J.type!=="text"||typeof J.text!=="string")return J;return{...J,text:vX(J.text)}})}}function cX($){return $.map(G_)}function s9($){return $?{...$}:void 0}async function uX($,J){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await J.queueSpawnRequest($);let Z=await J.upsertSubagentSessionFromHook($);if(!Z)return;await J.appendSubagentHookAudit(Z,$),await J.applySubagentStatus(Z,$)}function k8($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function I0($){let J=k8($);if(!J)return;return J.toLowerCase()==="unknown"?void 0:J}function i6($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function R_($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function t9($){let J=$??200;return Number.isFinite(J)?Math.max(0,Math.floor(J)):200}function z_($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function L_($){return $.isSubagent!==!0&&!k8($.parentSessionId)}function __($){let J=$.match(/\d{13,}/g);if(!J||J.length===0)return 0;let Q=0;for(let Z of J){let W=Number.parseInt(Z,10);if(Number.isFinite(W)&&W>Q)Q=W}return Q}function e9($){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 O_($){let J=t9($);if(J===0)return[];let Q=rX(),W=(await F_(Q,{withFileTypes:!0}).catch(()=>[])).filter((f)=>f.isDirectory()).map((f)=>({entry:f,recency:__(f.name.trim())})).sort((f,X)=>X.recency-f.recency||X.entry.name.localeCompare(f.entry.name));return(await Promise.all(W.map(async({entry:f})=>{let X=f.name.trim();if(!X)return;let Y=pX(Q,X,`${X}.json`),V=await lX(Y,"utf8").catch(()=>{return});if(!V)return;let H;try{H=JSON.parse(V)}catch{return}let B=P0.safeParse(H);if(!B.success)return;return e9(B.data)}))).filter((f)=>Boolean(f)).sort((f,X)=>X.startedAt.localeCompare(f.startedAt)).slice(0,J)}async function T_($,J,Q){let Z=t9(J);if(Z===0)return await $.listSessions(0),[];let W=Q.includeSubagents?Z:z_(Z),j=await $.listSessions(W);return(Q.includeSubagents?j:j.filter(L_)).slice(0,Z)}function M_($){if(typeof $==="string")return $.trim();let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q;if(Z.type!=="text")continue;let W=Z.text?.trim();if(W)J.push(W)}return J.join(`
444
+ `).trim()}function dX($){return $.replace(/\s+/g," ").trim()}function q_($,J){if($.length<=J)return $;return`${$.slice(0,Math.max(0,J-3)).trimEnd()}...`}function P_($){for(let J of["user","assistant"])for(let Q of $){if(Q.role!==J)continue;let Z=dX(M_(Q.content));if(!Z)continue;let W=J==="user"?dX(D_(Z)):Z,j=U_(W.split(`
445
+ `)[0]??W);return q_(j,50)}return}function N_($){let J=0;for(let Q of $)J+=i6(Q.metrics?.cost)??0;return J}function w_($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=I0(W.modelInfo?.provider);if(!Q)Q=I0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function S_($){return I0($?.provider)??I0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function C_($){return I0($?.model)??I0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function o9($,J){let Q=R_($.metadata),Z=k8(J?.title)??k8(Q?.title),W=i6(J?.totalCost)??i6(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:I0(J?.provider)??I0($.provider)??S_(Q)??"",model:I0(J?.model)??I0($.model)??C_(Q)??"",metadata:j}}function y_($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function E_($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!y_(Q)}async function b_($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return E_(Q,Z)?{...Q,status:"idle"}:Q}))}async function h_($,J){return await Promise.all(J.map(async(Q)=>{let Z=o9(Q),W=Boolean(k8(Z.metadata?.title)),j=Boolean(I0(Z.provider)),f=Boolean(I0(Z.model)),X=i6(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=w_(V),B=N_(V);return o9(Q,{title:W?void 0:P_(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||B<=0?void 0:B})}))}async function $Z($,J={}){let Q=t9(J.limit),Z=J.includeSubagents===!0,W=await T_($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await O_(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await b_($,X);if(J.hydrate===!1)return Y.map((V)=>o9(V));return await h_($,Y)}async function k_($){let J=$.trim();if(!J)return;let Q=pX(rX(),J,`${J}.json`),Z=await lX(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=P0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function I_($,J={}){let Q=new Map;return await $Z({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map(E8)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await k_(W);return await d1(j)}},J)}import{captureSdkError as NH}from"@cline/shared";import{createSessionId as xO,isHubProtocolCompatible as gO,resolveClineBuildEnv as mO,resolveHubCommandTimeoutMs as vO}from"@cline/shared";import{spawn as KO}from"node:child_process";import{closeSync as GO,mkdirSync as FO,openSync as DO}from"node:fs";import{basename as UO,dirname as RO,join as zO}from"node:path";import{fileURLToPath as LO}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as _O,isHubDaemonProcess as XY,isHubProtocolCompatible as OO,resolveClineBuildEnv as YY,withResolvedClineBuildEnv as TO}from"@cline/shared";import{createHash as x_,randomBytes as g_}from"node:crypto";import{existsSync as m_}from"node:fs";import{chmod as v_,mkdir as JZ,readFile as oX,rm as QZ,writeFile as tX}from"node:fs/promises";import{dirname as eX,join as ZZ}from"node:path";import{resolveClineDataDir as x8,resolveClineDir as ug}from"@cline/shared/storage";var nX="0.0.48";var I8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:nX,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var c_="CLINE_HUB_DISCOVERY_PATH",u_="CLINE_HUB_BUILD_ID",aX=30000,d_=15000,l_=100;function p_($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function r_($){return x_("sha256").update($).digest("hex").slice(0,12)}function i_($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function $Y(){return g_(32).toString("hex")}function n_($){return new Promise((J)=>setTimeout(J,$))}function a_($){return`${$}.lock`}async function s_($){try{let J=JSON.parse(await oX(ZZ($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function sX($){await QZ($,{recursive:!0,force:!0}).catch(()=>{return})}function JY(){return process.env[u_]?.trim()||String(I8.version)}function w$($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${r_($)}`,Q=process.env[c_]?.trim()||ZZ(x8(),"locks","hub","owners",`${p_(J)}.json`);return{ownerId:J,discoveryPath:Q}}function lg($=`hub-${Date.now().toString(36)}`){return w$($)}async function A0($){try{let J=JSON.parse(await oX($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function QY($,J){await JZ(eX($),{recursive:!0}),await QZ($,{force:!0}).catch(()=>{return}),await tX($,`${JSON.stringify(J,null,2)}
446
+ `,{encoding:"utf8",mode:384}),await v_($,384)}async function n0($){await QZ($,{force:!0}).catch(()=>{return})}async function ZY($,J){let Q=a_($);await JZ(eX(Q),{recursive:!0});let Z=Date.now()+d_;while(!0)try{await JZ(Q,{recursive:!1}),await tX(ZZ(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
447
+ `,"utf8");try{return await J()}finally{await sX(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await s_(Q),X=f?Date.now()-Date.parse(f.acquiredAt):aX+1;if(!f||!i_(f.pid)||X>aX){await sX(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await n_(l_)}}async function S$($,J){try{let Q=await fetch(J?.authToken?o_($):WY($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function F1($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function WY($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function o_($){let J=new URL(WY($));return J.pathname="/status",J.toString()}function pg($){return m_($)}import{CLINE_HUB_DEV_PORT as t_,CLINE_HUB_PORT as e_,resolveClineBuildEnv as $O}from"@cline/shared";var JO="CLINE_HUB_HOST",QO="CLINE_HUB_PORT",ZO="CLINE_HUB_PATHNAME",WO="127.0.0.1",jO=e_,fO="/hub";function jY($){return $O($)==="development"?t_:jO}function XO($={}){return($.env??process.env)[JO]?.trim()||WO}function n6($={}){let Q=($.env??process.env)[QO]?.trim();if(!Q)return jY($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return jY($);return Z}function YO($={}){return($.env??process.env)[ZO]?.trim()||fO}function l1($={},J={}){return{host:$.host??XO(J),port:$.port??n6(J),pathname:$.pathname??YO(J)}}import{join as VO}from"node:path";var HO="shared:cline",BO="CLINE_HUB_DISCOVERY_PATH",AO="hub-production";function tg($){let J=T$($.trim());return w$(`workspace:${J||$.trim()}`)}function D1($=HO){return w$($)}function p1(){return{ownerId:AO,discoveryPath:process.env[BO]?.trim()||VO(x8(),"locks","hub","production.json")}}var MO=8000,qO=200,PO=3000,NO=100,wO=[100,250,500,1000,2000],SO="--cline-hub-daemon";function CO($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function yO(){try{let $=zO(x8(),"logs","hub-daemon.log");return FO(RO($),{recursive:!0}),{fd:DO($,"a"),logPath:$}}catch{return}}function VY(){return YY()==="production"?p1():D1()}function C$($){return OO($).compatible}function fY($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function y$($,J){try{return await S$($,{authToken:J})}catch{return}}async function EO($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await y$($))?.url)return!0;await new Promise((W)=>setTimeout(W,NO))}return!1}async function a6($,J){if(await WZ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await EO($.url,PO);return await n0(J).catch(()=>{return}),Q}async function g8($,J){if(C$($))return!0;return a6($,J)}async function HY($){if(YY()!=="production")return;let J=D1();if(J.discoveryPath===$.discoveryPath)return;let Q=await A0(J.discoveryPath);if(Q?.url)await a6(Q,J.discoveryPath);else await n0(J.discoveryPath).catch(()=>{return})}function bO(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return LO(new URL(`./entry.${$}`,import.meta.url))}function hO($,J){let Q=bO(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=UO(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[SO]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...CO(J)],cwd:$,env:{...TO(process.env),CLINE_NO_INTERACTIVE:"1",[_O]:"1"}}}function kO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function IO($,J={}){if(XY())return;let Q=hO($,J),Z=yO();try{KO(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)GO(Z.fd)}}async function s6($,J={}){for(let Q=0;;Q++)try{IO($,J);return}catch(Z){let W=wO[Q];if(!kO(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function BY($,J={}){if(XY())return;let Q=VY(),Z=l1(J),W=F1(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;HY(Q).catch(()=>{return}).then(()=>A0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await a6(f,Q.discoveryPath)&&!j)return}else{let H=await y$(f.url,f.authToken);if(H?.url&&C$(H)&&await r1(H.url,{authToken:f.authToken}))return;if(H?.url)await g8({...H,authToken:f.authToken},Q.discoveryPath);else await n0(Q.discoveryPath).catch(()=>{return})}let Y=await y$(W);if(Y?.url){if(C$(Y)){if(!j||!X)return}else if(!await g8({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await s6($,V)}).catch(()=>{})}async function Vm($,J={}){let Q=VY(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=l1(J),j=F1(W.host,W.port,W.pathname),f=(K)=>{if(!Z)O2(K.url,K.authToken);return K};await HY(Q).catch(()=>{return});let X=await A0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await a6(X,Q.discoveryPath);else{let G=await y$(X.url,K);if(G?.url&&C$(G)&&await r1(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await g8({...G,authToken:K},Q.discoveryPath);else await n0(Q.discoveryPath).catch(()=>{return})}}let V=await y$(j);if(V?.url){let K=fY(V,X,j);if(C$(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await g8(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await s6($,B);let A=Date.now()+MO;while(Date.now()<A){let K=await A0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await y$(K.url,K.authToken);if(R?.url&&C$(R)&&await r1(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await y$(j);if(G?.url&&!C$(G)){let R=fY(G,K,j);if(!await g8(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,qO))}throw Error("Timed out waiting for detached hub startup.")}function t6(){return mO()==="production"?p1():D1()}function cO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function DY($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return DY($.data);return String($)}function uO($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function AY($){let J=$,Q=uO(J.reason);return new x0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:jZ,{closeCode:J.code,closeReason:Q||void 0})}function dO($,J){if($ instanceof x0)return $;if($ instanceof Error)return new x0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new x0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new x0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new x0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var lO=8000,pO=200,KY="*",GY=8000,rO="cline-hub-auth.",UY=new Map,RY=new Set,iO=3000,nO=3000,aO=100,jZ="Hub connection closed",sO=250,oO=5000,FY=0.5;class x0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function tO($){return $ instanceof x0}class o6 extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function zY($,J){return $ instanceof o6&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function LY($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=YZ($.toString());return Q?UY.get(Q):void 0}function eO($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function YZ($){if(!eO($))return;let J=new URL(T2($));return J.search="",J.hash="",J.toString()}function fZ($){let J=YZ($);return!!J&&RY.has(J)}function O2($,J){let Q=YZ($);if(Q){if(RY.add(Q),J?.trim())UY.set(Q,J)}return $}class U1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new x0("hub_connection_closed",jZ);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),J=this.options.authToken?.trim()||LY($);$.hash="";let Z=new(cO())($.toString(),J?[`${rO}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new x0("hub_connect_timeout",`Timed out connecting to hub after ${GY}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},GY);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=dO(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=AY(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(DY(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=AY(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=xO("hubreq_"),j=vO($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new o6($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(W,{resolve:(B)=>{if(H)clearTimeout(H);Y(B)},reject:(B)=>{if(H)clearTimeout(H);V(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===_8){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new _$(Y,X.error.message)}throw new o6($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!fZ(this.currentUrl)||!tO($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await m8({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(sO*2**this.reconnectAttempt,oO),J=Math.round($*(1-FY)+Math.random()*$*FY);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!fZ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await m8({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 x0("hub_connection_closed",jZ),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new x0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??KY}subscriptionSessionIdFromKey($){return $===KY?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function T2($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function r1($,J){let Q=new U1({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function XZ($,J){let Q=T2($),Z=await S$(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!gO(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await r1(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function $T($){let J=Date.now()+lO;while(Date.now()<J){let Q=await A0($.discoveryPath);if(Q?.url){let Z=await XZ(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return O2(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,pO))}return}async function JT($){let J=Date.now()+nO;while(Date.now()<J){if(!(await S$($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,aO))}return!1}function QT($,J){try{return T2($)===T2(J)}catch{return!1}}function ZT($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function WT($,J,Q){let Z=new U1({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:iO});return!ZT(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function VZ($={}){if($.endpoint?.trim()){let W=await XZ($.endpoint);return W.status==="compatible"?W.url:void 0}let J=t6(),Q=await A0(J.discoveryPath);if(!Q?.url)return;let Z=await XZ(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return O2(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await n0(J.discoveryPath).catch(()=>{return});return}async function m8($={}){let J=await VZ($);if(J&&await r1(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=t6();return await s6($.workspaceRoot??process.cwd()),await $T(Q)}async function WZ($,J){let Q=new URL($),Z=J?.trim()||LY(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function jT($=t6()){let J=await A0($.discoveryPath);if(!J?.url)return!1;try{if(await WZ(J.url,J.authToken))return!0}catch{}return!1}async function _Y($){if(!fZ($.url))return;let J=t6(),Q=await A0(J.discoveryPath);if(!Q?.url||!QT(Q.url,$.url))return;if(!await WT(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await jT())return;if(!await JT(Q.url))return;return await n0(J.discoveryPath).catch(()=>{return}),await m8({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as OY,createSessionId as TY,HUB_CHECKPOINT_CAPABILITY as VT,HUB_COMPACTION_CAPABILITY as HT,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as BT,HUB_HOOK_CAPABILITY_PREFIX as AT,HUB_MISTAKE_LIMIT_CAPABILITY as KT,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as GT,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as FT,isHubToolExecutorName as DT}from"@cline/shared";function fT($){return $?JSON.parse(JSON.stringify($)):void 0}function XT($){return $?JSON.parse(JSON.stringify($)):void 0}function YT($){let J=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Z=(Array.isArray(J?.history)?J.history:[]).filter((f)=>!!f&&typeof f==="object"&&!Array.isArray(f)).flatMap((f)=>{let X=typeof f.ref==="string"?f.ref.trim():"",Y=Number(f.createdAt),V=Number(f.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...f.kind==="stash"||f.kind==="commit"?{kind:f.kind}:{}}]}),W=Z.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Z.length===0)return;return{...j?{enabled:j}:{},...W?{latest:W}:{},history:Z}}function i1($){let{session:J}=$,Q=fT(J.metadata);return{version:1,sessionId:J.sessionId,source:J.source,status:J.status,createdAt:J.startedAt,updatedAt:J.updatedAt,endedAt:J.endedAt??null,exitCode:J.exitCode??null,interactive:J.interactive,workspace:{cwd:J.cwd,root:J.workspaceRoot},model:{providerId:J.provider,modelId:J.model},capabilities:{enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams},lineage:{...J.parentSessionId?{parentSessionId:J.parentSessionId}:{},...J.parentAgentId?{parentAgentId:J.parentAgentId}:{},...J.agentId?{agentId:J.agentId}:{},...J.conversationId?{conversationId:J.conversationId}:{},isSubagent:J.isSubagent},...J.teamName?{team:{name:J.teamName}}:{},...J.prompt?{prompt:J.prompt}:{},...Q?{metadata:Q}:{},...J.messagesPath?{artifacts:{messagesPath:J.messagesPath}}:{},...$.messages?{messages:XT($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Z=YT(Q);return Z?{checkpoint:Z}:{}})()}}function HZ($){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 M2($){if(!$)return;return JSON.parse(JSON.stringify($))}var UT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function MY($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function qY($){if(!$)return;let{userInstructionService:J,...Q}=$;return JSON.parse(JSON.stringify(Q))}function PY($){let J=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof J.agentId==="string"?J.agentId:"",conversationId:typeof J.conversationId==="string"?J.conversationId:"",iteration:typeof J.iteration==="number"?J.iteration:0,metadata:J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}}function E$($,J,Q){$.manifest.push(J),$.handlers.set(J.capabilityName,Q)}function NY($,J){let Q={manifest:[],handlers:new Map};for(let W of Object.keys(J.toolExecutors??{}).filter(DT)){let j=J.toolExecutors?.[W];if(typeof j!=="function")continue;E$(Q,{kind:"toolExecutor",executor:W,capabilityName:`${GT}${W}`},async({payload:f,abortSignal:X})=>{let Y=Array.isArray(f.args)?[...f.args]:[],V={...PY(f.context),signal:X};return{result:await j(...Y,V)}})}for(let W of $?.extraTools??[])E$(Q,{kind:"tool",name:W.name,description:W.description,inputSchema:M2(W.inputSchema)??{},...W.lifecycle?{lifecycle:M2(W.lifecycle)}:{},capabilityName:`${BT}${W.name}`},async({payload:j,abortSignal:f,progress:X})=>{let Y={...PY(j.context),signal:f};return{result:await W.execute(j.input,{...Y,emitUpdate:(H)=>{X({update:H})}})}});let Z=$?.hooks;if(Z)for(let W of UT){let j=Z[W];if(typeof j!=="function")continue;E$(Q,{kind:"hook",name:W,capabilityName:`${AT}${W}`},async({payload:f})=>({control:await j(f.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;E$(Q,{kind:"compaction",capabilityName:HT,config:MY($.compaction)},async({payload:j})=>({result:await W(j.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;E$(Q,{kind:"checkpoint",capabilityName:VT,config:MY($.checkpoint)},async({payload:j})=>({result:await W(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;E$(Q,{kind:"mistakeLimit",capabilityName:KT},async({payload:j})=>({result:await W(j.context)}))}if($?.userInstructionService){let W=$.userInstructionService;E$(Q,{kind:"userInstructionService",capabilityName:FT},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Q}function yY($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let J=$.message;if(typeof J==="string"&&J.trim())return J.trim()}return}function RT($){return yY($)??"Capability request was cancelled."}function zT($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function LT($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function _T($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=typeof J.inputTokens==="number"?J.inputTokens:void 0,Z=typeof J.outputTokens==="number"?J.outputTokens:void 0;if(Q===void 0||Z===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:typeof J.cacheReadTokens==="number"?J.cacheReadTokens:0,cacheWriteTokens:typeof J.cacheWriteTokens==="number"?J.cacheWriteTokens:0,totalCost:typeof J.totalCost==="number"?J.totalCost:0}}function wY($){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 BZ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function n1($,J){return BZ($?.[J])??0}function OT($){let J=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Z=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=Z?.teamRole==="teammate"||Z?.teamRole==="lead"?Z.teamRole:void 0;return{event:{type:"usage",agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,inputTokens:n1(J,"inputTokens"),outputTokens:n1(J,"outputTokens"),cacheReadTokens:n1(J,"cacheReadTokens"),cacheWriteTokens:n1(J,"cacheWriteTokens"),cost:BZ(J?.totalCost),totalInputTokens:n1(Q,"inputTokens"),totalOutputTokens:n1(Q,"outputTokens"),totalCacheReadTokens:n1(Q,"cacheReadTokens"),totalCacheWriteTokens:n1(Q,"cacheWriteTokens"),totalCost:BZ(Q?.totalCost)},teamAgentId:typeof Z?.teamAgentId==="string"?Z.teamAgentId:void 0,teamRole:W}}function TT($){let J=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??J?.finishReason,Z=LT(Q)?Q:Q==="failed"?"error":"completed",W=_T($?.usage??J?.usage);return{type:"done",reason:Z,text:typeof $?.text==="string"?$.text:typeof J?.text==="string"?J.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof J?.iterations==="number"?J.iterations:0,usage:W}}function e6($,J){return $.error?.message??`hub command failed: ${J}`}function v8($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function EY($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof J?.agentId==="string"?J.agentId:void 0),parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,isSubagent:typeof J?.isSubagent==="boolean"?J.isSubagent:!1,source:typeof J?.source==="string"?J.source:z0.CORE,pid:typeof J?.pid==="number"?J.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:v8($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:v8($.status)==="completed"?0:v8($.status)==="failed"?1:void 0,status:v8($.status),interactive:J?.interactive===!0,provider:typeof J?.provider==="string"?J.provider:"hub",model:typeof J?.model==="string"?J.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof J?.teamName==="string"?J.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??J?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??J?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??J?.enableTeams===!0,prompt:typeof J?.prompt==="string"?J.prompt:void 0,metadata:J,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,hookPath:typeof J?.hookPath==="string"?J.hookPath:void 0}}function a1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;return J.version===1&&typeof J.sessionId==="string"?JSON.parse(JSON.stringify(J)):void 0}function MT($){let J=a1($?.snapshot);if(J)return HZ(J);let Q=$?.session;return Q?EY(Q):void 0}function SY($,J,Q){let Z=Q?.workspaceRoot?.trim()||J.config.workspaceRoot||J.config.cwd;return P0.parse({version:1,session_id:$,source:J.source??z0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:v8(Q?.status),interactive:J.interactive===!0,provider:J.config.providerId,model:J.config.modelId,cwd:Q?.cwd?.trim()||J.config.cwd,workspace_root:Z,team_name:J.config.teamName,enable_tools:J.config.enableTools,enable_spawn:J.config.enableSpawnAgent,enable_teams:J.config.enableAgentTeams,prompt:J.prompt?.trim()||void 0,metadata:J.sessionMetadata&&Object.keys(J.sessionMetadata).length>0?J.sessionMetadata:void 0})}function CY($,J){return P0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??J.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class b${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new h8;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,J){this.clientContext=J,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd},this.defaultCapabilities=L0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new U1({...this.clientOptions,url:$})}async replaceClient($){let J=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(J.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!zY($,"session.create"))return!1;let J=await _Y({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!J)return!1;return await this.replaceClient(J),!0}registerPlannedSession($,J,Q){if(this.sessionCapabilities.set($,J),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let J=this.resolveCapabilities($),Q=NY($.localRuntime,J),Z=$.config.sessionId?.trim()||TY(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:M2({...$.config,sessionId:Z}),metadata:{...$.sessionMetadata??{},source:$.source??z0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:M2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Z,J,Q.handlers);let j;try{j=await W()}catch(V){if(this.cleanupPlannedSession(Z),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Z,J,Q.handlers);try{j=await W()}catch(H){throw this.cleanupPlannedSession(Z),H}}else throw V}let f=a1(j.payload?.snapshot),X=j.payload?.session,Y=(f?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Z),Error("Hub runtime did not return a session id.");if(Y!==Z)this.cleanupPlannedSession(Z),this.registerPlannedSession(Y,J,Q.handlers);return{sessionId:Y,manifest:f?CY(f,$):SY(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let Z=$.start,W=Z?this.resolveCapabilities(Z):void 0,j=Z?NY(Z.localRuntime,W??{}):{manifest:[],handlers:new Map},f=Z?Z.config.sessionId?.trim()||TY():void 0;if(f&&W)this.sessionCapabilities.set(f,W);if(f&&j.handlers.size>0)this.sessionClientContributionHandlers.set(f,j.handlers),this.ensureSessionSubscription(f);let X;try{X=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.config.workspaceRoot?.trim()||Z.config.cwd,cwd:Z.config.cwd??$.cwd,sessionConfig:M2({...Z.config,sessionId:f}),metadata:{...Z.sessionMetadata??{},source:Z.source??z0.CORE,provider:Z.config.providerId,model:Z.config.modelId,enableTools:Z.config.enableTools,enableSpawn:Z.config.enableSpawnAgent,enableTeams:Z.config.enableAgentTeams,teamName:Z.config.teamName,prompt:Z.prompt,interactive:Z.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Z.localRuntime?.configExtensions?{configExtensions:Z.localRuntime.configExtensions}:{}},toolPolicies:M2(Z.toolPolicies)}:{}},J)}catch(K){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error(K)}let Y=a1(X.payload?.snapshot),V=X.payload?.session,H=(Y?.sessionId??V?.sessionId)?.trim();if(Q&&!H){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error("Hub checkpoint restore returned no session id")}if(H&&f&&H!==f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&j.handlers.size>0)this.sessionClientContributionHandlers.set(H,j.handlers);if(H)this.ensureSessionSubscription(H);let B=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,A=X.payload?.checkpoint;if(!A)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:Y?CY(Y,Z??{}):SY(H,Z??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:B,checkpoint:A}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(J.payload?.prompts)?J.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,updated:J.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,removed:J.payload?.removed===!0}}async getAccumulatedUsage($){let J=await this.client.command("session.get",{includeSnapshot:!0},$),Q=a1(J.payload?.snapshot);if(Q){let f=Q.usage?{...Q.usage}:void 0,X=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return f||X?{usage:f,aggregateUsage:X}:void 0}let Z=J.payload?.session,W=wY(Z?.usage),j=wY(Z?.aggregateUsage);return W||j?{usage:W,aggregateUsage:j}:void 0}async abort($,J){await this.client.command("run.abort",{sessionId:$,reason:yY(J)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,J]of this.sessionSubscriptions){J();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(O$(Q))return;throw Q}return MT(J.payload)}async listSessions($=100){let J=await this.client.command("session.list",{limit:$}),Q=Array.isArray(J.payload?.snapshots)?J.payload.snapshots.flatMap((W)=>{let j=a1(W);return j?[HZ(j)]:[]}):[];if(Q.length>0)return Q;return(J.payload?.sessions??[]).map(EY)}async listSettings($){let J=await this.client.command("settings.list",qY($));if(!J.ok)throw Error(e6(J,"settings.list"));return J.payload?.snapshot}async toggleSetting($){let J=await this.client.command("settings.toggle",qY($));if(!J.ok)throw Error(e6(J,"settings.toggle"));return{snapshot:J.payload?.snapshot,changedTypes:Array.isArray(J.payload?.changedTypes)?J.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,J){let Q={...J.metadata??{}};if(typeof J.prompt==="string")Q.prompt=J.prompt;if(typeof J.title==="string")Q.title=J.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw OY(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(e6(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:J,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(e6(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,J){return this.events.subscribe($,J)}ensureSessionSubscription($){let J=$.trim();if(!J||this.sessionSubscriptions.has(J))return;let Q=this.client.subscribe((Z)=>{this.handleHubEvent(Z)},{sessionId:J});this.sessionSubscriptions.set(J,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let J=$.trim();if(!J)return;this.sessionSubscriptions.get(J)?.(),this.sessionSubscriptions.delete(J),this.agentDoneEmittedForCurrentRunBySession.delete(J)}resolveCapabilities($){return L0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:TT($.payload)}})}handleHubEvent($){let J=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!J)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(J);let Q=a1($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",Z=$.payload?.redacted===!0;if(!Q&&!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:Z}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:J,payload:$.payload});return}case"usage.updated":{let Q=OT($.payload);this.events.emit({type:"agent_event",payload:{sessionId:J,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:J,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"tool",toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Q=a1($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:J,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:J,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=a1($.payload?.snapshot),Z=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:J,payload:{...$.payload,reason:Z}}),Q?.interactive===!0&&Z0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:J,reason:Z,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,J,Q){try{OY(this.telemetry,{component:"core",operation:$,error:J,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let J=$.sessionId?.trim();if(!J)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let Z=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Z)return;let j=this.sessionClientContributionHandlers.get(J)?.get(W);if(!j){await this.client.command("capability.respond",{requestId:Z,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${J}.`},J).catch(()=>{});return}let f=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Z,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Z,payload:V},J).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let V=await j({payload:f,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!0,payload:V},J)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!1,error:V instanceof Error?V.message:String(V)},J)}finally{this.activeCapabilityAbortControllers.delete(Z)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let J=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!J)return;let Q=this.activeCapabilityAbortControllers.get(J);if(!Q)return;Q.abort(RT($.payload.error))}async handleApprovalRequested($){let J=$.sessionId?.trim();if(!J)return;let Q=this.sessionCapabilities.get(J)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let Z=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Z||!W||!j)return;let f=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=zT($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:J,toolCallId:W,toolName:j,toolInput:X});let Y=await Promise.resolve(Q({sessionId:J,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:J,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:j,input:X,policy:f})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Z,approved:Y.approved,reason:Y.reason},J).catch(()=>{})}}class $J extends b${constructor($){super({url:T2($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as qT,mkdirSync as PT}from"node:fs";import{join as NT}from"node:path";import{asBool as c8,asOptionalString as Q1,asString as R1,ensureSessionSchema as wT,loadSqliteDb as ST,nowIso as JJ,toBoolInt as u8}from"@cline/shared/db";import{resolveDbDataDir as CT}from"@cline/shared/storage";class s1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??CT()}init(){this.getRawDb()}ensureSessionsDir(){if(!qT(this.sessionsDirPath))PT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return NT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=ST(this.sessionDbPath());return wT($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}create($){let J=JJ();this.run(`INSERT OR REPLACE INTO sessions (
448
448
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
449
449
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
450
450
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
@@ -454,25 +454,25 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
454
454
  enable_tools, enable_spawn, enable_teams,
455
455
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
456
456
  prompt, metadata_json, hook_path, messages_path, updated_at
457
- FROM sessions WHERE session_id = ?`,[$]);if(!J)return;return{sessionId:R1(J.session_id),source:R1(J.source),pid:Number(J.pid??0),startedAt:R1(J.started_at),endedAt:J.ended_at??null,exitCode:J.exit_code??null,status:R1(J.status),interactive:c8(J.interactive),provider:R1(J.provider),model:R1(J.model),cwd:R1(J.cwd),workspaceRoot:R1(J.workspace_root),teamName:Q1(J.team_name),enableTools:c8(J.enable_tools),enableSpawn:c8(J.enable_spawn),enableTeams:c8(J.enable_teams),parentSessionId:Q1(J.parent_session_id),parentAgentId:Q1(J.parent_agent_id),agentId:Q1(J.agent_id),conversationId:Q1(J.conversation_id),isSubagent:c8(J.is_subagent),prompt:Q1(J.prompt),metadata:(()=>{let Q=Q1(J.metadata_json);if(!Q)return;try{let Z=JSON.parse(Q);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return})(),hookPath:Q1(J.hook_path),messagesPath:Q1(J.messages_path),updatedAt:Q1(J.updated_at)??JJ()}}list($=200){let J=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Q=[];for(let Z of J){let W=this.get(R1(Z.session_id));if(W)Q.push(W)}return Q}delete($,J=!1){let Q=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}}q2();import{existsSync as CZ,mkdirSync as EM,readFileSync as iY,renameSync as bM,writeFileSync as hM}from"node:fs";import{join as nY}from"node:path";import{resolveSessionDataDir as kM}from"@cline/shared/storage";import{dirname as CM}from"node:path";import{nanoid as yM}from"nanoid";import{execFile as uT}from"node:child_process";import{promisify as dT}from"node:util";var lT=dT(uT);function AZ($,J){$?.log(J,{severity:"warn"})}function pT($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))return;let Q=J;if(!Q.latest||!Array.isArray(Q.history))return;let Z=Q.latest,W=Q.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")return;return{latest:Z,history:W}}async function h$($,J){let Q=await lT("git",["-C",$,...J],{windowsHide:!0});return{stdout:Q.stdout.trim(),stderr:Q.stderr.trim()}}async function KZ($,J){if(!$)return;let Q=`refs/cline/checkpoints/${J}/`;try{let{stdout:Z}=await h$($,["for-each-ref","--format=%(refname)",Q]),W=Z.trim().split(`
458
- `).filter(Boolean);await Promise.allSettled(W.map((j)=>h$($,["update-ref","-d",j])))}catch{}}async function yY($,J,Q){if(!$||Q.length===0)return;await Promise.allSettled(Q.map((Z)=>h$($,["update-ref",`refs/cline/checkpoints/${J}/${Z.runCount}`,Z.ref])))}function rT($,J){let Q=$.findIndex((Z)=>Z.runCount===J.runCount);if(Q<0)return[...$,J];return $.map((Z,W)=>W===Q?J:Z)}function EY($){let J=$.initialRunCount??0,Q,Z=async()=>{if(Q!==void 0)return Q;try{Q=(await h$($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Q=!1}return Q},W=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:J});if(!await Z())return;let j=async(V)=>{try{let B=(await h$($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:J,kind:"commit"}}catch(H){AZ($.logger,`${V}: ${H instanceof Error?H.message:String(H)}`);return}},f=`cline checkpoint session=${$.sessionId} run=${J}`,X="";try{X=(await h$($.cwd,["stash","create",f])).stdout.trim()}catch(V){return AZ($.logger,`Checkpoint snapshot failed: ${V instanceof Error?V.message:String(V)}`),j("Checkpoint HEAD fallback failed")}if(!X)return j("Checkpoint HEAD fallback failed");let Y=`refs/cline/checkpoints/${$.sessionId}/${J}`;try{await h$($.cwd,["update-ref",Y,X])}catch(V){AZ($.logger,`Checkpoint store failed: ${V instanceof Error?V.message:String(V)}`);return}return{ref:X,createdAt:Date.now(),runCount:J,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;J+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||J<1)return;let f=await W();if(!f)return;let X=await $.readSessionMetadata(),Y=pT(X);if(Y?.latest.ref===f.ref)return;let V=rT(Y?.history??[],f);await $.writeSessionMetadata({...X??{},checkpoint:{latest:f,history:V}});return}}}import{existsSync as ZJ,mkdirSync as iT,readdirSync as nT,rmdirSync as aT,rmSync as sT,unlinkSync as oT}from"node:fs";import{dirname as bY,join as QJ}from"node:path";function s(){return new Date().toISOString()}function d8($){if(!$||!ZJ($))return;try{oT($)}catch{}}function tT($){let J=y8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:`${J.agentId}__${J.teamTaskId}`};let Q=l6($);if(Q)return{rootSessionId:Q.rootSessionId,fileStem:Q.agentId};return{rootSessionId:$,fileStem:$}}class GZ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return QJ(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let J=this.sessionArtifactsDir($);if(!ZJ(J))iT(J,{recursive:!0});return J}sessionMessagesPath($){return QJ(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,J=!1){let Q=J?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return QJ(Q,`${$}.json`)}removeSessionDirIfEmpty($){let J=this.sessionArtifactsDir($),Q=this.ensureSessionsDir();while(J.startsWith(Q)&&J!==Q){if(!ZJ(J)){J=bY(J);continue}try{if(nT(J).length>0)break;aT(J)}catch{break}J=bY(J)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!ZJ($))return;try{sT($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,J,Q){let{rootSessionId:Z,fileStem:W}=tT($),j=this.sessionArtifactsDir(Z);return{messagesPath:QJ(j,`${W}.messages.json`)}}}import{appendFileSync as eT,existsSync as $M,mkdirSync as hY,readFileSync as JM,writeFileSync as kY}from"node:fs";import{dirname as IY,join as QM}from"node:path";import{ensureHookLogDir as ZM}from"@cline/shared/storage";class FZ{adapter;messagesArtifactUploader;logger;artifacts;constructor($,J,Q){this.adapter=$;this.messagesArtifactUploader=J;this.logger=Q;this.artifacts=new GZ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,J,Q){kX(J,Q,n9($))}writeSessionManifest($,J){hY(IY($),{recursive:!0}),kY($,`${JSON.stringify(P0.parse(J),null,2)}
459
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let J=this.artifacts.sessionManifestPath($,!1);if(!$M(J))return{path:J};try{return{path:J,manifest:P0.parse(JSON.parse(JM(J,"utf8")))}}catch{return{path:J}}}async resolveArtifactPath($,J,Q){let W=(await this.adapter.getSession($))?.[J];return typeof W==="string"&&W.trim().length>0?W:Q($)}async persistSessionMessages($,J,Q){let Z=await this.resolveArtifactPath($,"messagesPath",(f)=>this.artifacts.sessionMessagesPath(f)),W=a9({updatedAt:s(),context:n9($),messages:J,systemPrompt:Q}),j=`${JSON.stringify(W,null,2)}
460
- `;if(hY(IY(Z),{recursive:!0}),kY(Z,j,"utf8"),!this.messagesArtifactUploader)return;try{let f=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Z,contents:j,row:f})}catch(f){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:f})}}appendStaleSessionHookLog($,J,Q,Z,W){let f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??QM(ZM(),"hooks.jsonl");eT(f,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Z,sessionId:J,pid:Q,source:W})}
461
- `,"utf8")}}import{appendFileSync as WM}from"node:fs";import{join as jM}from"node:path";import{resolveRootSessionId as xY}from"@cline/shared";import{ensureHookLogDir as fM}from"@cline/shared/storage";import{z as DZ}from"zod";var XM="subagent",YM=DZ.looseObject({task:DZ.string().optional(),systemPrompt:DZ.string().optional()});class WJ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,J,Q,Z){this.adapter=$;this.manifestStore=J;this.toPersistedMessages=Q;this.heartbeatLogIntervalMs=Z}teamTaskQueueKey($,J){return`${$}::${J}`}activeTeamTaskSessionId($,J){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,J))?.at(-1)}buildSubsessionRow($,J){return{sessionId:J.sessionId,source:XM,pid:process.ppid,startedAt:J.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:J.parentSessionId,parentAgentId:J.parentAgentId,agentId:J.agentId,conversationId:J.conversationId??null,isSubagent:!0,prompt:J.prompt,metadata:b8({prompt:J.prompt}),hookPath:"",messagesPath:J.messagesPath,updatedAt:J.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let J=xY($.sessionContext);if(!J)return;let Q=YM.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:J,parentAgentId:$.agent_id,task:Q.success?Q.data.task:void 0,systemPrompt:Q.success?Q.data.systemPrompt:void 0})}async upsertSubagentSession($){let J=$.rootSessionId;if(!J)return;let Q=await this.adapter.getSession(J);if(!Q)return;let Z=d6(J,$.agentId),W=await this.adapter.getSession(Z),j=s(),f=this.manifestStore.artifacts.subagentArtifactPaths(Z,$.agentId,this.activeTeamTaskSessionId(J,$.parentAgentId)),X=$.prompt??W?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(J,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!W)return await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:j,...f})),this.manifestStore.initializeMessagesFile(Z,f.messagesPath,j),Z;return await this.adapter.updateSession({sessionId:Z,setRunning:!0,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:W.prompt??X??null,metadata:b8({metadata:W.metadata??void 0,prompt:W.prompt??X??null}),expectedStatusLock:W.statusLock}),Z}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let J=xY($.sessionContext);if(!J)return;if($.hookName==="session_shutdown"){let Q=d6(J,$.agent_id);return await this.adapter.getSession(Q)?Q:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:J})}async applySubagentStatus($,J){await this.applySubagentStatusBySessionId($,l9(J))}async applySubagentStatusBySessionId($,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=Z0(J)?null:s(),W=Z0(J)?null:J==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:J,endedAt:Z,exitCode:W,expectedStatusLock:Q.statusLock})}async applyStatusToRunningChildSessions($,J){if(!$)return;let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Z of Q)await this.applySubagentStatusBySessionId(Z.sessionId,J)}async onTeamTaskStart($,J,Q){let Z=await this.adapter.getSession($);if(!Z)return;let W=d9($,J),j=s(),{messagesPath:f}=this.manifestStore.artifacts.subagentArtifactPaths(W,J);await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:W,parentSessionId:$,parentAgentId:"lead",agentId:J,prompt:Q||`Team task for ${J}`,startedAt:j,messagesPath:f})),this.manifestStore.initializeMessagesFile(W,f,j);let X=this.teamTaskQueueKey($,J),Y=this.teamTaskSessionsByAgent.get(X)??[];Y.push(W),this.teamTaskSessionsByAgent.set(X,Y)}async onTeamTaskEnd($,J,Q,Z,W,j){let f=this.teamTaskQueueKey($,J),X=this.teamTaskSessionsByAgent.get(f);if(!X||X.length===0)return;let Y=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(f);if(!Y)return;let V=W?.messages??j,H=this.toPersistedMessages(V,W,j);if(H)await this.manifestStore.persistSessionMessages(Y,H);await this.applySubagentStatusBySessionId(Y,Q),this.teamTaskLastHeartbeatBySession.delete(Y),this.teamTaskLastProgressLineBySession.delete(Y)}async onTeamTaskProgress($,J,Q,Z){let W=this.teamTaskQueueKey($,J),j=this.teamTaskSessionsByAgent.get(W)?.[0];if(!j)return;let f=Q.trim();if(!f)return;let X=Z?.kind??"progress";if(X==="heartbeat"){let V=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(V-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,V)}let Y=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${f}`:`[progress] ${f}`;if(this.teamTaskLastProgressLineBySession.get(j)===Y)return;this.teamTaskLastProgressLineBySession.set(j,Y)}async handleSubAgentStart($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;await this.applySubagentStatusBySessionId(Q,"running")}async handleSubAgentEnd($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;if(J.error){await this.applySubagentStatusBySessionId(Q,"failed");return}let Z=this.toPersistedMessages(J.agentResult?.messages,J.agentResult);if(Z)await this.manifestStore.persistSessionMessages(Q,Z);let W=J.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Q,W==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Q=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??jM(fM(),"hooks.jsonl");WM(Q,`${JSON.stringify({ts:s(),...$})}
462
- `,"utf8")}}import{formatUserInputBlock as SM}from"@cline/shared";import{existsSync as VM,readdirSync as HM,readFileSync as BM}from"node:fs";import{basename as gY,extname as AM,join as KM}from"node:path";import{resolveAgentConfigSearchPaths as GM}from"@cline/shared/storage";import vY from"yaml";import{z as _0}from"zod";var cY=_0.object({name:_0.string().trim().min(1),description:_0.string().trim().min(1),tools:_0.union([_0.string(),_0.array(_0.string())]).optional(),skills:_0.union([_0.string(),_0.array(_0.string())]).optional(),providerId:_0.string().trim().min(1).optional(),modelId:_0.string().trim().min(1).optional(),maxIterations:_0.number().int().positive().optional()});function FM($){let J=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!J)throw Error("Missing YAML frontmatter block in agent config file.");let Q=J[0].length,Z=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Z.lastIndex=Q;let W,j=Array.from($.matchAll(Z)).filter((f)=>f.index>=Q);for(let f of j){let X=f.index,Y=$.slice(Q,X);try{let V=vY.parse(Y);if(!V||typeof V!=="object"||Array.isArray(V))continue;cY.parse(V);let H=$.slice(X+f[0].length);W={frontmatter:Y,body:H}}catch{}}if(W)return W;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function mY($){if($===void 0)return;let J=Array.isArray($)?$:$.split(",");return Array.from(new Set(J.map((Q)=>Q.trim()).filter((Q)=>Q.length>0)))}function DM($){return $.trim().toLowerCase()}function UM($){let J=AM($).toLowerCase();return J===".yml"||J===".yaml"}function UZ($,J={}){let{frontmatter:Q,body:Z}=FM($),W=vY.parse(Q);if(!W||typeof W!=="object"||Array.isArray(W))throw Error("Agent config frontmatter must be a YAML mapping.");let j=cY.parse(W),f=Z.trim();if(!f)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:mY(j.tools),skills:mY(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:f,path:J.path}}function jJ($){let J=$.searchPaths??GM($.workspaceRoot),Q=new Map,Z=[];for(let j of J.filter(Boolean)){if(!VM(j))continue;let f;try{f=HM(j,{withFileTypes:!0})}catch(X){Z.push({path:j,error:X instanceof Error?X:Error(String(X))});continue}for(let X of f){if(!X.isFile()||!UM(X.name))continue;let Y=KM(j,X.name);try{let V=BM(Y,"utf8"),H=UZ(V,{path:Y}),B=DM(H.name);if(!Q.has(B))Q.set(B,H)}catch(V){Z.push({path:Y,error:V instanceof Error?V:Error(String(V))})}}}return{configs:Array.from(Q.values()).sort((j,f)=>(j.path?gY(j.path):j.name).localeCompare(f.path?gY(f.path):f.name)),errors:Z}}import{createTool as RM,zodToJsonSchema as zM}from"@cline/shared";import{z as uY}from"zod";var RZ="subagent_",fJ=64,LM=uY.object({prompt:uY.string().trim().min(1).describe("Task for the subagent to perform")});function _M($){let J="",Q=!0;for(let Z of $.trim().toLowerCase()){let W=Z.charCodeAt(0);if(!(W>=97&&W<=122||W>=48&&W<=57||Z==="_")||Z==="_"){if(!Q)J+="_",Q=!0;continue}J+=Z,Q=!1}return Q?J.slice(0,-1):J}function OM($){let J=2166136261;for(let Q=0;Q<$.length;Q++)J^=$.charCodeAt(Q),J=Math.imul(J,16777619);return(J>>>0).toString(36)}function zZ($){let J=_M($)||"agent",Q=OM($).slice(0,6),Z=`${RZ}${J}`;if(Z.length<=fJ)return Z;let W=fJ-RZ.length-Q.length-1,j=J.slice(0,Math.max(1,W));return`${RZ}${j}_${Q}`.slice(0,fJ)}function LZ($){let J=new Set,Q=[];for(let Z of[...$].sort((W,j)=>W.name.localeCompare(j.name))){let W=zZ(Z.name),j=W,f=2;while(J.has(j)){let X=`_${f++}`,Y=Math.max(1,fJ-X.length);j=`${W.slice(0,Y)}${X}`}J.add(j),Q.push({toolName:j,config:Z})}return Q}function TM($,J){return{...$,providerId:J.providerId??$.providerId,modelId:J.modelId??$.modelId,maxIterations:J.maxIterations??$.maxIterations}}function XJ($){return LZ($.agents).map(({toolName:J,config:Q})=>{return RM({name:J,description:`Use the "${Q.name}" subagent: ${Q.description}`,inputSchema:zM(LM),execute:async(W,j)=>{let f=$.configProvider.getRuntimeConfig(),X=G2(TM(f,Q)),Y=$.createSubAgentTools?await $.createSubAgentTools(Q,W,j):[],V=F2({kind:"subagent",prompt:Q.systemPrompt,configProvider:X,tools:Y,maxIterations:Q.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=V.getAgentId(),B=V.getConversationId(),A=j.agentId,K={systemPrompt:Q.systemPrompt,task:W.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:B,parentAgentId:A,input:K})}catch{}try{let G=await V.run(W.prompt),R={text:G.text,iterations:G.iterations,finishReason:G.finishReason,usage:{inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,result:R,agentResult:G})}catch{}return R}catch(G){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,error:G instanceof Error?G:Error(String(G))})}catch{}throw G}},timeoutMs:300000,retryable:!1})})}function Z1(){return new Date().toISOString()}function dY($,J){if(J<=0)return 0;return Math.round($/J*100)}function MM($,J){let Q=new Set;for(let W of J)if(W.status==="reviewed")Q.add(`${W.outcomeId}:${W.section}`);let Z=new Set;for(let W of $){if(W.status==="finalized")continue;for(let j of W.requiredSections)if(!Q.has(`${W.id}:${j}`))Z.add(`${W.id}:${j}`)}return[...Z].sort((W,j)=>W.localeCompare(j))}function YJ($,J){let Q={idle:0,running:0,stopped:0},Z={pending:0,in_progress:0,blocked:0,completed:0},W={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},f={draft:0,reviewed:0,rejected:0},X=0,Y=0;for(let D of J.members)if(Q[D.status]+=1,D.role==="lead")X+=1;else Y+=1;let V=[],H=[],B=J.tasks.filter((D)=>D.status==="completed").length,A=new Map(J.tasks.map((D)=>[D.id,D]));for(let D of J.tasks){if(Z[D.status]+=1,D.status==="blocked"){V.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((F)=>{return A.get(F)?.status==="completed"}))H.push(D.id)}let K=[],G,R=0;for(let D of J.runs){if(W[D.status]+=1,D.status==="queued"||D.status==="running")K.push(D.id);let U=D.startedAt.getTime();if(U>=R)R=U,G=D.id}for(let D of J.outcomes)j[D.status]+=1;for(let D of J.outcomeFragments)f[D.status]+=1;return{teamName:$,updatedAt:Z1(),members:{total:J.members.length,byStatus:Q,leadCount:X,teammateCount:Y},tasks:{total:J.tasks.length,byStatus:Z,blockedTaskIds:V,readyTaskIds:H,completionPct:dY(B,J.tasks.length)},runs:{total:J.runs.length,byStatus:W,activeRunIds:K,latestRunId:G},outcomes:{total:J.outcomes.length,byStatus:j,finalizedPct:dY(j.finalized,J.outcomes.length),missingRequiredSections:MM(J.outcomes,J.outcomeFragments)},fragments:{total:J.outcomeFragments.length,byStatus:f}}}function VJ($){let{event:J}=$;switch(J.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),taskId:J.task.id,agentId:J.task.assignee??J.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),outcomeId:J.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),outcomeId:J.fragment.outcomeId,fragmentId:J.fragment.id,agentId:J.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),taskId:J.message.taskId,agentId:J.message.fromAgentId,message:J.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),taskId:J.entry.taskId,agentId:J.entry.agentId,message:J.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),agentId:J.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1()}}import{sanitizeFileName as qM,TeamMessageType as b}from"@cline/shared";import{nanoid as PM}from"nanoid";import{TeamMessageType as Pv}from"@cline/shared";function _Z($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function lY($,J){return $?.status==="stopped"&&_Z(J)}var NM=600000,pY="recovered_queued";function wM($){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.
457
+ FROM sessions WHERE session_id = ?`,[$]);if(!J)return;return{sessionId:R1(J.session_id),source:R1(J.source),pid:Number(J.pid??0),startedAt:R1(J.started_at),endedAt:J.ended_at??null,exitCode:J.exit_code??null,status:R1(J.status),interactive:c8(J.interactive),provider:R1(J.provider),model:R1(J.model),cwd:R1(J.cwd),workspaceRoot:R1(J.workspace_root),teamName:Q1(J.team_name),enableTools:c8(J.enable_tools),enableSpawn:c8(J.enable_spawn),enableTeams:c8(J.enable_teams),parentSessionId:Q1(J.parent_session_id),parentAgentId:Q1(J.parent_agent_id),agentId:Q1(J.agent_id),conversationId:Q1(J.conversation_id),isSubagent:c8(J.is_subagent),prompt:Q1(J.prompt),metadata:(()=>{let Q=Q1(J.metadata_json);if(!Q)return;try{let Z=JSON.parse(Q);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return})(),hookPath:Q1(J.hook_path),messagesPath:Q1(J.messages_path),updatedAt:Q1(J.updated_at)??JJ()}}list($=200){let J=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Q=[];for(let Z of J){let W=this.get(R1(Z.session_id));if(W)Q.push(W)}return Q}delete($,J=!1){let Q=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}}q2();import{existsSync as CZ,mkdirSync as bM,readFileSync as aY,renameSync as hM,writeFileSync as kM}from"node:fs";import{join as sY}from"node:path";import{resolveSessionDataDir as IM}from"@cline/shared/storage";import{dirname as yM}from"node:path";import{nanoid as EM}from"nanoid";import{execFile as dT}from"node:child_process";import{promisify as lT}from"node:util";var pT=lT(dT);function AZ($,J){$?.log(J,{severity:"warn"})}function rT($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))return;let Q=J;if(!Q.latest||!Array.isArray(Q.history))return;let Z=Q.latest,W=Q.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")return;return{latest:Z,history:W}}async function h$($,J){let Q=await pT("git",["-C",$,...J],{windowsHide:!0});return{stdout:Q.stdout.trim(),stderr:Q.stderr.trim()}}async function KZ($,J){if(!$)return;let Q=`refs/cline/checkpoints/${J}/`;try{let{stdout:Z}=await h$($,["for-each-ref","--format=%(refname)",Q]),W=Z.trim().split(`
458
+ `).filter(Boolean);await Promise.allSettled(W.map((j)=>h$($,["update-ref","-d",j])))}catch{}}async function bY($,J,Q){if(!$||Q.length===0)return;await Promise.allSettled(Q.map((Z)=>h$($,["update-ref",`refs/cline/checkpoints/${J}/${Z.runCount}`,Z.ref])))}function iT($,J){let Q=$.findIndex((Z)=>Z.runCount===J.runCount);if(Q<0)return[...$,J];return $.map((Z,W)=>W===Q?J:Z)}function hY($){let J=$.initialRunCount??0,Q,Z=async()=>{if(Q!==void 0)return Q;try{Q=(await h$($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Q=!1}return Q},W=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:J});if(!await Z())return;let j=async(V)=>{try{let B=(await h$($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:J,kind:"commit"}}catch(H){AZ($.logger,`${V}: ${H instanceof Error?H.message:String(H)}`);return}},f=`cline checkpoint session=${$.sessionId} run=${J}`,X="";try{X=(await h$($.cwd,["stash","create",f])).stdout.trim()}catch(V){return AZ($.logger,`Checkpoint snapshot failed: ${V instanceof Error?V.message:String(V)}`),j("Checkpoint HEAD fallback failed")}if(!X)return j("Checkpoint HEAD fallback failed");let Y=`refs/cline/checkpoints/${$.sessionId}/${J}`;try{await h$($.cwd,["update-ref",Y,X])}catch(V){AZ($.logger,`Checkpoint store failed: ${V instanceof Error?V.message:String(V)}`);return}return{ref:X,createdAt:Date.now(),runCount:J,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;J+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||J<1)return;let f=await W();if(!f)return;let X=await $.readSessionMetadata(),Y=rT(X);if(Y?.latest.ref===f.ref)return;let V=iT(Y?.history??[],f);await $.writeSessionMetadata({...X??{},checkpoint:{latest:f,history:V}});return}}}import{existsSync as ZJ,mkdirSync as nT,readdirSync as aT,rmdirSync as sT,rmSync as oT,unlinkSync as tT}from"node:fs";import{dirname as kY,join as QJ}from"node:path";function s(){return new Date().toISOString()}function d8($){if(!$||!ZJ($))return;try{tT($)}catch{}}function eT($){let J=y8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:`${J.agentId}__${J.teamTaskId}`};let Q=l6($);if(Q)return{rootSessionId:Q.rootSessionId,fileStem:Q.agentId};return{rootSessionId:$,fileStem:$}}class GZ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return QJ(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let J=this.sessionArtifactsDir($);if(!ZJ(J))nT(J,{recursive:!0});return J}sessionMessagesPath($){return QJ(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,J=!1){let Q=J?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return QJ(Q,`${$}.json`)}removeSessionDirIfEmpty($){let J=this.sessionArtifactsDir($),Q=this.ensureSessionsDir();while(J.startsWith(Q)&&J!==Q){if(!ZJ(J)){J=kY(J);continue}try{if(aT(J).length>0)break;sT(J)}catch{break}J=kY(J)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!ZJ($))return;try{oT($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,J,Q){let{rootSessionId:Z,fileStem:W}=eT($),j=this.sessionArtifactsDir(Z);return{messagesPath:QJ(j,`${W}.messages.json`)}}}import{appendFileSync as $M,existsSync as JM,mkdirSync as IY,readFileSync as QM,writeFileSync as xY}from"node:fs";import{dirname as gY,join as ZM}from"node:path";import{ensureHookLogDir as WM}from"@cline/shared/storage";class FZ{adapter;messagesArtifactUploader;logger;artifacts;constructor($,J,Q){this.adapter=$;this.messagesArtifactUploader=J;this.logger=Q;this.artifacts=new GZ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,J,Q){xX(J,Q,n9($))}writeSessionManifest($,J){IY(gY($),{recursive:!0}),xY($,`${JSON.stringify(P0.parse(J),null,2)}
459
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let J=this.artifacts.sessionManifestPath($,!1);if(!JM(J))return{path:J};try{return{path:J,manifest:P0.parse(JSON.parse(QM(J,"utf8")))}}catch{return{path:J}}}async resolveArtifactPath($,J,Q){let W=(await this.adapter.getSession($))?.[J];return typeof W==="string"&&W.trim().length>0?W:Q($)}async persistSessionMessages($,J,Q){let Z=await this.resolveArtifactPath($,"messagesPath",(f)=>this.artifacts.sessionMessagesPath(f)),W=a9({updatedAt:s(),context:n9($),messages:J,systemPrompt:Q}),j=`${JSON.stringify(W,null,2)}
460
+ `;if(IY(gY(Z),{recursive:!0}),xY(Z,j,"utf8"),!this.messagesArtifactUploader)return;try{let f=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Z,contents:j,row:f})}catch(f){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:f})}}appendStaleSessionHookLog($,J,Q,Z,W){let f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??ZM(WM(),"hooks.jsonl");$M(f,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Z,sessionId:J,pid:Q,source:W})}
461
+ `,"utf8")}}import{appendFileSync as jM}from"node:fs";import{join as fM}from"node:path";import{resolveRootSessionId as mY}from"@cline/shared";import{ensureHookLogDir as XM}from"@cline/shared/storage";import{z as DZ}from"zod";var YM="subagent",VM=DZ.looseObject({task:DZ.string().optional(),systemPrompt:DZ.string().optional()});class WJ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,J,Q,Z){this.adapter=$;this.manifestStore=J;this.toPersistedMessages=Q;this.heartbeatLogIntervalMs=Z}teamTaskQueueKey($,J){return`${$}::${J}`}activeTeamTaskSessionId($,J){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,J))?.at(-1)}buildSubsessionRow($,J){return{sessionId:J.sessionId,source:YM,pid:process.ppid,startedAt:J.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:J.parentSessionId,parentAgentId:J.parentAgentId,agentId:J.agentId,conversationId:J.conversationId??null,isSubagent:!0,prompt:J.prompt,metadata:b8({prompt:J.prompt}),hookPath:"",messagesPath:J.messagesPath,updatedAt:J.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let J=mY($.sessionContext);if(!J)return;let Q=VM.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:J,parentAgentId:$.agent_id,task:Q.success?Q.data.task:void 0,systemPrompt:Q.success?Q.data.systemPrompt:void 0})}async upsertSubagentSession($){let J=$.rootSessionId;if(!J)return;let Q=await this.adapter.getSession(J);if(!Q)return;let Z=d6(J,$.agentId),W=await this.adapter.getSession(Z),j=s(),f=this.manifestStore.artifacts.subagentArtifactPaths(Z,$.agentId,this.activeTeamTaskSessionId(J,$.parentAgentId)),X=$.prompt??W?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(J,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!W)return await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:j,...f})),this.manifestStore.initializeMessagesFile(Z,f.messagesPath,j),Z;return await this.adapter.updateSession({sessionId:Z,setRunning:!0,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:W.prompt??X??null,metadata:b8({metadata:W.metadata??void 0,prompt:W.prompt??X??null}),expectedStatusLock:W.statusLock}),Z}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let J=mY($.sessionContext);if(!J)return;if($.hookName==="session_shutdown"){let Q=d6(J,$.agent_id);return await this.adapter.getSession(Q)?Q:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:J})}async applySubagentStatus($,J){await this.applySubagentStatusBySessionId($,l9(J))}async applySubagentStatusBySessionId($,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=Z0(J)?null:s(),W=Z0(J)?null:J==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:J,endedAt:Z,exitCode:W,expectedStatusLock:Q.statusLock})}async applyStatusToRunningChildSessions($,J){if(!$)return;let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Z of Q)await this.applySubagentStatusBySessionId(Z.sessionId,J)}async onTeamTaskStart($,J,Q){let Z=await this.adapter.getSession($);if(!Z)return;let W=d9($,J),j=s(),{messagesPath:f}=this.manifestStore.artifacts.subagentArtifactPaths(W,J);await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:W,parentSessionId:$,parentAgentId:"lead",agentId:J,prompt:Q||`Team task for ${J}`,startedAt:j,messagesPath:f})),this.manifestStore.initializeMessagesFile(W,f,j);let X=this.teamTaskQueueKey($,J),Y=this.teamTaskSessionsByAgent.get(X)??[];Y.push(W),this.teamTaskSessionsByAgent.set(X,Y)}async onTeamTaskEnd($,J,Q,Z,W,j){let f=this.teamTaskQueueKey($,J),X=this.teamTaskSessionsByAgent.get(f);if(!X||X.length===0)return;let Y=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(f);if(!Y)return;let V=W?.messages??j,H=this.toPersistedMessages(V,W,j);if(H)await this.manifestStore.persistSessionMessages(Y,H);await this.applySubagentStatusBySessionId(Y,Q),this.teamTaskLastHeartbeatBySession.delete(Y),this.teamTaskLastProgressLineBySession.delete(Y)}async onTeamTaskProgress($,J,Q,Z){let W=this.teamTaskQueueKey($,J),j=this.teamTaskSessionsByAgent.get(W)?.[0];if(!j)return;let f=Q.trim();if(!f)return;let X=Z?.kind??"progress";if(X==="heartbeat"){let V=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(V-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,V)}let Y=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${f}`:`[progress] ${f}`;if(this.teamTaskLastProgressLineBySession.get(j)===Y)return;this.teamTaskLastProgressLineBySession.set(j,Y)}async handleSubAgentStart($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;await this.applySubagentStatusBySessionId(Q,"running")}async handleSubAgentEnd($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;if(J.error){await this.applySubagentStatusBySessionId(Q,"failed");return}let Z=this.toPersistedMessages(J.agentResult?.messages,J.agentResult);if(Z)await this.manifestStore.persistSessionMessages(Q,Z);let W=J.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Q,W==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Q=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??fM(XM(),"hooks.jsonl");jM(Q,`${JSON.stringify({ts:s(),...$})}
462
+ `,"utf8")}}import{formatUserInputBlock as CM}from"@cline/shared";import{existsSync as HM,readdirSync as BM,readFileSync as AM}from"node:fs";import{basename as vY,extname as KM,join as GM}from"node:path";import{resolveAgentConfigSearchPaths as FM}from"@cline/shared/storage";import uY from"yaml";import{z as _0}from"zod";var dY=_0.object({name:_0.string().trim().min(1),description:_0.string().trim().min(1),tools:_0.union([_0.string(),_0.array(_0.string())]).optional(),skills:_0.union([_0.string(),_0.array(_0.string())]).optional(),providerId:_0.string().trim().min(1).optional(),modelId:_0.string().trim().min(1).optional(),maxIterations:_0.number().int().positive().optional()});function DM($){let J=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!J)throw Error("Missing YAML frontmatter block in agent config file.");let Q=J[0].length,Z=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Z.lastIndex=Q;let W,j=Array.from($.matchAll(Z)).filter((f)=>f.index>=Q);for(let f of j){let X=f.index,Y=$.slice(Q,X);try{let V=uY.parse(Y);if(!V||typeof V!=="object"||Array.isArray(V))continue;dY.parse(V);let H=$.slice(X+f[0].length);W={frontmatter:Y,body:H}}catch{}}if(W)return W;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function cY($){if($===void 0)return;let J=Array.isArray($)?$:$.split(",");return Array.from(new Set(J.map((Q)=>Q.trim()).filter((Q)=>Q.length>0)))}function UM($){return $.trim().toLowerCase()}function RM($){let J=KM($).toLowerCase();return J===".yml"||J===".yaml"}function UZ($,J={}){let{frontmatter:Q,body:Z}=DM($),W=uY.parse(Q);if(!W||typeof W!=="object"||Array.isArray(W))throw Error("Agent config frontmatter must be a YAML mapping.");let j=dY.parse(W),f=Z.trim();if(!f)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:cY(j.tools),skills:cY(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:f,path:J.path}}function jJ($){let J=$.searchPaths??FM($.workspaceRoot),Q=new Map,Z=[];for(let j of J.filter(Boolean)){if(!HM(j))continue;let f;try{f=BM(j,{withFileTypes:!0})}catch(X){Z.push({path:j,error:X instanceof Error?X:Error(String(X))});continue}for(let X of f){if(!X.isFile()||!RM(X.name))continue;let Y=GM(j,X.name);try{let V=AM(Y,"utf8"),H=UZ(V,{path:Y}),B=UM(H.name);if(!Q.has(B))Q.set(B,H)}catch(V){Z.push({path:Y,error:V instanceof Error?V:Error(String(V))})}}}return{configs:Array.from(Q.values()).sort((j,f)=>(j.path?vY(j.path):j.name).localeCompare(f.path?vY(f.path):f.name)),errors:Z}}import{createTool as zM,zodToJsonSchema as LM}from"@cline/shared";import{z as lY}from"zod";var RZ="subagent_",fJ=64,_M=lY.object({prompt:lY.string().trim().min(1).describe("Task for the subagent to perform")});function OM($){let J="",Q=!0;for(let Z of $.trim().toLowerCase()){let W=Z.charCodeAt(0);if(!(W>=97&&W<=122||W>=48&&W<=57||Z==="_")||Z==="_"){if(!Q)J+="_",Q=!0;continue}J+=Z,Q=!1}return Q?J.slice(0,-1):J}function TM($){let J=2166136261;for(let Q=0;Q<$.length;Q++)J^=$.charCodeAt(Q),J=Math.imul(J,16777619);return(J>>>0).toString(36)}function zZ($){let J=OM($)||"agent",Q=TM($).slice(0,6),Z=`${RZ}${J}`;if(Z.length<=fJ)return Z;let W=fJ-RZ.length-Q.length-1,j=J.slice(0,Math.max(1,W));return`${RZ}${j}_${Q}`.slice(0,fJ)}function LZ($){let J=new Set,Q=[];for(let Z of[...$].sort((W,j)=>W.name.localeCompare(j.name))){let W=zZ(Z.name),j=W,f=2;while(J.has(j)){let X=`_${f++}`,Y=Math.max(1,fJ-X.length);j=`${W.slice(0,Y)}${X}`}J.add(j),Q.push({toolName:j,config:Z})}return Q}function MM($,J){return{...$,providerId:J.providerId??$.providerId,modelId:J.modelId??$.modelId,maxIterations:J.maxIterations??$.maxIterations}}function XJ($){return LZ($.agents).map(({toolName:J,config:Q})=>{return zM({name:J,description:`Use the "${Q.name}" subagent: ${Q.description}`,inputSchema:LM(_M),execute:async(W,j)=>{let f=$.configProvider.getRuntimeConfig(),X=G2(MM(f,Q)),Y=$.createSubAgentTools?await $.createSubAgentTools(Q,W,j):[],V=F2({kind:"subagent",prompt:Q.systemPrompt,configProvider:X,tools:Y,maxIterations:Q.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=V.getAgentId(),B=V.getConversationId(),A=j.agentId,K={systemPrompt:Q.systemPrompt,task:W.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:B,parentAgentId:A,input:K})}catch{}try{let G=await V.run(W.prompt),R={text:G.text,iterations:G.iterations,finishReason:G.finishReason,usage:{inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,result:R,agentResult:G})}catch{}return R}catch(G){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,error:G instanceof Error?G:Error(String(G))})}catch{}throw G}},timeoutMs:300000,retryable:!1})})}function Z1(){return new Date().toISOString()}function pY($,J){if(J<=0)return 0;return Math.round($/J*100)}function qM($,J){let Q=new Set;for(let W of J)if(W.status==="reviewed")Q.add(`${W.outcomeId}:${W.section}`);let Z=new Set;for(let W of $){if(W.status==="finalized")continue;for(let j of W.requiredSections)if(!Q.has(`${W.id}:${j}`))Z.add(`${W.id}:${j}`)}return[...Z].sort((W,j)=>W.localeCompare(j))}function YJ($,J){let Q={idle:0,running:0,stopped:0},Z={pending:0,in_progress:0,blocked:0,completed:0},W={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},f={draft:0,reviewed:0,rejected:0},X=0,Y=0;for(let D of J.members)if(Q[D.status]+=1,D.role==="lead")X+=1;else Y+=1;let V=[],H=[],B=J.tasks.filter((D)=>D.status==="completed").length,A=new Map(J.tasks.map((D)=>[D.id,D]));for(let D of J.tasks){if(Z[D.status]+=1,D.status==="blocked"){V.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((F)=>{return A.get(F)?.status==="completed"}))H.push(D.id)}let K=[],G,R=0;for(let D of J.runs){if(W[D.status]+=1,D.status==="queued"||D.status==="running")K.push(D.id);let U=D.startedAt.getTime();if(U>=R)R=U,G=D.id}for(let D of J.outcomes)j[D.status]+=1;for(let D of J.outcomeFragments)f[D.status]+=1;return{teamName:$,updatedAt:Z1(),members:{total:J.members.length,byStatus:Q,leadCount:X,teammateCount:Y},tasks:{total:J.tasks.length,byStatus:Z,blockedTaskIds:V,readyTaskIds:H,completionPct:pY(B,J.tasks.length)},runs:{total:J.runs.length,byStatus:W,activeRunIds:K,latestRunId:G},outcomes:{total:J.outcomes.length,byStatus:j,finalizedPct:pY(j.finalized,J.outcomes.length),missingRequiredSections:qM(J.outcomes,J.outcomeFragments)},fragments:{total:J.outcomeFragments.length,byStatus:f}}}function VJ($){let{event:J}=$;switch(J.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),taskId:J.task.id,agentId:J.task.assignee??J.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),outcomeId:J.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),outcomeId:J.fragment.outcomeId,fragmentId:J.fragment.id,agentId:J.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),taskId:J.message.taskId,agentId:J.message.fromAgentId,message:J.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),taskId:J.entry.taskId,agentId:J.entry.agentId,message:J.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1(),agentId:J.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:Z1()}}import{sanitizeFileName as PM,TeamMessageType as b}from"@cline/shared";import{nanoid as NM}from"nanoid";import{TeamMessageType as Nv}from"@cline/shared";function _Z($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function rY($,J){return $?.status==="stopped"&&_Z(J)}var wM=600000,iY="recovered_queued";function SM($){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.
463
463
 
464
464
  ${$.message}`}class OZ{agents=new Map;configs=new Map;onTeamEvent;constructor($,J){if(this.onTeamEvent=J,$)for(let[Q,Z]of Object.entries($))this.addAgent(Q,Z)}addAgent($,J){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Q={...J,onEvent:(W)=>{J.onEvent?.(W),this.emitEvent({type:b.AgentEvent,agentId:$,event:W})}},Z=new g1(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);this.agents.set($,Z),this.configs.set($,J)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,J){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:J});try{let Z=await Q.run(J);return this.emitEvent({type:b.TaskEnd,agentId:$,result:Z}),Z}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:W,messages:Q.getMessages()}),Z}}async continueTo($,J){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:J});try{let Z=await Q.continue(J);return this.emitEvent({type:b.TaskEnd,agentId:$,result:Z}),Z}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:W,messages:Q.getMessages()}),Z}}async runParallel($){let J=$.map(async(Q)=>{let Z=this.agents.get(Q.agentId);if(!Z)return{agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata};this.emitEvent({type:b.TaskStart,agentId:Q.agentId,message:Q.message});try{let W=await Z.run(Q.message);return this.emitEvent({type:b.TaskEnd,agentId:Q.agentId,result:W}),{agentId:Q.agentId,result:W,metadata:Q.metadata}}catch(W){let j=W instanceof Error?W:Error(String(W));return this.emitEvent({type:b.TaskEnd,agentId:Q.agentId,error:j,messages:Z.getMessages()}),{agentId:Q.agentId,result:void 0,error:j,metadata:Q.metadata}}});return Promise.all(J)}async runSequential($){let J=[];for(let Q of $){let Z=this.agents.get(Q.agentId);if(!Z){J.push({agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata});continue}this.emitEvent({type:b.TaskStart,agentId:Q.agentId,message:Q.message});try{let W=await Z.run(Q.message);this.emitEvent({type:b.TaskEnd,agentId:Q.agentId,result:W}),J.push({agentId:Q.agentId,result:W,metadata:Q.metadata})}catch(W){let j=W instanceof Error?W:Error(String(W));this.emitEvent({type:b.TaskEnd,agentId:Q.agentId,error:j,messages:Z.getMessages()}),J.push({agentId:Q.agentId,result:void 0,error:j,metadata:Q.metadata})}}return J}async runPipeline($,J,Q){let Z=[],W=J;for(let j of $){let f=this.agents.get(j);if(!f){Z.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:b.TaskStart,agentId:j,message:W});try{let X=await f.run(W);this.emitEvent({type:b.TaskEnd,agentId:j,result:X}),Z.push({agentId:j,result:X});let Y=$.indexOf(j)+1;if(Y<$.length){let V=$[Y];W=Q?Q(X,V):`Previous agent output:
465
465
  ${X.text}
466
466
 
467
- Please continue from here.`}}catch(X){let Y=X instanceof Error?X:Error(String(X));this.emitEvent({type:b.TaskEnd,agentId:j,error:Y,messages:f.getMessages()}),Z.push({agentId:j,result:void 0,error:Y});break}}return Z}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}class l8{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_${qM(PM(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let J=$.leadAgentId??"lead";this.members.set(J,{agentId:J,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((J)=>{let Q=this.getUnresolvedDependencies(J);return{...J,blockedBy:Q,isReady:J.status==="pending"&&!J.assignee&&Q.length===0}}).filter((J)=>{if($?.status&&J.status!==$.status)return!1;if($?.assignee&&J.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,J){let Q=J?.unreadOnly??!0,Z=J?.markRead??!0,W=J?.limit,j=this.mailbox.filter((X)=>X.toAgentId===$&&(!Q||!X.readAt)),f=typeof W==="number"&&W>0?j.slice(Math.max(0,j.length-W)):j;if(Z){let X=new Date;for(let Y of f)if(!Y.readAt)Y.readAt=X}return f.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Q of this.tasks.values())$[Q.status]++;let J={draft:0,in_review:0,finalized:0};for(let Q of this.outcomes.values())J[Q.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Q)=>({agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Q)=>!Q.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").length,outcomeCounts:J}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Q of $.tasks)this.tasks.set(Q.id,{...Q});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Q)=>({...Q}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Q)=>({...Q}))),this.runs.clear();for(let Q of $.runs??[])this.runs.set(Q.id,{...Q});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").map((Q)=>Q.id)),this.outcomes.clear();for(let Q of $.outcomes??[])this.outcomes.set(Q.id,{...Q});this.outcomeFragments.clear();for(let Q of $.outcomeFragments??[])this.outcomeFragments.set(Q.id,{...Q});let J=Array.from(this.members.values()).filter((Q)=>Q.role==="lead");this.members.clear();for(let Q of J)this.members.set(Q.agentId,{...Q,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Q of $.members){if(Q.role!=="teammate")continue;this.members.set(Q.agentId,{agentId:Q.agentId,role:"teammate",description:Q.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,P2($.tasks.map((Q)=>Q.id),"task_")),this.messageCounter=Math.max(this.messageCounter,P2($.mailbox.map((Q)=>Q.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,P2($.missionLog.map((Q)=>Q.id),"log_")),this.runCounter=Math.max(this.runCounter,P2(($.runs??[]).map((Q)=>Q.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,P2(($.outcomes??[]).map((Q)=>Q.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,P2(($.outcomeFragments??[]).map((Q)=>Q.id),"frag_"))}isTeammateActive($){let J=this.members.get($);return!!J&&J.role==="teammate"&&!!J.agent}spawnTeammate({agentId:$,config:J}){let Q=this.members.get($);if(Q&&Q.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Q&&Q.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Z={...J,apiTimeoutMs:NM,consumePendingUserMessage:()=>{let f=this.members.get($);if(!f||!f.pendingSteerMessage)return;let X=f.pendingSteerMessage;return f.pendingSteerMessage=void 0,X},onEvent:(f)=>{J.onEvent?.(f),this.emitEvent({type:b.AgentEvent,agentId:$,event:f}),this.trackMeaningfulEvent($,f)}},W=new g1(Z);if(Z.onEvent)W.subscribeEvents(Z.onEvent);let j={agentId:$,role:"teammate",description:J.role,status:"idle",agent:W,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:b.TeammateSpawned,agentId:$,role:J.role,teammate:{rolePrompt:J.systemPrompt,modelId:J.modelId,maxIterations:J.maxIterations,runtimeAgentId:W.getAgentId(),conversationId:W.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Q.agent?.abort()}catch(Z){if(!_Z(Z))throw Z}Q.status="stopped",this.emitEvent({type:b.TeammateShutdown,agentId:$,reason:J})}updateTeammateConnections($){for(let J of this.members.values()){if(J.role!=="teammate"||!J.agent)continue;J.agent.updateConnection($)}}createTask($){let J=`task_${String(++this.taskCounter).padStart(4,"0")}`,Q=new Date,Z={id:J,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Q,updatedAt:Q,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(J,Z),this.emitEvent({type:b.TeamTaskUpdated,task:{...Z}}),{...Z}}claimTask($,J){let Q=this.requireTask($);return this.assertDependenciesResolved(Q),Q.status="in_progress",Q.assignee=J,Q.updatedAt=new Date,this.emitEvent({type:b.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:J,taskId:$,kind:"progress",summary:`Claimed task "${Q.title}"`}),{...Q}}blockTask($,J,Q){let Z=this.requireTask($);return Z.status="blocked",Z.updatedAt=new Date,Z.summary=Q,this.emitEvent({type:b.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"blocked",summary:Q}),{...Z}}completeTask($,J,Q){let Z=this.requireTask($);if(Z.status="completed",Z.updatedAt=new Date,Z.summary=Q,!Z.assignee)Z.assignee=J;return this.emitEvent({type:b.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"done",summary:Q}),{...Z}}async routeToTeammate($,J,Q){let Z=this.members.get($);if(!Z||Z.role!=="teammate"||!Z.agent)throw Error(`Teammate "${$}" was not found`);if(!Z.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Z.runningCount++,Z.status="running",this.emitEvent({type:b.TaskStart,agentId:$,message:J});try{let W=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=W.length>0?`${this.buildMailboxNotification(W)}
467
+ Please continue from here.`}}catch(X){let Y=X instanceof Error?X:Error(String(X));this.emitEvent({type:b.TaskEnd,agentId:j,error:Y,messages:f.getMessages()}),Z.push({agentId:j,result:void 0,error:Y});break}}return Z}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}class l8{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_${PM(NM(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let J=$.leadAgentId??"lead";this.members.set(J,{agentId:J,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((J)=>{let Q=this.getUnresolvedDependencies(J);return{...J,blockedBy:Q,isReady:J.status==="pending"&&!J.assignee&&Q.length===0}}).filter((J)=>{if($?.status&&J.status!==$.status)return!1;if($?.assignee&&J.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,J){let Q=J?.unreadOnly??!0,Z=J?.markRead??!0,W=J?.limit,j=this.mailbox.filter((X)=>X.toAgentId===$&&(!Q||!X.readAt)),f=typeof W==="number"&&W>0?j.slice(Math.max(0,j.length-W)):j;if(Z){let X=new Date;for(let Y of f)if(!Y.readAt)Y.readAt=X}return f.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Q of this.tasks.values())$[Q.status]++;let J={draft:0,in_review:0,finalized:0};for(let Q of this.outcomes.values())J[Q.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Q)=>({agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Q)=>!Q.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").length,outcomeCounts:J}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Q of $.tasks)this.tasks.set(Q.id,{...Q});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Q)=>({...Q}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Q)=>({...Q}))),this.runs.clear();for(let Q of $.runs??[])this.runs.set(Q.id,{...Q});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").map((Q)=>Q.id)),this.outcomes.clear();for(let Q of $.outcomes??[])this.outcomes.set(Q.id,{...Q});this.outcomeFragments.clear();for(let Q of $.outcomeFragments??[])this.outcomeFragments.set(Q.id,{...Q});let J=Array.from(this.members.values()).filter((Q)=>Q.role==="lead");this.members.clear();for(let Q of J)this.members.set(Q.agentId,{...Q,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Q of $.members){if(Q.role!=="teammate")continue;this.members.set(Q.agentId,{agentId:Q.agentId,role:"teammate",description:Q.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,P2($.tasks.map((Q)=>Q.id),"task_")),this.messageCounter=Math.max(this.messageCounter,P2($.mailbox.map((Q)=>Q.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,P2($.missionLog.map((Q)=>Q.id),"log_")),this.runCounter=Math.max(this.runCounter,P2(($.runs??[]).map((Q)=>Q.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,P2(($.outcomes??[]).map((Q)=>Q.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,P2(($.outcomeFragments??[]).map((Q)=>Q.id),"frag_"))}isTeammateActive($){let J=this.members.get($);return!!J&&J.role==="teammate"&&!!J.agent}spawnTeammate({agentId:$,config:J}){let Q=this.members.get($);if(Q&&Q.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Q&&Q.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Z={...J,apiTimeoutMs:wM,consumePendingUserMessage:()=>{let f=this.members.get($);if(!f||!f.pendingSteerMessage)return;let X=f.pendingSteerMessage;return f.pendingSteerMessage=void 0,X},onEvent:(f)=>{J.onEvent?.(f),this.emitEvent({type:b.AgentEvent,agentId:$,event:f}),this.trackMeaningfulEvent($,f)}},W=new g1(Z);if(Z.onEvent)W.subscribeEvents(Z.onEvent);let j={agentId:$,role:"teammate",description:J.role,status:"idle",agent:W,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:b.TeammateSpawned,agentId:$,role:J.role,teammate:{rolePrompt:J.systemPrompt,modelId:J.modelId,maxIterations:J.maxIterations,runtimeAgentId:W.getAgentId(),conversationId:W.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Q.agent?.abort()}catch(Z){if(!_Z(Z))throw Z}Q.status="stopped",this.emitEvent({type:b.TeammateShutdown,agentId:$,reason:J})}updateTeammateConnections($){for(let J of this.members.values()){if(J.role!=="teammate"||!J.agent)continue;J.agent.updateConnection($)}}createTask($){let J=`task_${String(++this.taskCounter).padStart(4,"0")}`,Q=new Date,Z={id:J,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Q,updatedAt:Q,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(J,Z),this.emitEvent({type:b.TeamTaskUpdated,task:{...Z}}),{...Z}}claimTask($,J){let Q=this.requireTask($);return this.assertDependenciesResolved(Q),Q.status="in_progress",Q.assignee=J,Q.updatedAt=new Date,this.emitEvent({type:b.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:J,taskId:$,kind:"progress",summary:`Claimed task "${Q.title}"`}),{...Q}}blockTask($,J,Q){let Z=this.requireTask($);return Z.status="blocked",Z.updatedAt=new Date,Z.summary=Q,this.emitEvent({type:b.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"blocked",summary:Q}),{...Z}}completeTask($,J,Q){let Z=this.requireTask($);if(Z.status="completed",Z.updatedAt=new Date,Z.summary=Q,!Z.assignee)Z.assignee=J;return this.emitEvent({type:b.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"done",summary:Q}),{...Z}}async routeToTeammate($,J,Q){let Z=this.members.get($);if(!Z||Z.role!=="teammate"||!Z.agent)throw Error(`Teammate "${$}" was not found`);if(!Z.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Z.runningCount++,Z.status="running",this.emitEvent({type:b.TaskStart,agentId:$,message:J});try{let W=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=W.length>0?`${this.buildMailboxNotification(W)}
468
468
 
469
- ${J}`:J,f=Q?.continueConversation?await Z.agent.continue(j):await Z.agent.run(j);return this.emitEvent({type:b.TaskEnd,agentId:$,result:f}),this.recordProgressStep($,`Completed a delegated run (${f.iterations} iterations)`,Q?.taskId,!0),f}catch(W){let j=W instanceof Error?W:Error(String(W));if(this.emitEvent({type:b.TaskEnd,agentId:$,error:j,messages:Z.agent.getMessages()}),!lY(Z,j))this.appendMissionLog({agentId:$,taskId:Q?.taskId,kind:"error",summary:j.message});throw j}finally{if(Z.runningCount--,Z.runningCount<=0&&this.members.get($)?.status!=="stopped")Z.status="idle"}}startTeammateRun($,J,Q){let Z=`run_${String(++this.runCounter).padStart(5,"0")}`,W={id:Z,agentId:$,taskId:Q?.taskId,status:"queued",message:J,priority:Q?.priority??0,retryCount:0,maxRetries:Math.max(0,Q?.maxRetries??0),continueConversation:Q?.continueConversation,startedAt:new Date(0),leaseOwner:Q?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Z,W),this.runQueue.push(Z),this.emitEvent({type:b.RunQueued,run:{...W}}),this.dispatchQueuedRuns(),{...W}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let J=this.selectNextDispatchableQueuedRun();$=J.nextDelayedAttemptAt;let Q=J.index;if(Q<0){this.scheduleQueuedRunDispatch($);return}let[Z]=this.runQueue.splice(Q,1),W=Z?this.runs.get(Z):void 0;if(!W||W.status!=="queued")continue;this.executeQueuedRun(W)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,J=Number.NEGATIVE_INFINITY,Q,Z=Date.now();for(let W=0;W<this.runQueue.length;W++){let j=this.runs.get(this.runQueue[W]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Z){if(!Q||j.nextAttemptAt<Q)Q=j.nextAttemptAt;continue}if(j.priority>J)J=j.priority,$=W}return{index:$,nextDelayedAttemptAt:Q}}scheduleQueuedRunDispatch($){if(!$)return;let J=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},J)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let J of this.runs.values())if(J.status==="running")$++;return $}async executeQueuedRun($){let J=$.currentActivity===pY;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:b.RunStarted,run:{...$}});let Q=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Z=J?wM($):$.message,W=await this.routeToTeammate($.agentId,Z,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=W,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:b.RunCompleted,run:{...$}})}catch(Z){let W=Z instanceof Error?Z.message:String(Z??"Unknown error");$.error=W,$.endedAt=new Date;let j=this.members.get($.agentId);if(lY(j,Z))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:b.RunCancelled,run:{...$},reason:W});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:b.RunFailed,run:{...$}})}finally{clearInterval(Q),this.dispatchQueuedRuns()}}listRuns($){let J=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Q)=>{if(!J&&!["running","queued"].includes(Q.status))return!1;if($?.status&&Q.status!==$.status)return!1;if($?.agentId&&Q.agentId!==$.agentId)return!1;return!0}).map((Q)=>({...Q}))}getRun($){let J=this.runs.get($);return J?{...J}:void 0}async awaitRun($,J=250){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);while(Q.status==="queued"||Q.status==="running")await rY(J);return{...Q}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((J)=>["queued","running"].includes(J.status)))await rY($);return this.listRuns()}cancelRun($,J){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);if(Q.status==="completed"||Q.status==="failed")return{...Q};Q.status="cancelled",Q.error=J,Q.endedAt=new Date,Q.currentActivity="cancelled";let Z=this.runQueue.indexOf($);if(Z>=0)this.runQueue.splice(Z,1);return this.emitEvent({type:b.RunCancelled,run:{...Q},reason:J}),{...Q}}recoverActiveRuns($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;let Z=this.members.get(Q.agentId);if(!Z||Z.role!=="teammate"||!Z.agent){Q.status="interrupted",Q.error="teammate_unavailable_after_recovery",Q.endedAt=new Date,Q.currentActivity="interrupted",this.emitEvent({type:b.RunInterrupted,run:{...Q},reason:Q.error});continue}let W=new Date;if(Q.status="queued",Q.error=void 0,Q.endedAt=void 0,Q.heartbeatAt=W,Q.lastProgressAt=W,Q.lastProgressMessage=$,Q.currentActivity=pY,!this.runQueue.includes(Q.id))this.runQueue.push(Q.id);J.push({...Q}),this.emitEvent({type:b.RunQueued,run:{...Q}})}return this.dispatchQueuedRuns(),J}markStaleRunsInterrupted($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;Q.status="interrupted",Q.error=$,Q.endedAt=new Date,Q.currentActivity="interrupted",J.push({...Q}),this.emitEvent({type:b.RunInterrupted,run:{...Q},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),J}sendMessage($,J,Q,Z,W){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(J);if(!j)throw Error(`Unknown recipient "${J}"`);let f={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:J,subject:Q,body:Z,taskId:W,sentAt:new Date};if(this.mailbox.push(f),this.emitEvent({type:b.TeamMessage,message:{...f}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Q}". Use the team_read_mailbox tool to read it at your convenience.`;return{...f}}broadcast($,J,Q,Z){let W=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;W.push(this.sendMessage($,j.agentId,J,Q,Z?.taskId))}return W}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let J={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(J);let Q=this.members.get($.agentId);if(Q)Q.lastMissionAt=Date.now(),Q.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:b.TeamMissionLog,entry:{...J}}),{...J}}createOutcome($){let J={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(J.id,J),this.emitEvent({type:b.OutcomeCreated,outcome:{...J}}),{...J}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let J=this.outcomes.get($.outcomeId);if(!J)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!J.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Q={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Q.id,Q),J.status==="draft")J.status="in_review";return this.emitEvent({type:b.OutcomeFragmentAttached,fragment:{...Q}}),{...Q}}reviewOutcomeFragment($){let J=this.outcomeFragments.get($.fragmentId);if(!J)throw Error(`Fragment "${$.fragmentId}" was not found`);return J.status=$.approved?"reviewed":"rejected",J.reviewedBy=$.reviewedBy,J.reviewedAt=new Date,this.emitEvent({type:b.OutcomeFragmentReviewed,fragment:{...J}}),{...J}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((J)=>J.outcomeId===$).map((J)=>({...J}))}finalizeOutcome($){let J=this.outcomes.get($);if(!J)throw Error(`Outcome "${$}" was not found`);let Q=this.listOutcomeFragments($);for(let Z of J.requiredSections)if(!Q.some((j)=>j.section===Z&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Z}" is missing a reviewed fragment.`);return J.status="finalized",J.finalizedAt=new Date,this.emitEvent({type:b.OutcomeFinalized,outcome:{...J}}),{...J}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(J){if(!_Z(J))throw J}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,J]of this.members.entries())if(J.role==="teammate")this.members.delete($)}requireTask($){let J=this.tasks.get($);if(!J)throw Error(`Task "${$}" was not found`);return J}assertDependenciesResolved($){let J=this.getUnresolvedDependencies($);if(J.length>0)throw Error(`Task "${$.id}" is blocked by "${J[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((J)=>{let Q=this.tasks.get(J);return!Q||Q.status!=="completed"})}trackMeaningfulEvent($,J){if(this.recordRunActivityFromAgentEvent($,J),J.type==="iteration_end"&&J.hadToolCalls){this.recordProgressStep($,`Completed iteration ${J.iteration} with ${J.toolCallCount} tool call(s)`);return}if(J.type==="content_end"&&J.contentType==="tool"&&!J.error){this.recordProgressStep($,`Finished tool "${J.toolName??"unknown"}"`);return}if(J.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${J.iterations} iterations)`});return}if(J.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:J.error.message})}recordRunActivityFromAgentEvent($,J){let Q;switch(J.type){case"iteration_start":Q=`iteration_${J.iteration}_started`;break;case"content_start":if(J.contentType==="tool")Q=`running_tool_${J.toolName??"unknown"}`;break;case"content_end":if(J.contentType==="tool")Q=J.error?this.formatProgressErrorActivity(`tool_${J.toolName??"unknown"}_error`,J.error):`finished_tool_${J.toolName??"unknown"}`;break;case"done":Q="finalizing_response";break;case"error":Q=this.formatProgressErrorActivity("run_error",J.error.message);break;default:break}if(!Q)return;for(let Z of this.runs.values()){if(Z.agentId!==$||Z.status!=="running")continue;this.recordRunProgress(Z,Q)}}recordRunProgress($,J){let Q=new Date;$.heartbeatAt=Q,$.lastProgressAt=Q,$.lastProgressMessage=J,$.currentActivity=J,this.emitEvent({type:b.RunProgress,run:{...$},message:J})}formatProgressErrorActivity($,J){let Q=J.replace(/\s+/g," ").trim();if(Q.length===0)return $;let Z=Q.length>240?`${Q.slice(0,237).trimEnd()}...`:Q;return`${$}: ${Z}`}recordProgressStep($,J,Q,Z=!1){this.missionStepCounter++;let W=this.members.get($);if(!W)return;let j=this.missionStepCounter-W.lastMissionStep,f=Date.now()-W.lastMissionAt;if(!Z&&j<this.missionLogIntervalSteps&&f<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Q,kind:"progress",summary:J})}buildMailboxNotification($){if($.length===0)return"";let J=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Q of $)J.push(`--- Message from ${Q.fromAgentId} | subject: ${Q.subject} ---`),J.push(Q.body);return J.push("---"),J.join(`
470
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function rY($){return new Promise((J)=>setTimeout(J,$))}function P2($,J){let Q=0;for(let Z of $){if(!Z.startsWith(J))continue;let W=Number.parseInt(Z.slice(J.length),10);if(Number.isFinite(W))Q=Math.max(Q,W)}return Q}function TZ($,J){switch(J.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(J.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Q;if(J.type==="run_failed")Q=J.run.error;else if(J.type==="run_cancelled"||J.type==="run_interrupted")Q=J.run.error??J.reason;$.activeTeamRunIds.delete(J.run.id),$.pendingTeamRunUpdates.push({runId:J.run.id,agentId:J.run.agentId,taskId:J.run.taskId,status:J.type.replace("run_",""),error:Q,iterations:J.run.result?.iterations}),HJ($);break}default:break}}async function MZ($,J,Q){switch(J.type){case"run_progress":await Q("onTeamTaskProgress",$,J.run.agentId,J.message,{kind:J.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(J.event.type==="content_start"&&J.event.contentType==="text"&&typeof J.event.text==="string"){let Z=J.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Z)await Q("onTeamTaskProgress",$,J.agentId,Z,{kind:"text"})}break;case"task_start":await Q("onTeamTaskStart",$,J.agentId,J.message);break;case"task_end":{if(J.error)await Q("onTeamTaskEnd",$,J.agentId,"failed",`[error] ${J.error.message}`,void 0,J.messages);else if(J.result?.finishReason==="aborted")await Q("onTeamTaskEnd",$,J.agentId,"cancelled","[done] aborted",J.result,J.result.messages);else await Q("onTeamTaskEnd",$,J.agentId,"completed",`[done] ${J.result?.finishReason??"completed"}`,J.result,J.result?.messages);break}default:break}}function qZ($,J,Q,Z){if(!$.runtime.teamRuntime)return;let W=$.runtime.teamRuntime.getTeamName();Z({type:"team_progress",payload:{sessionId:J,teamName:W,lifecycle:VJ({teamName:W,sessionId:J,event:Q}),summary:YJ(W,$.runtime.teamRuntime.exportState())}})}function p8($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function PZ($,J){if($.aborting)return!1;if(!(J==="completed"||J==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&p8($)}function HJ($){let J=$.teamRunWaiters.splice(0);for(let Q of J)Q()}async function NZ($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let J=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,J}if($.activeTeamRunIds.size===0)return[];await new Promise((J)=>{$.teamRunWaiters.push(J)})}}function wZ($,J){let Q=J.map((j)=>{let f=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)f.push(` task=${j.taskId}`);if(typeof j.iterations==="number")f.push(` iterations=${j.iterations}`);if(j.error)f.push(` error=${j.error}`);return f.join("")}),Z=$.activeTeamRunIds.size,W=Z>0?`There are still ${Z} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return r8(`System-delivered teammate async run updates:
469
+ ${J}`:J,f=Q?.continueConversation?await Z.agent.continue(j):await Z.agent.run(j);return this.emitEvent({type:b.TaskEnd,agentId:$,result:f}),this.recordProgressStep($,`Completed a delegated run (${f.iterations} iterations)`,Q?.taskId,!0),f}catch(W){let j=W instanceof Error?W:Error(String(W));if(this.emitEvent({type:b.TaskEnd,agentId:$,error:j,messages:Z.agent.getMessages()}),!rY(Z,j))this.appendMissionLog({agentId:$,taskId:Q?.taskId,kind:"error",summary:j.message});throw j}finally{if(Z.runningCount--,Z.runningCount<=0&&this.members.get($)?.status!=="stopped")Z.status="idle"}}startTeammateRun($,J,Q){let Z=`run_${String(++this.runCounter).padStart(5,"0")}`,W={id:Z,agentId:$,taskId:Q?.taskId,status:"queued",message:J,priority:Q?.priority??0,retryCount:0,maxRetries:Math.max(0,Q?.maxRetries??0),continueConversation:Q?.continueConversation,startedAt:new Date(0),leaseOwner:Q?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Z,W),this.runQueue.push(Z),this.emitEvent({type:b.RunQueued,run:{...W}}),this.dispatchQueuedRuns(),{...W}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let J=this.selectNextDispatchableQueuedRun();$=J.nextDelayedAttemptAt;let Q=J.index;if(Q<0){this.scheduleQueuedRunDispatch($);return}let[Z]=this.runQueue.splice(Q,1),W=Z?this.runs.get(Z):void 0;if(!W||W.status!=="queued")continue;this.executeQueuedRun(W)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,J=Number.NEGATIVE_INFINITY,Q,Z=Date.now();for(let W=0;W<this.runQueue.length;W++){let j=this.runs.get(this.runQueue[W]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Z){if(!Q||j.nextAttemptAt<Q)Q=j.nextAttemptAt;continue}if(j.priority>J)J=j.priority,$=W}return{index:$,nextDelayedAttemptAt:Q}}scheduleQueuedRunDispatch($){if(!$)return;let J=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},J)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let J of this.runs.values())if(J.status==="running")$++;return $}async executeQueuedRun($){let J=$.currentActivity===iY;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:b.RunStarted,run:{...$}});let Q=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Z=J?SM($):$.message,W=await this.routeToTeammate($.agentId,Z,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=W,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:b.RunCompleted,run:{...$}})}catch(Z){let W=Z instanceof Error?Z.message:String(Z??"Unknown error");$.error=W,$.endedAt=new Date;let j=this.members.get($.agentId);if(rY(j,Z))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:b.RunCancelled,run:{...$},reason:W});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:b.RunFailed,run:{...$}})}finally{clearInterval(Q),this.dispatchQueuedRuns()}}listRuns($){let J=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Q)=>{if(!J&&!["running","queued"].includes(Q.status))return!1;if($?.status&&Q.status!==$.status)return!1;if($?.agentId&&Q.agentId!==$.agentId)return!1;return!0}).map((Q)=>({...Q}))}getRun($){let J=this.runs.get($);return J?{...J}:void 0}async awaitRun($,J=250){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);while(Q.status==="queued"||Q.status==="running")await nY(J);return{...Q}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((J)=>["queued","running"].includes(J.status)))await nY($);return this.listRuns()}cancelRun($,J){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);if(Q.status==="completed"||Q.status==="failed")return{...Q};Q.status="cancelled",Q.error=J,Q.endedAt=new Date,Q.currentActivity="cancelled";let Z=this.runQueue.indexOf($);if(Z>=0)this.runQueue.splice(Z,1);return this.emitEvent({type:b.RunCancelled,run:{...Q},reason:J}),{...Q}}recoverActiveRuns($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;let Z=this.members.get(Q.agentId);if(!Z||Z.role!=="teammate"||!Z.agent){Q.status="interrupted",Q.error="teammate_unavailable_after_recovery",Q.endedAt=new Date,Q.currentActivity="interrupted",this.emitEvent({type:b.RunInterrupted,run:{...Q},reason:Q.error});continue}let W=new Date;if(Q.status="queued",Q.error=void 0,Q.endedAt=void 0,Q.heartbeatAt=W,Q.lastProgressAt=W,Q.lastProgressMessage=$,Q.currentActivity=iY,!this.runQueue.includes(Q.id))this.runQueue.push(Q.id);J.push({...Q}),this.emitEvent({type:b.RunQueued,run:{...Q}})}return this.dispatchQueuedRuns(),J}markStaleRunsInterrupted($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;Q.status="interrupted",Q.error=$,Q.endedAt=new Date,Q.currentActivity="interrupted",J.push({...Q}),this.emitEvent({type:b.RunInterrupted,run:{...Q},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),J}sendMessage($,J,Q,Z,W){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(J);if(!j)throw Error(`Unknown recipient "${J}"`);let f={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:J,subject:Q,body:Z,taskId:W,sentAt:new Date};if(this.mailbox.push(f),this.emitEvent({type:b.TeamMessage,message:{...f}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Q}". Use the team_read_mailbox tool to read it at your convenience.`;return{...f}}broadcast($,J,Q,Z){let W=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;W.push(this.sendMessage($,j.agentId,J,Q,Z?.taskId))}return W}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let J={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(J);let Q=this.members.get($.agentId);if(Q)Q.lastMissionAt=Date.now(),Q.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:b.TeamMissionLog,entry:{...J}}),{...J}}createOutcome($){let J={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(J.id,J),this.emitEvent({type:b.OutcomeCreated,outcome:{...J}}),{...J}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let J=this.outcomes.get($.outcomeId);if(!J)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!J.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Q={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Q.id,Q),J.status==="draft")J.status="in_review";return this.emitEvent({type:b.OutcomeFragmentAttached,fragment:{...Q}}),{...Q}}reviewOutcomeFragment($){let J=this.outcomeFragments.get($.fragmentId);if(!J)throw Error(`Fragment "${$.fragmentId}" was not found`);return J.status=$.approved?"reviewed":"rejected",J.reviewedBy=$.reviewedBy,J.reviewedAt=new Date,this.emitEvent({type:b.OutcomeFragmentReviewed,fragment:{...J}}),{...J}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((J)=>J.outcomeId===$).map((J)=>({...J}))}finalizeOutcome($){let J=this.outcomes.get($);if(!J)throw Error(`Outcome "${$}" was not found`);let Q=this.listOutcomeFragments($);for(let Z of J.requiredSections)if(!Q.some((j)=>j.section===Z&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Z}" is missing a reviewed fragment.`);return J.status="finalized",J.finalizedAt=new Date,this.emitEvent({type:b.OutcomeFinalized,outcome:{...J}}),{...J}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(J){if(!_Z(J))throw J}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,J]of this.members.entries())if(J.role==="teammate")this.members.delete($)}requireTask($){let J=this.tasks.get($);if(!J)throw Error(`Task "${$}" was not found`);return J}assertDependenciesResolved($){let J=this.getUnresolvedDependencies($);if(J.length>0)throw Error(`Task "${$.id}" is blocked by "${J[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((J)=>{let Q=this.tasks.get(J);return!Q||Q.status!=="completed"})}trackMeaningfulEvent($,J){if(this.recordRunActivityFromAgentEvent($,J),J.type==="iteration_end"&&J.hadToolCalls){this.recordProgressStep($,`Completed iteration ${J.iteration} with ${J.toolCallCount} tool call(s)`);return}if(J.type==="content_end"&&J.contentType==="tool"&&!J.error){this.recordProgressStep($,`Finished tool "${J.toolName??"unknown"}"`);return}if(J.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${J.iterations} iterations)`});return}if(J.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:J.error.message})}recordRunActivityFromAgentEvent($,J){let Q;switch(J.type){case"iteration_start":Q=`iteration_${J.iteration}_started`;break;case"content_start":if(J.contentType==="tool")Q=`running_tool_${J.toolName??"unknown"}`;break;case"content_end":if(J.contentType==="tool")Q=J.error?this.formatProgressErrorActivity(`tool_${J.toolName??"unknown"}_error`,J.error):`finished_tool_${J.toolName??"unknown"}`;break;case"done":Q="finalizing_response";break;case"error":Q=this.formatProgressErrorActivity("run_error",J.error.message);break;default:break}if(!Q)return;for(let Z of this.runs.values()){if(Z.agentId!==$||Z.status!=="running")continue;this.recordRunProgress(Z,Q)}}recordRunProgress($,J){let Q=new Date;$.heartbeatAt=Q,$.lastProgressAt=Q,$.lastProgressMessage=J,$.currentActivity=J,this.emitEvent({type:b.RunProgress,run:{...$},message:J})}formatProgressErrorActivity($,J){let Q=J.replace(/\s+/g," ").trim();if(Q.length===0)return $;let Z=Q.length>240?`${Q.slice(0,237).trimEnd()}...`:Q;return`${$}: ${Z}`}recordProgressStep($,J,Q,Z=!1){this.missionStepCounter++;let W=this.members.get($);if(!W)return;let j=this.missionStepCounter-W.lastMissionStep,f=Date.now()-W.lastMissionAt;if(!Z&&j<this.missionLogIntervalSteps&&f<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Q,kind:"progress",summary:J})}buildMailboxNotification($){if($.length===0)return"";let J=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Q of $)J.push(`--- Message from ${Q.fromAgentId} | subject: ${Q.subject} ---`),J.push(Q.body);return J.push("---"),J.join(`
470
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function nY($){return new Promise((J)=>setTimeout(J,$))}function P2($,J){let Q=0;for(let Z of $){if(!Z.startsWith(J))continue;let W=Number.parseInt(Z.slice(J.length),10);if(Number.isFinite(W))Q=Math.max(Q,W)}return Q}function TZ($,J){switch(J.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(J.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Q;if(J.type==="run_failed")Q=J.run.error;else if(J.type==="run_cancelled"||J.type==="run_interrupted")Q=J.run.error??J.reason;$.activeTeamRunIds.delete(J.run.id),$.pendingTeamRunUpdates.push({runId:J.run.id,agentId:J.run.agentId,taskId:J.run.taskId,status:J.type.replace("run_",""),error:Q,iterations:J.run.result?.iterations}),HJ($);break}default:break}}async function MZ($,J,Q){switch(J.type){case"run_progress":await Q("onTeamTaskProgress",$,J.run.agentId,J.message,{kind:J.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(J.event.type==="content_start"&&J.event.contentType==="text"&&typeof J.event.text==="string"){let Z=J.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Z)await Q("onTeamTaskProgress",$,J.agentId,Z,{kind:"text"})}break;case"task_start":await Q("onTeamTaskStart",$,J.agentId,J.message);break;case"task_end":{if(J.error)await Q("onTeamTaskEnd",$,J.agentId,"failed",`[error] ${J.error.message}`,void 0,J.messages);else if(J.result?.finishReason==="aborted")await Q("onTeamTaskEnd",$,J.agentId,"cancelled","[done] aborted",J.result,J.result.messages);else await Q("onTeamTaskEnd",$,J.agentId,"completed",`[done] ${J.result?.finishReason??"completed"}`,J.result,J.result?.messages);break}default:break}}function qZ($,J,Q,Z){if(!$.runtime.teamRuntime)return;let W=$.runtime.teamRuntime.getTeamName();Z({type:"team_progress",payload:{sessionId:J,teamName:W,lifecycle:VJ({teamName:W,sessionId:J,event:Q}),summary:YJ(W,$.runtime.teamRuntime.exportState())}})}function p8($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function PZ($,J){if($.aborting)return!1;if(!(J==="completed"||J==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&p8($)}function HJ($){let J=$.teamRunWaiters.splice(0);for(let Q of J)Q()}async function NZ($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let J=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,J}if($.activeTeamRunIds.size===0)return[];await new Promise((J)=>{$.teamRunWaiters.push(J)})}}function wZ($,J){let Q=J.map((j)=>{let f=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)f.push(` task=${j.taskId}`);if(typeof j.iterations==="number")f.push(` iterations=${j.iterations}`);if(j.error)f.push(` error=${j.error}`);return f.join("")}),Z=$.activeTeamRunIds.size,W=Z>0?`There are still ${Z} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return r8(`System-delivered teammate async run updates:
471
471
  ${Q.join(`
472
472
  `)}
473
473
 
474
- ${W}`,$.config.mode)}function r8($,J){return SM($,J==="plan"?"plan":J==="yolo"?"yolo":"act")}var SZ=4;class z1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,J={}){this.adapter=$;this.manifestStore=new FZ($,J.messagesArtifactUploader,J.logger),this.teamChildren=new WJ($,this.manifestStore,(Q,Z,W)=>this.toPersistedMessages(Q,Z,W),z1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,J,Q){if(!$)return;return J?r6(J.messages,J,Q):p6($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,J){this.manifestStore.writeSessionManifest($,J)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let J=$.startedAt??s(),Q=$.sessionId.trim(),Z=Q.length>0?Q:`${Date.now()}_${yM(5)}`,W=this.manifestStore.artifacts.sessionMessagesPath(Z),j=this.manifestStore.artifacts.sessionManifestPath(Z),f=b8({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Z,source:$.source,pid:$.pid,started_at:J,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:f,messages_path:W};return await this.adapter.upsertSession({sessionId:Z,source:$.source,pid:$.pid,startedAt:J,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:X.prompt??null,metadata:u1(X.metadata),hookPath:"",messagesPath:W,updatedAt:s()}),this.manifestStore.initializeMessagesFile(Z,W,J),this.manifestStore.writeSessionManifest(j,X),{manifestPath:j,messagesPath:W,manifest:X}}async updateSessionStatus($,J,Q){let Z;if((await xX(()=>this.adapter.getSession($),async(j)=>{return Z=Z0(J)?void 0:s(),this.adapter.updateSession({sessionId:$,status:J,endedAt:Z??null,exitCode:Z0(J)?null:typeof Q==="number"?Q:null,expectedStatusLock:j.statusLock})},SZ)).updated){if(J==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Z}}return{updated:!1}}async updateSession($){for(let J=0;J<SZ;J++){let Q=await this.adapter.getSession($.sessionId);if(!Q)return{updated:!1};let Z=Q.metadata??void 0,W=$.metadata!==void 0?u1($.metadata)??{}:u1(Z)??{},j=N$(typeof Z?.title==="string"?Z.title:void 0),f=$.title!==void 0?N$($.title):j??i9($.prompt);if(f)W.title=f;else delete W.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(W).length>0?W:null:void 0,title:f,expectedStatusLock:Q.statusLock})).updated)continue;let{path:V,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let B=$.metadata!==void 0?u1($.metadata)??{}:u1(H.metadata)??{};if(f)B.title=f;H.metadata=Object.keys(B).length>0?B:void 0,this.manifestStore.writeSessionManifest(V,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,J){return this.teamChildren.appendSubagentHookAudit(J),Promise.resolve()}persistSessionMessages($,J,Q){let Z=p6(J);return this.manifestStore.persistSessionMessages($,Z,Q)}applySubagentStatus($,J){return this.teamChildren.applySubagentStatus($,J)}applySubagentStatusBySessionId($,J){return this.teamChildren.applySubagentStatusBySessionId($,J)}applyStatusToRunningChildSessions($,J){return this.teamChildren.applyStatusToRunningChildSessions($,J)}onTeamTaskStart($,J,Q){return this.teamChildren.onTeamTaskStart($,J,Q)}onTeamTaskEnd($,J,Q,Z,W,j){return this.teamChildren.onTeamTaskEnd($,J,Q,Z,W,j)}onTeamTaskProgress($,J,Q,Z){return this.teamChildren.onTeamTaskProgress($,J,Q,Z)}handleSubAgentStart($,J){return this.teamChildren.handleSubAgentStart($,J)}handleSubAgentEnd($,J){return this.teamChildren.handleSubAgentEnd($,J)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(J){return typeof J==="object"&&J!==null&&"code"in J&&J.code==="EPERM"}}async reconcileDeadRunningSession($){if(Z0($.status)===!1||this.isPidAlive($.pid))return $;let J=s(),Q=z1.STALE_REASON;for(let Z=0;Z<SZ;Z++){let W=await this.adapter.getSession($.sessionId);if(!W)return;if(Z0(W.status)===!1)return W;let j={...W.metadata??{},terminal_marker:Q,terminal_marker_at:J,terminal_marker_pid:W.pid,terminal_marker_source:z1.STALE_SOURCE},f=await this.adapter.updateSession({sessionId:W.sessionId,status:"failed",endedAt:J,exitCode:1,metadata:j,expectedStatusLock:W.statusLock});if(!f.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(W.sessionId,"failed");let X=IX(W,{status:"failed",endedAt:J,exitCode:1,metadata:j}),{path:Y}=this.manifestStore.readManifestFile(W.sessionId);return this.manifestStore.writeSessionManifest(Y,X),this.manifestStore.appendStaleSessionHookLog(J,W.sessionId,W.pid,Q,z1.STALE_SOURCE),{...W,status:"failed",endedAt:J,exitCode:1,metadata:j,statusLock:f.statusLock,updatedAt:J}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let J=Math.max(1,Math.floor($)),Q=Math.min(J*5,2000);return await this.reconcileDeadSessions(Q),(await this.adapter.listSessions({limit:Q})).slice(0,J).map((W)=>{let j=u1(W.metadata??void 0),f=this.manifestStore.readSessionManifest(W.sessionId),X=N$(typeof f?.metadata?.title==="string"?f.metadata.title:void 0),Y=X?{...j??{},title:X}:j;return{...W,metadata:Y}})}async reconcileDeadSessions($=2000){let J=Math.max(1,Math.floor($)),Q=(await Promise.all(["idle","running","pending"].map((W)=>this.adapter.listSessions({limit:J,status:W})))).flat(),Z=0;for(let W of Q){let j=await this.reconcileDeadRunningSession(W);if(j&&j.status!==W.status)Z++}return Z}async deleteSession($){let J=$.trim();if(!J)throw Error("session id is required");let Q=await this.adapter.getSession(J);if(!Q)return{deleted:!1};if(await this.adapter.deleteSession(J,!1),!Q.isSubagent){let Z=await this.adapter.listSessions({limit:2000,parentSessionId:J});await this.adapter.deleteSession(J,!0),await Promise.allSettled(Z.map(async(W)=>{await KZ(W.cwd,W.sessionId),d8(W.messagesPath),d8(this.manifestStore.artifacts.sessionManifestPath(W.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(W.sessionId)}))}if(await KZ(Q.cwd,J),d8(Q.messagesPath),d8(this.manifestStore.artifacts.sessionManifestPath(J,!1)),Q.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(J);else{let Z=new Set([this.manifestStore.artifacts.sessionArtifactsDir(J)]);for(let W of[Q.messagesPath])if(typeof W==="string"&&W.trim().length>0)Z.add(CM(W));for(let W of Z)this.manifestStore.artifacts.removeDir(W)}return{deleted:!0}}}function yZ(){return new Date().toISOString()}function aY($,J){let Q=`${$}.tmp`;hM(Q,`${JSON.stringify(J,null,2)}
475
- `,"utf8"),bM(Q,$)}class sY{sessionsDirPath;constructor($=kM()){this.sessionsDirPath=$}ensureSessionsDir(){if(!CZ(this.sessionsDirPath))EM(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return nY(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return nY(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!CZ($))return{version:1,sessions:{}};try{let J=JSON.parse(iY($,"utf8"));if(J?.version===1&&J.sessions)return J}catch{}return{version:1,sessions:{}}}writeIndex($){aY(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!CZ($))return{version:1,nextId:1,requests:[]};try{let J=JSON.parse(iY($,"utf8"));if(J?.version===1&&typeof J.nextId==="number"&&Array.isArray(J.requests))return J}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){aY(this.spawnQueuePath(),$)}async upsertSession($){let J=this.readIndex();J.sessions[$.sessionId]=$,this.writeIndex(J)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((J)=>$.parentSessionId!==void 0?J.parentSessionId===$.parentSessionId:!0).filter((J)=>$.status!==void 0?J.status===$.status:!0).sort((J,Q)=>Q.startedAt.localeCompare(J.startedAt)).slice(0,$.limit)}async updateSession($){let J=this.readIndex(),Q=J.sessions[$.sessionId];if(!Q)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Q.statusLock};let Z=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Q.statusLock,W={...Q,status:$.status??Q.status,endedAt:$.endedAt!==void 0?$.endedAt:Q.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Q.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Q.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Q.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Q.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Q.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Q.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Q.conversationId??null,statusLock:Z,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Q.isSubagent,updatedAt:yZ()};if($.setRunning)W.status="running",W.endedAt=null,W.exitCode=null;return J.sessions[$.sessionId]=W,this.writeIndex(J),{updated:!0,statusLock:W.statusLock}}async deleteSession($,J){let Q=this.readIndex();if(!Q.sessions[$])return!1;if(delete Q.sessions[$],J){for(let W of Object.values(Q.sessions))if(W.parentSessionId===$)delete Q.sessions[W.sessionId]}return this.writeIndex(Q),!0}async enqueueSpawnRequest($){let J=this.readQueue();J.requests.push({id:J.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:yZ()}),J.nextId+=1,this.writeQueue(J)}async claimSpawnRequest($,J){let Q=this.readQueue(),Z=Q.requests.find((W)=>W.rootSessionId===$&&W.parentAgentId===J&&!W.consumedAt);if(!Z)return;return Z.consumedAt=yZ(),this.writeQueue(Q),Z.task}}class EZ extends z1{constructor($,J={}){super(new sY($),J)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as IM,mkdirSync as xM}from"node:fs";import{resolveSessionDataDir as gM}from"@cline/shared/storage";var bZ=`
474
+ ${W}`,$.config.mode)}function r8($,J){return CM($,J==="plan"?"plan":J==="yolo"?"yolo":"act")}var SZ=4;class z1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,J={}){this.adapter=$;this.manifestStore=new FZ($,J.messagesArtifactUploader,J.logger),this.teamChildren=new WJ($,this.manifestStore,(Q,Z,W)=>this.toPersistedMessages(Q,Z,W),z1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,J,Q){if(!$)return;return J?r6(J.messages,J,Q):p6($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,J){this.manifestStore.writeSessionManifest($,J)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let J=$.startedAt??s(),Q=$.sessionId.trim(),Z=Q.length>0?Q:`${Date.now()}_${EM(5)}`,W=this.manifestStore.artifacts.sessionMessagesPath(Z),j=this.manifestStore.artifacts.sessionManifestPath(Z),f=b8({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Z,source:$.source,pid:$.pid,started_at:J,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:f,messages_path:W};return await this.adapter.upsertSession({sessionId:Z,source:$.source,pid:$.pid,startedAt:J,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:X.prompt??null,metadata:u1(X.metadata),hookPath:"",messagesPath:W,updatedAt:s()}),this.manifestStore.initializeMessagesFile(Z,W,J),this.manifestStore.writeSessionManifest(j,X),{manifestPath:j,messagesPath:W,manifest:X}}async updateSessionStatus($,J,Q){let Z;if((await mX(()=>this.adapter.getSession($),async(j)=>{return Z=Z0(J)?void 0:s(),this.adapter.updateSession({sessionId:$,status:J,endedAt:Z??null,exitCode:Z0(J)?null:typeof Q==="number"?Q:null,expectedStatusLock:j.statusLock})},SZ)).updated){if(J==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Z}}return{updated:!1}}async updateSession($){for(let J=0;J<SZ;J++){let Q=await this.adapter.getSession($.sessionId);if(!Q)return{updated:!1};let Z=Q.metadata??void 0,W=$.metadata!==void 0?u1($.metadata)??{}:u1(Z)??{},j=N$(typeof Z?.title==="string"?Z.title:void 0),f=$.title!==void 0?N$($.title):j??i9($.prompt);if(f)W.title=f;else delete W.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(W).length>0?W:null:void 0,title:f,expectedStatusLock:Q.statusLock})).updated)continue;let{path:V,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let B=$.metadata!==void 0?u1($.metadata)??{}:u1(H.metadata)??{};if(f)B.title=f;H.metadata=Object.keys(B).length>0?B:void 0,this.manifestStore.writeSessionManifest(V,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,J){return this.teamChildren.appendSubagentHookAudit(J),Promise.resolve()}persistSessionMessages($,J,Q){let Z=p6(J);return this.manifestStore.persistSessionMessages($,Z,Q)}applySubagentStatus($,J){return this.teamChildren.applySubagentStatus($,J)}applySubagentStatusBySessionId($,J){return this.teamChildren.applySubagentStatusBySessionId($,J)}applyStatusToRunningChildSessions($,J){return this.teamChildren.applyStatusToRunningChildSessions($,J)}onTeamTaskStart($,J,Q){return this.teamChildren.onTeamTaskStart($,J,Q)}onTeamTaskEnd($,J,Q,Z,W,j){return this.teamChildren.onTeamTaskEnd($,J,Q,Z,W,j)}onTeamTaskProgress($,J,Q,Z){return this.teamChildren.onTeamTaskProgress($,J,Q,Z)}handleSubAgentStart($,J){return this.teamChildren.handleSubAgentStart($,J)}handleSubAgentEnd($,J){return this.teamChildren.handleSubAgentEnd($,J)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(J){return typeof J==="object"&&J!==null&&"code"in J&&J.code==="EPERM"}}async reconcileDeadRunningSession($){if(Z0($.status)===!1||this.isPidAlive($.pid))return $;let J=s(),Q=z1.STALE_REASON;for(let Z=0;Z<SZ;Z++){let W=await this.adapter.getSession($.sessionId);if(!W)return;if(Z0(W.status)===!1)return W;let j={...W.metadata??{},terminal_marker:Q,terminal_marker_at:J,terminal_marker_pid:W.pid,terminal_marker_source:z1.STALE_SOURCE},f=await this.adapter.updateSession({sessionId:W.sessionId,status:"failed",endedAt:J,exitCode:1,metadata:j,expectedStatusLock:W.statusLock});if(!f.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(W.sessionId,"failed");let X=gX(W,{status:"failed",endedAt:J,exitCode:1,metadata:j}),{path:Y}=this.manifestStore.readManifestFile(W.sessionId);return this.manifestStore.writeSessionManifest(Y,X),this.manifestStore.appendStaleSessionHookLog(J,W.sessionId,W.pid,Q,z1.STALE_SOURCE),{...W,status:"failed",endedAt:J,exitCode:1,metadata:j,statusLock:f.statusLock,updatedAt:J}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let J=Math.max(1,Math.floor($)),Q=Math.min(J*5,2000);return await this.reconcileDeadSessions(Q),(await this.adapter.listSessions({limit:Q})).slice(0,J).map((W)=>{let j=u1(W.metadata??void 0),f=this.manifestStore.readSessionManifest(W.sessionId),X=N$(typeof f?.metadata?.title==="string"?f.metadata.title:void 0),Y=X?{...j??{},title:X}:j;return{...W,metadata:Y}})}async reconcileDeadSessions($=2000){let J=Math.max(1,Math.floor($)),Q=(await Promise.all(["idle","running","pending"].map((W)=>this.adapter.listSessions({limit:J,status:W})))).flat(),Z=0;for(let W of Q){let j=await this.reconcileDeadRunningSession(W);if(j&&j.status!==W.status)Z++}return Z}async deleteSession($){let J=$.trim();if(!J)throw Error("session id is required");let Q=await this.adapter.getSession(J);if(!Q)return{deleted:!1};if(await this.adapter.deleteSession(J,!1),!Q.isSubagent){let Z=await this.adapter.listSessions({limit:2000,parentSessionId:J});await this.adapter.deleteSession(J,!0),await Promise.allSettled(Z.map(async(W)=>{await KZ(W.cwd,W.sessionId),d8(W.messagesPath),d8(this.manifestStore.artifacts.sessionManifestPath(W.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(W.sessionId)}))}if(await KZ(Q.cwd,J),d8(Q.messagesPath),d8(this.manifestStore.artifacts.sessionManifestPath(J,!1)),Q.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(J);else{let Z=new Set([this.manifestStore.artifacts.sessionArtifactsDir(J)]);for(let W of[Q.messagesPath])if(typeof W==="string"&&W.trim().length>0)Z.add(yM(W));for(let W of Z)this.manifestStore.artifacts.removeDir(W)}return{deleted:!0}}}function yZ(){return new Date().toISOString()}function oY($,J){let Q=`${$}.tmp`;kM(Q,`${JSON.stringify(J,null,2)}
475
+ `,"utf8"),hM(Q,$)}class tY{sessionsDirPath;constructor($=IM()){this.sessionsDirPath=$}ensureSessionsDir(){if(!CZ(this.sessionsDirPath))bM(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return sY(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return sY(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!CZ($))return{version:1,sessions:{}};try{let J=JSON.parse(aY($,"utf8"));if(J?.version===1&&J.sessions)return J}catch{}return{version:1,sessions:{}}}writeIndex($){oY(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!CZ($))return{version:1,nextId:1,requests:[]};try{let J=JSON.parse(aY($,"utf8"));if(J?.version===1&&typeof J.nextId==="number"&&Array.isArray(J.requests))return J}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){oY(this.spawnQueuePath(),$)}async upsertSession($){let J=this.readIndex();J.sessions[$.sessionId]=$,this.writeIndex(J)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((J)=>$.parentSessionId!==void 0?J.parentSessionId===$.parentSessionId:!0).filter((J)=>$.status!==void 0?J.status===$.status:!0).sort((J,Q)=>Q.startedAt.localeCompare(J.startedAt)).slice(0,$.limit)}async updateSession($){let J=this.readIndex(),Q=J.sessions[$.sessionId];if(!Q)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Q.statusLock};let Z=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Q.statusLock,W={...Q,status:$.status??Q.status,endedAt:$.endedAt!==void 0?$.endedAt:Q.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Q.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Q.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Q.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Q.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Q.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Q.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Q.conversationId??null,statusLock:Z,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Q.isSubagent,updatedAt:yZ()};if($.setRunning)W.status="running",W.endedAt=null,W.exitCode=null;return J.sessions[$.sessionId]=W,this.writeIndex(J),{updated:!0,statusLock:W.statusLock}}async deleteSession($,J){let Q=this.readIndex();if(!Q.sessions[$])return!1;if(delete Q.sessions[$],J){for(let W of Object.values(Q.sessions))if(W.parentSessionId===$)delete Q.sessions[W.sessionId]}return this.writeIndex(Q),!0}async enqueueSpawnRequest($){let J=this.readQueue();J.requests.push({id:J.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:yZ()}),J.nextId+=1,this.writeQueue(J)}async claimSpawnRequest($,J){let Q=this.readQueue(),Z=Q.requests.find((W)=>W.rootSessionId===$&&W.parentAgentId===J&&!W.consumedAt);if(!Z)return;return Z.consumedAt=yZ(),this.writeQueue(Q),Z.task}}class EZ extends z1{constructor($,J={}){super(new tY($),J)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as xM,mkdirSync as gM}from"node:fs";import{resolveSessionDataDir as mM}from"@cline/shared/storage";var bZ=`
476
476
  session_id AS sessionId,
477
477
  source,
478
478
  pid,
@@ -499,7 +499,7 @@ ${W}`,$.config.mode)}function r8($,J){return SM($,J==="plan"?"plan":J==="yolo"?"
499
499
  metadata_json AS metadata,
500
500
  hook_path AS hookPath,
501
501
  messages_path AS messagesPath,
502
- updated_at AS updatedAt`;function hZ($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let J=$.metadata;if(typeof J==="string"&&J.trim())try{let Q=JSON.parse(J);$.metadata=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{$.metadata=null}else $.metadata=null;return $}function kZ($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function oY($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class tY{store;sessionsDirPath;constructor($,J=gM()){this.store=$;this.sessionsDirPath=J}ensureSessionsDir(){if(!IM(this.sessionsDirPath))xM(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
502
+ updated_at AS updatedAt`;function hZ($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let J=$.metadata;if(typeof J==="string"&&J.trim())try{let Q=JSON.parse(J);$.metadata=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{$.metadata=null}else $.metadata=null;return $}function kZ($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function eY($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class $V{store;sessionsDirPath;constructor($,J=mM()){this.store=$;this.sessionsDirPath=J}ensureSessionsDir(){if(!xM(this.sessionsDirPath))gM(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
503
503
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
504
504
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
505
505
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
@@ -515,27 +515,27 @@ ${W}`,$.config.mode)}function r8($,J){return SM($,J==="plan"?"plan":J==="yolo"?"
515
515
  WHERE session_id = ? AND status_lock = ?`,[s(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let J=[],Q=[];if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.endedAt!==void 0)J.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)J.push("exit_code = ?"),Q.push($.exitCode);if($.prompt!==void 0)J.push("prompt = ?"),Q.push($.prompt??null);if($.metadata!==void 0)J.push("metadata_json = ?"),Q.push(kZ($.metadata));if($.parentSessionId!==void 0)J.push("parent_session_id = ?"),Q.push($.parentSessionId??null);if($.parentAgentId!==void 0)J.push("parent_agent_id = ?"),Q.push($.parentAgentId??null);if($.agentId!==void 0)J.push("agent_id = ?"),Q.push($.agentId??null);if($.conversationId!==void 0)J.push("conversation_id = ?"),Q.push($.conversationId??null);if(J.length===0){let f=await this.getSession($.sessionId);return{updated:!!f,statusLock:f?.statusLock??0}}let Z=0;if($.expectedStatusLock!==void 0)Z=$.expectedStatusLock+1,J.push("status_lock = ?"),Q.push(Z);J.push("updated_at = ?"),Q.push(s());let W=`UPDATE sessions SET ${J.join(", ")} WHERE session_id = ?`;if(Q.push($.sessionId),$.expectedStatusLock!==void 0)W+=" AND status_lock = ?",Q.push($.expectedStatusLock);if((this.store.run(W,Q).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Z=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Z}}async deleteSession($,J){let Q=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
516
516
  VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,s()])}async claimSpawnRequest($,J){let Q=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
517
517
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
518
- ORDER BY id ASC LIMIT 1`,[$,J]);if(!Q||typeof Q.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),Q.id]),Q.task??void 0}}class o1 extends z1{store;constructor($,J={}){super(new tY($,J.sessionArtifactsDir),J);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
518
+ ORDER BY id ASC LIMIT 1`,[$,J]);if(!Q||typeof Q.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),Q.id]),Q.task??void 0}}class o1 extends z1{store;constructor($,J={}){super(new $V($,J.sessionArtifactsDir),J);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
519
519
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
520
520
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
521
521
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
522
522
  metadata_json, transcript_path, hook_path, messages_path, updated_at
523
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,s()])}}import{readdirSync as FN}from"node:fs";import{homedir as DN}from"node:os";import{isAbsolute as UN,join as R7,resolve as z7}from"node:path";import{captureSdkError as g$,createSessionId as RN,isLikelyAuthError as zN,normalizeUserInput as LN}from"@cline/shared";import{setHomeDirIfUnset as _N}from"@cline/shared/storage";F0();import{createHandlerAsync as dM}from"@cline/llms";import{estimateTokens as IZ}from"@cline/shared";var JV=200000,xZ=0.9,QV=16384,gZ=20000,eY=1024,$V=2000,ZV=2000,WV=8;function t1($,J){if($.length<=J)return $;return`${$.slice(0,J)}
524
- ...[truncated ${$.length-J} chars]`}function mM($){let J=mZ($);if(typeof J==="string")return J;return J.map((Q)=>{switch(Q.type){case"text":return Q.text;case"file":return`<file path="${Q.path}">
523
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,s()])}}import{readdirSync as DN}from"node:fs";import{homedir as UN}from"node:os";import{isAbsolute as RN,join as R7,resolve as z7}from"node:path";import{captureSdkError as g$,createSessionId as zN,isLikelyAuthError as LN,normalizeUserInput as _N}from"@cline/shared";import{setHomeDirIfUnset as ON}from"@cline/shared/storage";F0();import{createHandlerAsync as lM}from"@cline/llms";import{estimateTokens as IZ}from"@cline/shared";var ZV=200000,xZ=0.9,WV=16384,gZ=20000,JV=1024,QV=2000,jV=2000,fV=8;function t1($,J){if($.length<=J)return $;return`${$.slice(0,J)}
524
+ ...[truncated ${$.length-J} chars]`}function vM($){let J=mZ($);if(typeof J==="string")return J;return J.map((Q)=>{switch(Q.type){case"text":return Q.text;case"file":return`<file path="${Q.path}">
525
525
  ${Q.content}
526
526
  </file>`;case"image":return`[image:${Q.mediaType}]`;default:return""}}).join(`
527
- `)}function mZ($){if(typeof $==="string")return t1($,$V);return $.map((J)=>{switch(J.type){case"text":return{...J,text:t1(J.text,$V)};case"file":return{...J,content:t1(J.content,ZV)};case"image":return J;default:return J}})}function vM($){return Object.entries($).map(([J,Q])=>`${J}=${JSON.stringify(Q)}`).join(", ")}function jV($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let J=[];for(let Q of $.content)switch(Q.type){case"text":J.push(`[${$.role==="user"?"User":"Bot"}]: ${Q.text}`);break;case"thinking":J.push(`[Bot thinking]: ${t1(Q.thinking,2000)}`);break;case"redacted_thinking":J.push("[Bot thinking]: [redacted]");break;case"tool_use":J.push(`[Bot tool calls]: ${Q.name}(${vM(Q.input)})`);break;case"tool_result":J.push(`[Tool result]: ${mM(Q.content)}`);break;case"file":J.push(`[${$.role==="user"?"User":"Bot"} file ${Q.path}]: ${t1(Q.content,ZV)}`);break;case"image":J.push(`[${$.role==="user"?"User":"Bot"} image]: ${Q.mediaType}`);break}return J.join(`
528
- `)}function fV($){return $.map(jV).join(`
527
+ `)}function mZ($){if(typeof $==="string")return t1($,QV);return $.map((J)=>{switch(J.type){case"text":return{...J,text:t1(J.text,QV)};case"file":return{...J,content:t1(J.content,jV)};case"image":return J;default:return J}})}function cM($){return Object.entries($).map(([J,Q])=>`${J}=${JSON.stringify(Q)}`).join(", ")}function XV($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let J=[];for(let Q of $.content)switch(Q.type){case"text":J.push(`[${$.role==="user"?"User":"Bot"}]: ${Q.text}`);break;case"thinking":J.push(`[Bot thinking]: ${t1(Q.thinking,2000)}`);break;case"redacted_thinking":J.push("[Bot thinking]: [redacted]");break;case"tool_use":J.push(`[Bot tool calls]: ${Q.name}(${cM(Q.input)})`);break;case"tool_result":J.push(`[Tool result]: ${vM(Q.content)}`);break;case"file":J.push(`[${$.role==="user"?"User":"Bot"} file ${Q.path}]: ${t1(Q.content,jV)}`);break;case"image":J.push(`[${$.role==="user"?"User":"Bot"} image]: ${Q.mediaType}`);break}return J.join(`
528
+ `)}function YV($){return $.map(XV).join(`
529
529
 
530
- `).trim()}function XV(){let $=new WeakMap;return(J)=>{let Q=J,Z=$.get(Q);if(typeof Z==="number")return Z;let W;try{W=JSON.stringify(J)}catch{W=jV(J)}let j=IZ(W.length);return $.set(Q,j),j}}function a8($){return $.metadata?.kind==="compaction_summary"}function vZ($){if(!a8($))return;let J=$.metadata;if(!J)return;let Q=J.details;return{kind:"compaction_summary",summary:String(J.summary??""),details:{readFiles:Array.isArray(Q?.readFiles)?Q.readFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[],modifiedFiles:Array.isArray(Q?.modifiedFiles)?Q.modifiedFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[]},tokensBefore:Number(J.tokensBefore??0),generatedAt:Number(J.generatedAt??0)}}function cM($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((J)=>J.type==="tool_result")}function s8($){return $.role==="user"&&!cM($)&&!a8($)}function YV($){for(let J=0;J<$.length;J+=1)if(s8($[J]))return J;return-1}function BJ($){for(let J=$.length-1;J>=0;J-=1)if(s8($[J]))return J;return 0}function VV($){for(let J=$.length-1;J>=0;J-=1)if($[J].role==="assistant")return J;return-1}function HV($){for(let J=$.length-1;J>=0;J-=1)if(a8($[J]))return J;return-1}function BV($,J,Q){let Z=BJ($);if(Z<=0)return 0;let W=0,j=$.length;for(let X=$.length-1;X>=0;X-=1)if(W+=Q($[X]),j=X,W>=J)break;if(j<=0)return 0;let f=Math.min(j,Z);while(f>0&&!s8($[f]))f-=1;return f}function n8($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((J)=>n8(J));if($&&typeof $==="object"){let J=$,Q=[];for(let Z of["path","file_path","target_file","new_file_path","old_file_path"])Q.push(...n8(J[Z]));if(Array.isArray(J.files)){for(let Z of J.files)if(Z&&typeof Z==="object")Q.push(...n8(Z.path))}if(Array.isArray(J.file_paths))Q.push(...n8(J.file_paths));return Q}return[]}function i8($,J){let Q=new Set($);for(let Z of J){let W=Z.trim();if(!W)continue;Q.add(W)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function AV($){let J=[],Q=[];for(let Z of $){let W=vZ(Z);if(W){J=i8(J,W.details.readFiles),Q=i8(Q,W.details.modifiedFiles);continue}if(!Array.isArray(Z.content))continue;for(let j of Z.content){if(j.type==="file"){J=i8(J,[j.path]);continue}if(j.type!=="tool_use")continue;let f=n8(j.input);if(j.name==="read_files"){J=i8(J,f);continue}if(j.name==="editor"||j.name==="apply_patch")Q=i8(Q,f)}}return{readFiles:J,modifiedFiles:Q}}function uM($){let J=$.readFiles.length>0?$.readFiles.map((Z)=>`- ${Z}`).join(`
530
+ `).trim()}function VV(){let $=new WeakMap;return(J)=>{let Q=J,Z=$.get(Q);if(typeof Z==="number")return Z;let W;try{W=JSON.stringify(J)}catch{W=XV(J)}let j=IZ(W.length);return $.set(Q,j),j}}function a8($){return $.metadata?.kind==="compaction_summary"}function vZ($){if(!a8($))return;let J=$.metadata;if(!J)return;let Q=J.details;return{kind:"compaction_summary",summary:String(J.summary??""),details:{readFiles:Array.isArray(Q?.readFiles)?Q.readFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[],modifiedFiles:Array.isArray(Q?.modifiedFiles)?Q.modifiedFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[]},tokensBefore:Number(J.tokensBefore??0),generatedAt:Number(J.generatedAt??0)}}function uM($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((J)=>J.type==="tool_result")}function s8($){return $.role==="user"&&!uM($)&&!a8($)}function HV($){for(let J=0;J<$.length;J+=1)if(s8($[J]))return J;return-1}function BJ($){for(let J=$.length-1;J>=0;J-=1)if(s8($[J]))return J;return 0}function BV($){for(let J=$.length-1;J>=0;J-=1)if($[J].role==="assistant")return J;return-1}function AV($){for(let J=$.length-1;J>=0;J-=1)if(a8($[J]))return J;return-1}function KV($,J,Q){let Z=BJ($);if(Z<=0)return 0;let W=0,j=$.length;for(let X=$.length-1;X>=0;X-=1)if(W+=Q($[X]),j=X,W>=J)break;if(j<=0)return 0;let f=Math.min(j,Z);while(f>0&&!s8($[f]))f-=1;return f}function n8($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((J)=>n8(J));if($&&typeof $==="object"){let J=$,Q=[];for(let Z of["path","file_path","target_file","new_file_path","old_file_path"])Q.push(...n8(J[Z]));if(Array.isArray(J.files)){for(let Z of J.files)if(Z&&typeof Z==="object")Q.push(...n8(Z.path))}if(Array.isArray(J.file_paths))Q.push(...n8(J.file_paths));return Q}return[]}function i8($,J){let Q=new Set($);for(let Z of J){let W=Z.trim();if(!W)continue;Q.add(W)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function GV($){let J=[],Q=[];for(let Z of $){let W=vZ(Z);if(W){J=i8(J,W.details.readFiles),Q=i8(Q,W.details.modifiedFiles);continue}if(!Array.isArray(Z.content))continue;for(let j of Z.content){if(j.type==="file"){J=i8(J,[j.path]);continue}if(j.type!=="tool_use")continue;let f=n8(j.input);if(j.name==="read_files"){J=i8(J,f);continue}if(j.name==="editor"||j.name==="apply_patch")Q=i8(Q,f)}}return{readFiles:J,modifiedFiles:Q}}function dM($){let J=$.readFiles.length>0?$.readFiles.map((Z)=>`- ${Z}`).join(`
531
531
  `):"- none",Q=$.modifiedFiles.length>0?$.modifiedFiles.map((Z)=>`- ${Z}`).join(`
532
532
  `):"- none";return`## Files
533
533
  Read:
534
534
  ${J}
535
535
  Modified:
536
- ${Q}`}function KV($,J){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
536
+ ${Q}`}function FV($,J){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
537
537
 
538
- ${uM(J)}`.trim()}function GV($){let J=[`Summarize this session for continuation. Be concise and factual.
538
+ ${dM(J)}`.trim()}function DV($){let J=[`Summarize this session for continuation. Be concise and factual.
539
539
 
540
540
  ## Goal
541
541
  One sentence: what is being built or fixed.
@@ -557,18 +557,18 @@ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.tr
557
557
  ${$.previousSummary.trim()}`);return J.push(`Conversation:
558
558
  ${$.conversationText||"(empty)"}`),J.join(`
559
559
 
560
- `)}function FV($){let J=$.summarizer,Q=(W)=>{if(W.providerId==="openai-codex"){let{maxOutputTokens:j,...f}=W;return{...f,thinking:!1}}return{...W,maxOutputTokens:W.maxOutputTokens??eY,thinking:!1}};if(!J)return Q($.activeProviderConfig);let Z=J.providerConfig?.providerId===J.providerId?J.providerConfig:void 0;return Q({...Z??{},providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey??Z?.apiKey,baseUrl:J.baseUrl??Z?.baseUrl,headers:J.headers??Z?.headers,knownModels:J.knownModels??Z?.knownModels,maxOutputTokens:J.maxOutputTokens??eY})}function DV($){return{role:"user",content:`Context summary:
561
-
562
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function lM($){let J=await dM($.providerConfig),Q="";for await(let Z of J.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Z.type==="text"){Q+=Z.text;continue}if(Z.type==="done"&&!Z.success&&Z.error)throw Error(Z.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Q.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Q.trim()}function pM($){try{return JSON.stringify($).length}catch{return String($).length}}async function UV($){let J=$.context.messages;if(J.length<2)return;let Q=BV(J,$.preserveRecentTokens,$.estimateMessageTokens);if(Q<=0||Q>=J.length)return;let Z=J.slice(0,Q),W=HV(Z),j=W>=0?vZ(Z[W])?.summary:void 0,f=W>=0?Z.slice(W+1):Z;if(f.length===0)return;let X=AV(Z),Y=fV(f),V=GV({previousSummary:j,conversationText:Y,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Z.length,newMessagesToFold:f.length,preservedMessages:J.length-Q,previousSummaryChars:j?.length??0,conversationTextChars:Y.length,summaryRequestChars:V.length,summaryRequestEstimatedTokens:IZ(V.length),newMessagesJsonChars:pM(f),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let H=await lM({providerConfig:FV({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:V,logger:$.logger});if(!H.trim())return;let B=KV(H,X),A=J.reduce((R,D)=>R+$.estimateMessageTokens(D),0),K=[DV({summary:B,fileOps:X,tokensBefore:A}),...J.slice(Q)],G=K.reduce((R,D)=>R+$.estimateMessageTokens(D),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:J.length,messagesAfter:K.length,messagesSummarized:Q,messagesPreserved:J.length-Q,tokensBefore:A,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function LV($){if(a8($))return;if(typeof $.content==="string"){let Q=$.content.trim();return Q?{...$,content:Q}:void 0}let J=$.content.filter((Q)=>Q.type!=="text"||Q.text.trim());if(J.length===0)return;return{...$,content:J.map((Q)=>Q.type==="text"?{...Q,text:Q.text.trim()}:Q.type==="tool_result"?{...Q,content:mZ(Q.content)}:Q)}}function o8($,J){return $.reduce((Q,Z)=>Q+J(Z),0)}function RV($,J){let Q=Math.max(1,J),Z=Math.max(16,Q*4);if(typeof $.content==="string"){let f=t1($.content,Z).trim();return{...$,content:f||"..."}}let W=Z,j=$.content.map((f)=>{if(f.type!=="text"||W<=0)return f;let X=t1(f.text,W).trim();return W-=X.length,{...f,text:X||"..."}});return{...$,content:j}}function rM($,J){let Q=YV($),Z=BJ($),W=VV($),j=[];for(let f=0;f<$.length;f+=1){let X=LV($[f]);if(!X)continue;j.push({index:f,message:X,estimatedTokens:J(X),isFirstUser:f===Q,isLastUser:f===Z,isLastAssistant:f===W})}return j}function zV($,J,Q,Z){let W=$[J];W.message=Q,W.estimatedTokens=Z(Q)}function iM($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_use")J.add(Q.id);return J}function nM($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_result")J.add(Q.tool_use_id);return J}function _V($){return new Set([...iM($.message),...nM($.message)])}function aM($){let J=new Map;for(let Q=0;Q<$.length;Q+=1)for(let Z of _V($[Q])){let W=J.get(Z);if(W)W.add(Q);else J.set(Z,new Set([Q]))}return J}function sM($,J){let Q=aM($),Z=new Set,W=[J];while(W.length>0){let j=W.shift();if(j===void 0||Z.has(j))continue;Z.add(j);for(let f of _V($[j]))for(let X of Q.get(f)??[])if(!Z.has(X))W.push(X)}return Z}function AJ($,J,Q,Z){let W=o8($.map((j)=>j.message),Z);for(let j=0;j<$.length&&W>Q;){if(!J($[j])){j+=1;continue}let f=sM($,j);W-=Array.from(f).reduce((X,Y)=>X+$[Y].estimatedTokens,0);for(let X of Array.from(f).sort((Y,V)=>V-Y))$.splice(X,1)}}function oM($,J,Q){let Z=o8($.map((j)=>j.message),Q);if(Z<=J)return;for(let j=$.length-1;j>=0&&Z>J;j-=1){let f=$[j];if(f.isFirstUser)continue;let X=Math.max(WV,f.estimatedTokens-(Z-J));if(X>=f.estimatedTokens)continue;zV($,j,RV(f.message,X),Q),Z=o8($.map((Y)=>Y.message),Q)}if(Z<=J)return;let W=$.findIndex((j)=>j.isFirstUser);if(W>=0){let j=Math.max(1,$[W].estimatedTokens-(Z-J));zV($,W,RV($[W].message,j),Q)}}function tM($,J){return JSON.stringify($)!==JSON.stringify(J)}function eM($){let J=BJ($);if(J<0||J===0&&!s8($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,J),protectedTail:$.slice(J)}}function OV($){let J=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:Q,protectedTail:Z}=eM($.context.messages);if(Q.length===0)return;let W=rM(Q,$.estimateMessageTokens);if(W.length===0)return;AJ(W,(Y)=>Y.message.role==="assistant"&&!Y.isLastAssistant,J,$.estimateMessageTokens),AJ(W,(Y)=>Y.message.role==="user"&&!Y.isFirstUser&&!Y.isLastUser,J,$.estimateMessageTokens),AJ(W,(Y)=>Y.message.role==="assistant"&&Y.isLastAssistant,J,$.estimateMessageTokens),AJ(W,(Y)=>Y.message.role==="user"&&Y.isLastUser&&!Y.isFirstUser,J,$.estimateMessageTokens),oM(W,J,$.estimateMessageTokens);let j=[...W.map((Y)=>Y.message),...Z];if(!tM($.context.messages,j))return;let f=o8([...Q.map((Y)=>LV(Y)??Y),...Z],$.estimateMessageTokens),X=o8(j,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:j.length,messagesRemoved:$.context.messages.length-j.length,tokensBefore:f,tokensAfter:X,targetTokens:J,maxInputTokens:$.context.maxInputTokens}),{messages:j}}function TV($){try{return JSON.stringify($).length}catch{return String($).length}}function $q($){let J=0,Q=0,Z=0;for(let W of $){if(!Array.isArray(W.content))continue;for(let j of W.content){if(j.type!=="tool_result")continue;let f=TV(j.content);J+=1,Q+=f,Z=Math.max(Z,f)}}return{toolResultCount:J,toolResultSerializedChars:Q,maxToolResultSerializedChars:Z}}var Jq={basic:({context:$,estimateMessageTokens:J,logger:Q})=>OV({context:$,estimateMessageTokens:J,logger:Q}),agentic:({context:$,providerConfig:J,compaction:Q,mode:Z,estimateMessageTokens:W,logger:j})=>UV({context:$,providerConfig:J,summarizer:Q?.summarizer,preserveRecentTokens:Z==="manual"?Math.min(Q?.preserveRecentTokens??gZ,$.triggerTokens):Q?.preserveRecentTokens??gZ,estimateMessageTokens:W,logger:j})};function Qq($){if(typeof $.config.reserveTokens==="number"){let Z=Math.max(0,$.config.reserveTokens),W=Math.max(0,$.maxInputTokens-Z);return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Z=Math.max(0,Math.min($.maxInputTokens-QV,$.maxInputTokens*xZ));return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}let J=$.config.thresholdRatio??xZ,Q=$.maxInputTokens*J;return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:J}}function Zq($){let J=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Q=Math.min(0.95,Math.max(0.05,J)),Z=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*Q)));return{triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}function cZ($,J={}){let Q=$.compaction;if(Q?.enabled!==!0)return;let Z=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},W=XV(),j=Q?.strategy??"basic",f=Jq[j],X=J.mode??"auto",Y=Q?.compact?"custom":j;return async(V)=>{let H=V.apiMessages.reduce((z,M)=>z+W(M),0),B=Q?.maxInputTokens??V.model.info?.maxInputTokens??V.model.info?.contextWindow??JV;if(typeof B!=="number"||!Number.isFinite(B)||B<=0)return;let A=Qq({inputTokens:H,maxInputTokens:B,config:{reserveTokens:Q?.reserveTokens,thresholdRatio:Q?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:j,iteration:V.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:H,maxInputTokens:B,triggerTokens:A.triggerTokens,thresholdRatio:A.thresholdRatio,shouldCompact:A.shouldCompact,messageCount:V.messages.length,apiMessageCount:V.apiMessages.length,apiMessagesJsonChars:TV(V.apiMessages),...$q(V.apiMessages)}),X==="auto"&&!A.shouldCompact)return;let K=X==="manual"?Zq({inputTokens:H,maxInputTokens:B,autoTriggerTokens:A.triggerTokens,manualTargetRatio:J.manualTargetRatio}):A,G={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId,iteration:V.iteration,messages:V.messages,model:V.model,maxInputTokens:B,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:B>0?H/B:0},R=X==="manual"?"manual_compaction":"auto_compaction";V.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:V.iteration,triggerTokens:K.triggerTokens,maxInputTokens:B});let D=V.messages.length,U=Date.now(),F=Q?.compact?await Q.compact(G):await f({context:G,providerConfig:{...Z,abortSignal:V.abortSignal},compaction:Q,mode:X,estimateMessageTokens:W,logger:$.logger}),O=Date.now()-U,T=$.sessionId??V.conversationId,L={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId??void 0};if(F?.messages){let z=F.messages.reduce((M,P)=>M+W(P),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:B,inputTokens:H,afterTokens:z,tokensSaved:H-z,utilizationBefore:`${(H/B*100).toFixed(1)}%`,utilizationAfter:`${(z/B*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length}),P5($.telemetry,{ulid:T,strategy:Y,mode:X,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length,tokensBefore:H,tokensAfter:z,tokensSaved:H-z,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L})}else N5($.telemetry,{ulid:T,strategy:Y,mode:X,reason:"no_result",tokensBefore:H,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L});return F}}F0();function U0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function K0($,J){return{inputTokens:$.inputTokens+Math.max(0,J.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,J.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,J.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,J.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,J.totalCost??0)}}function KJ($){let J=U0();for(let Q of $)J=K0(J,Q);return J}function N2($){return typeof $==="number"&&Number.isFinite($)?$:0}function GJ($){let J=U0();for(let Q of $){let Z=Q.metrics;if(!Z)continue;J=K0(J,{inputTokens:N2(Z.inputTokens),outputTokens:N2(Z.outputTokens),cacheReadTokens:N2(Z.cacheReadTokens),cacheWriteTokens:N2(Z.cacheWriteTokens),totalCost:N2(Z.cost)})}return J}function Wq($){for(let J=$.length-1;J>=0;J-=1){let Q=$[J];if(Q?.role!=="assistant")continue;let Z=N2(Q.metrics?.inputTokens);return Z>0?Z:void 0}return}function jq($){if(!$||typeof $!=="object")return;let J=$,Q=J.skill??J.skill_name??J.skillName;if(typeof Q!=="string")return;let Z=Q.trim();return Z.length>0?Z:void 0}function uZ($){if(!$||typeof $!=="object")return{};let J=$;return{agentId:typeof J.agentId==="string"?J.agentId:void 0,conversationId:typeof J.conversationId==="string"?J.conversationId:void 0,parentAgentId:typeof J.parentAgentId==="string"?J.parentAgentId:void 0}}function L1($){let J=$.agentId?.trim();if(!J)return;let Q=$.parentAgentId?.trim()||void 0,Z=$.teamRole,W="root";if(Z==="teammate")W="team_teammate";else if(Z==="lead")W="team_lead";else if(Q)W="subagent";return{agentId:J,agentKind:W,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Q,createdByAgentId:$.createdByAgentId?.trim()||Q||void 0,isSubagent:Boolean(Q),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Z,teamAgentId:$.teamAgentId?.trim()||void 0}}function fq($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function Xq($){let J=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Q of J){let Z=Q?.trim();if(Z)return Z}return $.isPrimaryAgentEvent?"root":"unknown"}function dZ($,J,Q){let{sessionId:Z,config:W,liveSession:j,emit:f}=$,X=W.telemetry,Y=j?.runtime.teamRuntime,V=Q?.isPrimaryAgentEvent??!0,H=uZ(J),B=L1({agentId:Q?.agentId??H.agentId,conversationId:Q?.conversationId??H.conversationId,parentAgentId:Q?.parentAgentId??H.parentAgentId,createdByAgentId:Q?.createdByAgentId,teamId:Q?.teamId??Y?.getTeamId(),teamName:Q?.teamName??Y?.getTeamName(),teamRole:Q?.teamRole,teamAgentId:Q?.teamAgentId});if(J.type==="content_start"&&J.contentType==="tool"&&J.toolName==="skills"){let A=jq(J.input);if(A)z5(X,{ulid:Z,skillName:A,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:W.providerId,modelId:W.modelId,...B})}if(J.type==="content_end"&&J.contentType==="tool"){let A=J.toolName??"unknown",K=!J.error;if(R5(X,{ulid:Z,tool:A,autoApproved:void 0,success:K,modelId:W.modelId,provider:W.providerId,...B}),!K&&(A==="editor"||A==="apply_patch"))L5(X,{ulid:Z,modelId:W.modelId,provider:W.providerId,errorType:J.error,...B})}if(J.type==="notice"&&J.reason==="api_error")R4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.message,...B});if(J.type==="error")R4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.error?.message??"unknown error",...B});if(J.type==="usage"&&j?.turnUsageBaseline){let A=fq(J);if(V){j.turnPrimaryUsage=K0(j.turnPrimaryUsage??U0(),A);let G=K0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Z,G),g2(X,{ulid:Z,provider:W.providerId,model:W.modelId,source:"assistant",mode:W.mode,...B}),D5(X,{ulid:Z,tokensIn:J.inputTokens,tokensOut:J.outputTokens,cacheWriteTokens:J.cacheWriteTokens,cacheReadTokens:J.cacheReadTokens,totalCost:J.cost,model:W.modelId,...B})}else{let G=Xq({isPrimaryAgentEvent:V,overrides:Q,eventMetadata:H}),R=j.turnUsageByAgent??new Map;j.turnUsageByAgent=R,R.set(G,K0(R.get(G)??U0(),A))}let K=K0(j.turnPrimaryUsage??U0(),KJ(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Z,K0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,K))}if(J.type==="iteration_end"&&V)$.persistMessages(Z,j?.agent.getMessages()??[],j?.config.systemPrompt);f({type:"agent_event",payload:{sessionId:Z,event:J,teamAgentId:Q?.teamAgentId,teamRole:Q!==void 0?Q.teamRole??(V?"lead":void 0):void 0}}),f({type:"chunk",payload:{sessionId:Z,stream:"agent",chunk:hX(J),ts:Date.now()}})}function e1($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as kq}from"@cline/shared";import{spawn as Dq}from"node:child_process";import{appendFileSync as Uq,readFileSync as Rq}from"node:fs";import{join as zq}from"node:path";import{augmentNodeCommandForDebug as NV,withResolvedClineBuildEnv as aZ}from"@cline/shared";import{ensureHookLogDir as qV}from"@cline/shared/storage";function FJ($,J){if(!J)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:J}}import{existsSync as Yq,readdirSync as Vq}from"node:fs";import{basename as Hq,extname as Bq,join as Aq}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as MV,resolveHooksConfigSearchPaths as Kq}from"@cline/shared/storage";function lZ($){return Kq($)}var DJ;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(DJ||={});var pZ={["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"},Gq=new Map(Object.values(DJ).map(($)=>[$.toLowerCase(),$])),Fq=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function rZ($){let J=Bq($).toLowerCase();if(!Fq.has(J))return;let Q=Hq($,J).trim().toLowerCase();return Gq.get(Q)}function w2($){let J=[],Q=new Set,Z=lZ($).filter((W)=>Yq(W));for(let W of Z)try{for(let j of Vq(W,{withFileTypes:!0})){if(!j.isFile())continue;let f=rZ(j.name);if(!f)continue;let X=Aq(W,j.name);if(Q.has(X))continue;Q.add(X),J.push({fileName:f,hookEventName:pZ[f],path:X})}}catch{}return J.sort((W,j)=>W.path.localeCompare(j.path))}function RJ($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))J[Q]=typeof Z==="string"?Z:JSON.stringify(Z);return J}function UJ($,J,Q){let Z=Q instanceof Error?`: ${Q.message}`:"",W=`${J}${Z}`;if($){try{$.log(W,{severity:"warn",...Q!==void 0?{error:Q}:{}})}catch{}return}console.warn(W)}function Lq($,J){if(!J)return $;if(!$)return{...J};let Q=[$.context,J.context].filter((W)=>typeof W==="string"&&W.length>0).join(`
563
- `),Z=[...$.appendMessages??[],...J.appendMessages??[]];return{cancel:$.cancel===!0||J.cancel===!0?!0:void 0,review:$.review===!0||J.review===!0?!0:void 0,context:Q||void 0,overrideInput:J.overrideInput!==void 0?J.overrideInput:$.overrideInput,systemPrompt:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,appendMessages:Z.length>0?Z:void 0}}function _q($){if(!$||typeof $!=="object")return;let J=$,Q=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Q,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function iZ($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function G0($,J){let Q=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Z={rootSessionId:J.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Z,workspaceRoots:J.workspacePath?[J.workspacePath]:[],workspaceInfo:J.workspaceInfo,userId:Q,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function Oq($){let J=$.trim();if(!J)return{};let Z=J.split(`
564
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function Tq($,J){let Q=$.stdin;if(!Q)throw Error("hook command failed to create stdin");await new Promise((Z,W)=>{let j=!1,f=()=>{Q.off("error",Y),Q.off("finish",V),$.off("close",H)},X=(B)=>{if(j)return;if(j=!0,f(),B){let A=B.code;if(A==="EPIPE"||A==="ERR_STREAM_DESTROYED"){Z();return}W(B);return}Z()},Y=(B)=>X(B),V=()=>X(),H=()=>X();Q.on("error",Y),Q.once("finish",V),$.once("close",H);try{Q.end(J)}catch(B){X(B)}})}async function wV($,J){if(J.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await PV($,J)}catch(Q){let Z=Pq(J.command,process.platform,Q);if(!Z)throw Q;return await PV($,{...J,command:Z})}}async function PV($,J){let Q=NV(J.command,{env:J.env,debugRole:"hook"}),Z=Dq(Q[0],Q.slice(1),{cwd:J.cwd,env:aZ(J.env),stdio:J.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:J.detached,windowsHide:!0}),W=new Promise((A)=>{Z.once("spawn",()=>A())}),j=new Promise((A,K)=>{Z.once("error",(G)=>K(G))}),f=JSON.stringify($);if(await Promise.race([W,j]),await Tq(Z,f),J.detached){Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("hook command failed to create stdout/stderr");let X="",Y="",V=!1,H;Z.stdout.on("data",(A)=>{X+=A.toString()}),Z.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,Z.kill("SIGKILL")},J.timeoutMs);Z.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=Oq(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,j])}function Mq($){try{let Q=Rq($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Q?.startsWith("#!"))return;let Z=Q.slice(2).trim();if(!Z)return;let W=Z.split(/\s+/).filter(Boolean);return W.length>0?W:void 0}catch{return}}function qq($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function Pq($,J=process.platform,Q){if(J!=="win32"||!qq(Q))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function SV($){if($.length===0)return;let[J,...Q]=$,Z=J.replace(/\\/g,"/").toLowerCase(),W=Z.split("/").at(-1)??Z;if(W==="env")return SV(Q);if(W==="bash"||W==="sh"||W==="zsh")return[W,...Q];if(W==="python3"||W==="python")return process.platform==="win32"?["py","-3",...Q]:[W,...Q];return $}function Nq($){let J=Mq($);if(J&&J.length>0)return[...SV(J)??J,$];let Q=$.toLowerCase();if(Q.endsWith(".sh")||Q.endsWith(".bash")||Q.endsWith(".zsh"))return["bash",$];if(Q.endsWith(".js")||Q.endsWith(".mjs")||Q.endsWith(".cjs"))return NV(["node",$],{debugRole:"hook"});if(Q.endsWith(".ts")||Q.endsWith(".mts")||Q.endsWith(".cts"))return["bun","run",$];if(Q.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Q.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function wq($){let J={};for(let Q of w2($)){if(!Q.hookEventName)continue;let Z=Q.hookEventName,W=J[Z]??[];W.push(Nq(Q.path)),J[Z]=W}return J}async function Sq($){let J;for(let Q of $.commands){let Z=Q.join(" ");try{let W=await wV($.payload,{command:Q,cwd:$.cwd,env:aZ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(W?.timedOut){UJ($.logger,`hook command timed out: ${Z}`);continue}if(W?.parseError){UJ($.logger,`hook command returned invalid JSON control output: ${Z} (${W.parseError})`);continue}J=Lq(J,_q(W?.parsedJson))}catch(W){UJ($.logger,`hook command failed: ${Z}`,W)}}return J}function k$($){for(let J of $.commands){let Q=J.join(" ");wV($.payload,{command:J,cwd:$.cwd,env:aZ(process.env),detached:!0}).catch((Z)=>{UJ($.logger,`hook command failed: ${Q}`,Z)})}}function $$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function nZ($,J){return{...$$($.snapshot),userMessage:J}}function CV($){return{...$$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function yV($){return{...$$($.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 EV($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function Cq($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}function zJ($){let J={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Q=(Z)=>{let W=`${JSON.stringify({ts:new Date().toISOString(),...Z})}
565
- `,f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??zq(qV(),"hooks.jsonl");qV(f),Uq(f,W,"utf8")};return{beforeRun:async(Z)=>{let W=nZ(Z,"");Q({...G0(W,J),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Z)=>{let W=CV(Z);Q({...G0(W,J),hookName:"tool_call",iteration:W.iteration,tool_call:{id:W.call.id,name:W.call.name,input:W.call.input},preToolUse:{toolName:W.call.name,parameters:RJ(W.call.input)}});return},afterTool:async(Z)=>{let W=yV(Z);Q({...G0(W,J),hookName:"tool_result",iteration:W.iteration,tool_result:W.record,postToolUse:{toolName:W.record.name,parameters:RJ(W.record.input),result:typeof W.record.output==="string"?W.record.output:JSON.stringify(W.record.output),success:!W.record.error,executionTimeMs:W.record.durationMs}});return},afterRun:async({snapshot:Z,result:W})=>{let j=$$(Z);if(W.status==="completed"){Q({...G0(j,J),hookName:"agent_end",iteration:W.iterations,turn:{outputText:W.outputText,status:W.status},taskComplete:{taskMetadata:{}}});return}if(W.status==="aborted"||iZ(W.error?.message)){Q({...G0(j,J),hookName:"agent_abort",reason:W.error?.message,taskCancel:{taskMetadata:{}}});return}if(W.error)Q({...G0(j,J),hookName:"agent_error",iteration:W.iterations,error:{name:W.error.name,message:W.error.message,stack:W.error.stack}})},onEvent:async(Z)=>{if(Z.type!=="message-added"||Z.message.role!=="user")return;let W=nZ({snapshot:Z.snapshot},EV(Z.message.content));Q({...G0(W,J),hookName:"prompt_submit",userPromptSubmit:{prompt:W.userMessage,attachments:[]}})}}}function sZ($){let J=wq($.workspacePath);if(!Object.values(J).some((B)=>B.length>0))return;let Z=async(B,A)=>{let K=J[A]??[];if(K.length===0)return;k$({commands:K,cwd:$.cwd,logger:$.logger,payload:A==="agent_resume"?{...G0(B,$),hookName:A,taskResume:{taskMetadata:{},previousState:{}}}:{...G0(B,$),hookName:A,taskStart:{taskMetadata:{}}}})},W=async(B)=>{let A=J.prompt_submit??[];if(A.length>0)k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},j=async(B)=>{let A=J.tool_call??[];if(A.length===0)return;return Sq({commands:A,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...G0(B,$),hookName:"tool_call",iteration:B.iteration,tool_call:{id:B.call.id,name:B.call.name,input:B.call.input},preToolUse:{toolName:B.call.name,parameters:RJ(B.call.input)}}})},f=async(B)=>{let A=J.tool_result??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:RJ(B.record.input),result:typeof B.record.output==="string"?B.record.output:JSON.stringify(B.record.output),success:!B.record.error,executionTimeMs:B.record.durationMs}}})},X=async(B)=>{let A=J.agent_end??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"agent_end",iteration:B.iteration,turn:B.turn,taskComplete:{taskMetadata:{}}}})},Y=async(B)=>{let A=J.agent_error??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"agent_error",iteration:B.iteration,error:{name:B.error.name,message:B.error.message,stack:B.error.stack}}})},V=async(B)=>{if(iZ(B.reason)){let K=J.agent_abort??[];if(K.length>0)k$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let A=J.session_shutdown??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"session_shutdown",reason:B.reason}})},H={};if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0||(J.prompt_submit?.length??0)>0){if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0)H.beforeRun=async(B)=>{let A=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Z($$(B.snapshot),A);return};if((J.prompt_submit?.length??0)>0)H.onEvent=async(B)=>{if(B.type!=="message-added"||B.message.role!=="user")return;await W(nZ({snapshot:B.snapshot},EV(B.message.content)))}}if((J.tool_call?.length??0)>0)H.beforeTool=async(B)=>{let A=await j(CV(B));return Cq(A)};if((J.tool_result?.length??0)>0)H.afterTool=async(B)=>{await f(yV(B));return};if((J.agent_end?.length??0)>0)H.afterRun=async({snapshot:B,result:A})=>{if(A.status!=="completed")return;await X({...$$(B),iteration:A.iterations,turn:{outputText:A.outputText,status:A.status}})};if((J.agent_error?.length??0)>0||(J.agent_abort?.length??0)>0||(J.session_shutdown?.length??0)>0){let B=H.afterRun;H.afterRun=async(A)=>{await B?.(A);let{snapshot:K,result:G}=A;if(G.status==="aborted"||iZ(G.error?.message)){await V({...$$(K),reason:G.error?.message});return}if(G.error)await Y({...$$(K),iteration:G.iterations,error:G.error})}}return H}function LJ($){return FJ("core.hook_config_files",sZ($))}function I$($,J){let Q=$.map((Z)=>Z[J]).filter((Z)=>typeof Z==="function");if(Q.length===0)return;return async(Z)=>{let W;for(let j of Q){let f=await j(Z);if(!f||typeof f!=="object")continue;let X=f;W={...W??{},...X,stop:W?.stop===!0||X.stop===!0?!0:X.stop,options:W?.options||X.options?{...W?.options??{},...X.options??{}}:void 0}}return W}}function t8($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return;return{beforeRun:I$(J,"beforeRun"),afterRun:I$(J,"afterRun"),beforeModel:I$(J,"beforeModel"),afterModel:I$(J,"afterModel"),beforeTool:I$(J,"beforeTool"),afterTool:I$(J,"afterTool"),onEvent:I$(J,"onEvent")}}import{z as J$}from"zod";var e8=e$;var bV=J$.object({settings:e$,updatedAt:J$.string().datetime(),tokenSource:J$.enum(["manual","oauth","migration"]).default("manual")}),_J=J$.object({version:J$.literal(1),lastUsedProvider:J$.string().min(1).optional(),providers:J$.record(J$.string(),bV)});function S2(){return{version:1,providers:{}}}p0();import{upsertWorkspaceInfo as yq,WorkspaceManifestSchema as oZ}from"@cline/shared";class OJ{manifest;listeners=new Set;constructor($){this.manifest=oZ.parse($??{workspaces:{}})}async addWorkspacePath($){let J=await c6($);return this.manifest=yq(this.manifest,J),this.emit({type:"workspace_added",workspace:J}),J}async switchWorkspace($){let J=T$($),Q=this.manifest.workspaces[J];if(Q)return this.manifest=oZ.parse({...this.manifest,currentWorkspacePath:J}),this.emit({type:"workspace_switched",workspace:Q}),Q;let Z=await this.addWorkspacePath(J);return this.manifest=oZ.parse({...this.manifest,currentWorkspacePath:Z.rootPath}),this.emit({type:"workspace_switched",workspace:Z}),Z}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let J=T$($);return this.manifest.workspaces[J]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let J of this.listeners)J($)}}F0();import{createHash as Eq}from"node:crypto";var hV=new Set,kV=new Set;function bq($){return Eq("sha256").update($).digest("hex")}function hq($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function IV($){if(!$.telemetry)return;let J=bq($.rootPath),Q=$.rootCount??1;if(!hV.has(J))hV.add(J),A5($.telemetry,{root_count:Q,vcs_types:hq($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!kV.has(J)){kV.add(J);let Z=Error($.initError.message);Z.name=$.initError.errorType||"Error",K5($.telemetry,Z,{fallback_to_single_root:!0,workspace_count:Q})}}function Iq($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function xq($,J,Q){if(J.length>0)for(let j of J)Q?.log(j.message,{severity:"warn"});if($.length===0)return;let Z=$.slice(0,3).map(Iq).join("; "),W=$.length>3?`; and ${$.length-3} more`:"";Q?.log(`Some plugins failed to initialize. ${Z}${W}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Q?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function gq($,J){let Q=typeof $.thinking==="boolean",Z=typeof $.reasoningEffort==="string";if(!Q&&!Z)return J;return{...J??{},...Q?{enabled:$.thinking}:{},...Z?{effort:$.reasoningEffort}:{}}}function xV($,J){return kq($,J)}function mq($){let J=0;for(let Q of $??[]){if(Q.role!=="user")continue;if(("metadata"in Q&&Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0)?.kind==="recovery_notice")continue;J+=1}return J}function vq($){let J={...$.storedHeaders??{},...$.configHeaders??{}},Q=$.accountId?.trim()||cq($.accessToken);if(J.originator="cline",J.session_id=$.sessionId,J["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,Q)J["ChatGPT-Account-Id"]=Q;return J}function cq($){let J=$?.trim();if(!J)return;let Q=R0(J),Z=Q?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let W=Q?.organizations?.[0]?.id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return}function uq($,J,Q,Z,W){let j=Q.getProviderSettings($.providerId),f=Z||j?.modelCatalog?{...Z??{},...j?.modelCatalog??{}}:void 0,X=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,Y={...j??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??j?.apiKey,baseUrl:$.baseUrl??j?.baseUrl,headers:$.providerId==="openai-codex"?vq({sessionId:J,configHeaders:$.headers,storedHeaders:j?.headers,accountId:j?.auth?.accountId,accessToken:$.apiKey??j?.auth?.accessToken??j?.apiKey}):$.headers??j?.headers,reasoning:gq($,j?.reasoning),modelCatalog:f},V={...V1(Y),...X??{}};if($.knownModels)V.knownModels=$.knownModels;if($.extensionContext)V.extensionContext=$.extensionContext;let B=$.fetch??V.fetch??W;if(B)V.fetch=B;return V}async function gV($){let{input:J,sessionId:Q,providerSettingsManager:Z,defaultTelemetry:W,defaultCapabilities:j,defaultToolPolicies:f,defaultFetch:X,onPluginEvent:Y,onTeamEvent:V,createSubAgentLifecycleCallbacks:H,createSpawnTool:B,localRuntime:A,readSessionMetadata:K,writeSessionMetadata:G}=$,R=e1(J.config),{modelCatalogDefaults:D,userInstructionService:U,configExtensions:F,onTeamRestored:O,...T}=A??{},L=Object.keys(T).length>0?T:void 0,{workspaceInfo:z,workspaceMetadata:M,durationMs:P,vcsType:C,initError:m}=await DX(R),n=L?.extensionContext,o={...n??{},workspace:{...z,...n?.workspace??{}},session:{...n?.session??{},sessionId:Q},logger:n?.logger??L?.logger,telemetry:n?.telemetry??L?.telemetry??W};IV({telemetry:o.telemetry,rootPath:z.rootPath,workspaceInfo:z,rootCount:1,vcsType:C,durationMs:P,initError:m,featureFlagEnabled:!0});let a=LJ({cwd:J.config.cwd,workspacePath:R,rootSessionId:Q,logger:L?.logger,workspaceInfo:z}),l0=bX(L?.hooks)?void 0:zJ({rootSessionId:Q,workspacePath:R,workspaceInfo:z}),f$=t8([L?.hooks,l0]),p;if(xV(F,"plugins"))try{p=await n4({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:J.config.cwd,onEvent:Y,providerId:J.config.providerId,modelId:J.config.modelId,workspaceInfo:z,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),xq(p.failures,p.warnings,L?.logger)}catch(i$){let X5=i$ instanceof Error?i$.message:String(i$);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${X5})`)}let N=r9(a?[a]:void 0,r9(L?.extensions,jQ(p?.extensions))),X0=xV(F,"plugins")?a2(p?.pluginPaths??[]):void 0,J0={...J.config,...L??{},sessionId:Q,hooks:f$,extensions:N,extensionContext:o,telemetry:o.telemetry},T0=uq(J0,Q,Z,D,X),p$=t8([J0.hooks,J0.checkpoint?.enabled===!0?EY({cwd:J0.cwd,sessionId:Q,logger:J0.logger,createCheckpoint:J0.checkpoint?.createCheckpoint,initialRunCount:mq(J.initialMessages),readSessionMetadata:K,writeSessionMetadata:G}):void 0]),j1={...J0,providerConfig:T0,workspaceMetadata:M,hooks:p$},o0=J.toolPolicies??J0.toolPolicies??f,x2=L0(j,J.capabilities),r$=x2?.requestToolApproval,A4=x2?.toolExecutors,f1=H?.(j1),K4=new OJ({currentWorkspacePath:z.rootPath,workspaces:{[z.rootPath]:z}});return{effectiveInput:J,config:j1,providerConfig:T0,workspaceMetadata:M,workspaceInfo:z,extensions:N,hooks:p$,toolPolicies:o0,requestToolApproval:r$,pluginSandboxShutdown:p?.shutdown,runtimeBuilderInput:{config:j1,hooks:p$,extensions:N,onTeamEvent:V,createSpawnTool:B,onTeamRestored:O,onSubAgentEvent:f1?.onSubAgentEvent,onSubAgentStart:f1?.onSubAgentStart,onSubAgentEnd:f1?.onSubAgentEnd,userInstructionService:U,pluginSkillDirectories:X0,configExtensions:F,toolExecutors:A4,toolPolicies:o0,workspaceManager:K4,logger:j1.logger,telemetry:j1.telemetry,requestToolApproval:r$}}}import{resolveDocumentsExtensionPath as dq}from"@cline/shared/storage";F0();function mV($,J,Q,Z,W){if(Q)F5($.telemetry,{ulid:J,apiProvider:$.providerId,...W});else G5($.telemetry,{ulid:J,apiProvider:$.providerId,...W});lq($.telemetry,{workspacePath:Z})}function lq($,J){let Q=dq("Hooks"),Z=w2(J.workspacePath),W=new Map;for(let j of Z){let f=j.hookEventName??"unknown",X=W.get(f)??{global:0,workspace:0};if(j.path===Q||j.path.startsWith(`${Q}/`))X.global+=1;else X.workspace+=1;W.set(f,X)}for(let[j,f]of W.entries())q5($,j,f.global,f.workspace)}function vV($,J){for(let Q of J.mentions)T5($,Q,J.matchedFiles.includes(Q)?1:0,"file",!J.matchedFiles.includes(Q));for(let Q of J.matchedFiles)_5($,"file",Q.length);for(let Q of J.ignoredMentions)O5($,"file","not_found",Q)}import{chmodSync as WH,existsSync as Z7,mkdirSync as TP,readFileSync as MP,writeFileSync as qP}from"node:fs";import{basename as jH,dirname as W7}from"node:path";import{resolveProviderSettingsPath as PP}from"@cline/shared/storage";import{existsSync as pq,mkdirSync as rq,readFileSync as iq,writeFileSync as nq}from"node:fs";import{mkdir as aq,readFile as sq,writeFile as oq}from"node:fs/promises";import{dirname as tZ,join as tq}from"node:path";import*as N0 from"@cline/llms";import{ModelCapabilitySchema as eq,ProviderCapabilitySchema as $P,ProviderClientSchema as JP,ProviderProtocolSchema as QP}from"@cline/shared";import{z as l}from"zod";var ZP=l.object({id:l.string().optional(),name:l.string().optional(),maxTokens:l.number().optional(),contextWindow:l.number().optional(),maxInputTokens:l.number().optional(),capabilities:l.array(eq).optional(),supportsVision:l.boolean().optional(),supportsAttachments:l.boolean().optional(),supportsReasoning:l.boolean().optional()}).passthrough(),WP=l.object({name:l.string(),baseUrl:l.string(),defaultModelId:l.string().optional(),protocol:QP.optional(),client:JP.optional(),capabilities:l.array($P).optional(),modelsSourceUrl:l.string().optional()}).passthrough(),cV=l.object({provider:WP.optional(),models:l.record(l.string(),ZP).optional()}).passthrough(),uV=l.object({version:l.literal(1),providers:l.record(l.string(),cV)}),jP=l.object({version:l.literal(1),providers:l.record(l.string(),l.unknown())}),TJ=new Set;function dV($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function x$($){return tq(tZ($.getFilePath()),"models.json")}function MJ(){return{version:1,providers:{}}}function lV($){let J=jP.safeParse($);if(!J.success)return MJ();let Q={};for(let[Z,W]of Object.entries(J.data.providers)){let j=cV.safeParse(W);if(j.success)Q[Z]=j.data}return{version:1,providers:Q}}function eZ($){if(!pq($))return MJ();try{let J=iq($,"utf8");return lV(JSON.parse(J))}catch{}return MJ()}async function C2($){try{let J=await sq($,"utf8");return lV(JSON.parse(J))}catch{}return MJ()}function pV($,J){rq(tZ($),{recursive:!0});let Q=uV.parse(J);nq($,`${JSON.stringify(Q,null,2)}
566
- `,"utf8")}async function qJ($,J){await aq(tZ($),{recursive:!0});let Q=uV.parse(J);await oq($,`${JSON.stringify(Q,null,2)}
567
- `,"utf8")}function rV($,J){return{id:$,name:J.name??$,supportsAttachments:J.capabilities?.includes("files"),supportsVision:J.capabilities?.includes("images"),supportsReasoning:J.capabilities?.includes("reasoning")||J.thinkingConfig!=null}}function iV($){if(!$||$.length===0)return;let J=new Set;if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("tools"))J.add("tools");return J.size>0?[...J]:void 0}function nV($){let J=new Set;if(!$||$.length===0)return[...J];if($.includes("streaming"))J.add("streaming");if($.includes("tools"))J.add("tools");if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("vision"))J.add("images"),J.add("files");return[...J]}function fP($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function aV($,J){return $??J??"openai-chat"}function sV($,J,Q){return $??Q??(J==="openai-responses"?"openai":"openai-compatible")}function oV($,J,Q){let Z=new Set(J?.capabilities??Q??[]);if(J?.supportsVision)Z.add("images");if(J?.supportsAttachments)Z.add("files");if(J?.supportsReasoning)Z.add("reasoning");return{id:$,name:J?.name??$,maxTokens:J?.maxTokens,contextWindow:J?.contextWindow,maxInputTokens:J?.maxInputTokens,capabilities:Z.size>0?[...Z]:void 0}}function XP($,J){for(let[Q,Z]of Object.entries(J??{})){let W=Z.id?.trim()||Q.trim();if(!W)continue;N0.registerModel($,W,oV(W,Z))}}function YP($,J,Q){return{...J??{},id:$,name:J?.name??$,capabilities:J?.capabilities??Q}}function VP($){return Object.assign({},...N0.resolveProviderModelCatalogKeys($).map((Q)=>N0.getGeneratedModelsForProvider(Q)))}function HP($){let J=$.provider.trim();if(!J||N0.isBuiltInProviderId(J))return;let Q=$.baseUrl?.trim();if(!Q)return;let Z=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J],W=VP(J),j=nV($.capabilities),f=j.length>0?j:void 0,X=$.model?.trim(),Y={...W,...Z?.models??{}};if(X)Y[X]=YP(X,Y[X],f);let V=Object.keys(Y).filter(Boolean),H=X||V[0];if(!H)return;let B=aV($.protocol,Z?.provider.protocol),A=sV($.client,B,Z?.provider.client);N0.registerProvider({provider:{id:J,name:Z?.provider.name??dV(J),description:Z?.provider.description,protocol:B,client:A,baseUrl:Q,modelsSourceUrl:Z?.provider.modelsSourceUrl,defaultModelId:H,capabilities:iV($.capabilities)??Z?.provider.capabilities,source:"file"},models:Y})}function PJ($){for(let J of Object.values($.providers))HP(J.settings)}function $4($,J){let Q=J.models??{};if(!fP(J.provider)){XP($,Q);return}let Z=nV(J.provider.capabilities),W=Object.entries(Q).map(([V,H])=>({id:H.id?.trim()||V.trim(),model:H})).filter(({id:V})=>V.length>0),j=J.provider.defaultModelId?.trim()||W[0]?.id||"default",f=aV(J.provider.protocol,void 0),X=sV(J.provider.client,f,void 0),Y=Object.fromEntries(W.map(({id:V,model:H})=>[V,{...oV(V,H,Z.length>0?Z:void 0),status:"active"}]));N0.registerProvider({provider:{id:$,name:J.provider.name.trim()||dV($),protocol:f,client:X,baseUrl:J.provider.baseUrl,modelsSourceUrl:J.provider.modelsSourceUrl,defaultModelId:j,capabilities:iV(J.provider.capabilities),source:"file"},models:Y})}function tV($){let J=x$($);if(TJ.has(J))return;let Q=eZ(J);for(let[Z,W]of Object.entries(Q.providers))$4(Z,W);TJ.add(J)}async function eV($){let J=x$($);if(TJ.has(J))return;let Q=await C2(J);for(let[Z,W]of Object.entries(Q.providers))$4(Z,W);TJ.add(J)}import{existsSync as BP,readFileSync as AP}from"node:fs";import{dirname as KP,join as $7}from"node:path";import*as wJ from"@cline/llms";import{resolveClineDataDir as GP}from"@cline/shared/storage";var NJ="openai",QH=wJ.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,$H=128000;function ZH($){let J=$?.trim();if(!J)return;try{let Q=JSON.parse(J);if(!Q)return;let Z=typeof Q.expiresAt==="number"&&Number.isFinite(Q.expiresAt)?Q.expiresAt<10000000000?Q.expiresAt*1000:Q.expiresAt:void 0;return{accessToken:Q.idToken,refreshToken:Q.refreshToken,expiresAt:Z,accountId:Q.userInfo?.id}}catch{return}}function S($){let J=$?.trim();return J?J:void 0}function JH($){if(!BP($))return;try{let J=AP($,"utf8"),Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return}function FP($){let J=$.dataDir??GP(),Q=$.globalStatePath??$7(J,"globalState.json"),Z=$.secretsPath??$7(J,"secrets.json"),W=JH(Q),j=JH(Z);if(!W&&!j)return;return{globalState:W??{},secrets:j??{}}}function J7($){if($===NJ)return QH;return $}function DP($,J,Q,Z){let W=Q==="plan"?"planMode":"actMode",j=J===Z?S(Q==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${W}OpenRouterModelId`,cline:`${W}ClineModelId`,openai:`${W}OpenAiModelId`,ollama:`${W}OllamaModelId`,lmstudio:`${W}LmStudioModelId`,litellm:`${W}LiteLlmModelId`,requesty:`${W}RequestyModelId`,together:`${W}TogetherModelId`,fireworks:`${W}FireworksModelId`,sapaicore:`${W}SapAiCoreModelId`,groq:`${W}GroqModelId`,baseten:`${W}BasetenModelId`,huggingface:`${W}HuggingFaceModelId`,"huawei-cloud-maas":`${W}HuaweiCloudMaasModelId`,oca:`${W}OcaModelId`,aihubmix:`${W}AihubmixModelId`,hicap:`${W}HicapModelId`,nousResearch:`${W}NousResearchModelId`,"vercel-ai-gateway":`${W}VercelAiGatewayModelId`}[J];return(X?S(typeof $[X]==="string"?$[X]:void 0):void 0)??j}function UP($,J,Q){let Z=Q==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,W=Q==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,j=Q==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,f=(J==="gemini"?W:void 0)??Z,X=f==="none"||f==="low"||f==="medium"||f==="high"?f:void 0,Y=typeof j==="number"&&Number.isInteger(j)&&j>0?j:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function RP($){let J=$["openai-codex-oauth-credentials"];if(!J)return;try{let Q=JSON.parse(J),Z=S(Q.access_token),W=S(Q.refresh_token),j=S(Q.accountId);if(!Z&&!W&&!j)return;return{...Z?{apiKey:Z}:{},auth:{...Z?{accessToken:Z}:{},...W?{refreshToken:W}:{},...j?{accountId:j}:{}}}}catch{return}}function zP($){let J=wJ.getGeneratedModelsForProvider($);return Object.keys(J)[0]??void 0}function LP($,J,Q,Z){let W=J7($),j=S(Z==="plan"?J.planModeApiProvider:J.actModeApiProvider),f=DP(J,$,Z,j)??zP(W),X=UP(J,W,Z),Y=typeof J.requestTimeoutMs==="number"&&Number.isInteger(J.requestTimeoutMs)&&J.requestTimeoutMs>0?J.requestTimeoutMs:void 0,V={anthropic:Q.apiKey,cline:Q.clineApiKey,openai:Q.openAiApiKey,"openai-native":Q.openAiNativeApiKey,openrouter:Q.openRouterApiKey,bedrock:Q.awsBedrockApiKey,gemini:Q.geminiApiKey,ollama:Q.ollamaApiKey,deepseek:Q.deepSeekApiKey,requesty:Q.requestyApiKey,together:Q.togetherApiKey,fireworks:Q.fireworksApiKey,qwen:Q.qwenApiKey,doubao:Q.doubaoApiKey,mistral:Q.mistralApiKey,litellm:Q.liteLlmApiKey,asksage:Q.asksageApiKey,xai:Q.xaiApiKey,moonshot:Q.moonshotApiKey,zai:Q.zaiApiKey,huggingface:Q.huggingFaceApiKey,nebius:Q.nebiusApiKey,sambanova:Q.sambanovaApiKey,cerebras:Q.cerebrasApiKey,groq:Q.groqApiKey,"huawei-cloud-maas":Q.huaweiCloudMaasApiKey,baseten:Q.basetenApiKey,"vercel-ai-gateway":Q.vercelAiGatewayApiKey,dify:Q.difyApiKey,minimax:Q.minimaxApiKey,hicap:Q.hicapApiKey,aihubmix:Q.aihubmixApiKey,nousResearch:Q.nousResearchApiKey,oca:Q.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,RP(Q));if($==="cline")try{let U=S(Q["cline:clineAccountId"]);if(U)H.auth={...H.auth??{},...ZH(U)}}catch{}if($===NJ&&J.openAiHeaders)H.headers=J.openAiHeaders;if($==="bedrock"){let U=J.awsAuthentication==="profile"||J.awsUseProfile===!0;H.aws={accessKey:S(Q.awsAccessKey),secretKey:S(Q.awsSecretKey),sessionToken:S(Q.awsSessionToken),region:S(J.awsRegion),authentication:J.awsAuthentication,profile:U?S(J.awsProfile):void 0,usePromptCache:J.awsBedrockUsePromptCache,useCrossRegionInference:J.awsUseCrossRegionInference,useGlobalInference:J.awsUseGlobalInference,endpoint:S(J.awsBedrockEndpoint),customModelBaseId:S(Z==="plan"?J.planModeAwsBedrockCustomModelBaseId:J.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:S(J.vertexProjectId),region:S(J.vertexRegion)};if($===NJ&&(J.azureApiVersion||J.azureIdentity!==void 0))H.azure={apiVersion:S(J.azureApiVersion),useIdentity:J.azureIdentity};if($==="sapaicore")H.sap={clientId:S(Q.sapAiCoreClientId),clientSecret:S(Q.sapAiCoreClientSecret),tokenUrl:S(J.sapAiCoreTokenUrl),resourceGroup:S(J.sapAiResourceGroup),deploymentId:S(Z==="plan"?J.planModeSapAiCoreDeploymentId:J.actModeSapAiCoreDeploymentId),useOrchestrationMode:J.sapAiCoreUseOrchestrationMode};if($==="oca"){H.oca={mode:J.ocaMode};let U=S(Q.ocaRefreshToken);if(U)H.auth={...H.auth??{},refreshToken:U}}if($==="qwen")H.apiLine=J.qwenApiLine;if($==="moonshot")H.apiLine=J.moonshotApiLine;if($==="zai")H.apiLine=J.zaiApiLine;if($==="minimax")H.apiLine=J.minimaxApiLine;let B={anthropic:J.anthropicBaseUrl,openai:J.openAiBaseUrl,ollama:J.ollamaBaseUrl,lmstudio:J.lmStudioBaseUrl,litellm:J.liteLlmBaseUrl,gemini:J.geminiBaseUrl,requesty:J.requestyBaseUrl,asksage:J.asksageApiUrl,dify:J.difyBaseUrl,oca:J.ocaBaseUrl,aihubmix:J.aihubmixBaseUrl,sapaicore:J.sapAiCoreBaseUrl},A=S(V[$]),K=S(B[$]),G={provider:W,...A?{apiKey:A}:{},...f?{model:f}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...Y?{timeout:Y}:{},...H},R=e8.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function _P($,J){if($!==QH)return;if(!J.baseUrl||!J.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:J.baseUrl,defaultModelId:J.model},models:{[J.model]:{id:J.model,name:J.model,contextWindow:$H,maxInputTokens:$H,capabilities:["streaming","tools","images"]}}}}function OP($,J){let Q=new Set;for(let W of[$.actModeApiProvider,$.planModeApiProvider]){let j=S(W);if(j)Q.add(j)}if(S(J.apiKey))Q.add("anthropic");if(S(J.openRouterApiKey))Q.add("openrouter");if(S(J.openAiApiKey))Q.add(NJ);if(S(J.openAiNativeApiKey))Q.add("openai-native");if(S(J["openai-codex-oauth-credentials"]))Q.add("openai-codex");if(S(J.geminiApiKey))Q.add("gemini");if(S(J.ollamaApiKey))Q.add("ollama");if(S(J.awsAccessKey)||S(J.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||S($.awsProfile))Q.add("bedrock");if(S($.vertexProjectId)||S($.vertexRegion))Q.add("vertex");if(S(J.clineApiKey))Q.add("cline");let Z=ZH(S(J["cline:clineAccountId"]));if(Z?.accessToken||Z?.refreshToken||Z?.accountId)Q.add("cline");if(S(J.ocaApiKey))Q.add("oca");if(S(J.sapAiCoreClientId)||S(J.sapAiCoreClientSecret)||S($.sapAiCoreTokenUrl)||S($.sapAiCoreBaseUrl)||S($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Q.add("sapaicore");return Q}function Q7($){let J=$.providerSettingsManager.read(),Q=FP($);if(!Q)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let{globalState:Z,secrets:W}=Q,j=Z.mode==="plan"?"plan":"act",f=OP(Z,W),X=S2();X.providers={...J.providers},X.lastUsedProvider=J.lastUsedProvider;let Y=new Date().toISOString(),V=0,H=$7(KP($.providerSettingsManager.getFilePath()),"models.json"),B=eZ(H),A=0;for(let R of f){let D=J7(R);if(X.providers[D])continue;let U=LP(R,Z,W,j);if(!U)continue;X.providers[D]={settings:U,updatedAt:Y,tokenSource:"migration"},V+=1;let F=_P(D,U);if(F&&!B.providers[D])B.providers[D]=F,A+=1}if(V===0&&A===0)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let K=S(j==="plan"?Z.planModeApiProvider:Z.actModeApiProvider),G=K?J7(K):void 0;if(X.lastUsedProvider=J.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),A>0)pV(H,B);return{migrated:V>0||A>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}function NP(){return new Date().toISOString()}var wP="cline",SP="cline-pass";function CP($){if(jH($)!=="providers.json")return;let J=W7($);if(jH(J)!=="settings")return;return W7(J)}class Q${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??PP(),this.dataDir=$.dataDir??CP(this.filePath),this.dataDir||!$.filePath)Q7({providerSettingsManager:this,dataDir:this.dataDir});if(tV(this),PJ(this.read()),Z7(this.filePath))try{WH(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!Z7(this.filePath))return S2();try{let $=MP(this.filePath,"utf8"),J=JSON.parse($),Q=_J.safeParse(J);if(Q.success)return PJ(Q.data),Q.data}catch{}return S2()}write($){let J=_J.parse($),Q=W7(this.filePath);if(!Z7(Q))TP(Q,{recursive:!0,mode:448});qP(this.filePath,`${JSON.stringify(J,null,2)}
568
- `,"utf8");try{WH(this.filePath,384)}catch{}PJ(J)}saveProviderSettings($,J={}){let Q=e8.parse($),Z=this.read(),W=Q.provider,j=J.setLastUsed!==!1,f=Z.providers[W],X=J.tokenSource??f?.tokenSource??"manual",Y={...Z,providers:{...Z.providers,[W]:{settings:Q,updatedAt:NP(),tokenSource:X}},lastUsedProvider:j?W:Z.lastUsedProvider};return this.write(Y),Y}resolveProviderSettings($,J){let Q=$.providers[J]?.settings,W=f0(J)?.storageProviderId;if(!W||W===J)return Q;let j=$.providers[W]?.settings;if(!j)return Q;return e8.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Q??{},provider:J})}getProviderSettings($){let J=this.read();return this.resolveProviderSettings(J,$)}resolveLastUsedProviderId($,J){let Q=$.lastUsedProvider;if(Q===SP&&J.isClinePassEnabled===!1)return wP;return Q}getLastUsedProviderSettings($={}){let J=this.read(),Q=this.resolveLastUsedProviderId(J,$);if(!Q)return;return this.resolveProviderSettings(J,Q)}getProviderConfig($,J){let Q=this.getProviderSettings($);if(!Q)return;return V1(Q,J)}getLastUsedProviderConfig($={}){let J=this.getLastUsedProviderSettings($);if(!J)return;return V1(J,$)}async refreshCatalog(){try{await h4({})}catch{}}}F0();q2();import{execFile as yP}from"node:child_process";import{promisify as EP}from"node:util";var y2=EP(yP);function j7($){let J=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(J?.history)?J.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let W=String(Z.ref??"").trim(),j=Number(Z.createdAt??0),f=Number(Z.runCount??0);if(W.length===0||!Number.isFinite(j)||!Number.isInteger(f)||f<1)return[];let X=Z.kind==="stash"||Z.kind==="commit"?Z.kind:void 0;return[{ref:W,createdAt:j,runCount:f,...X?{kind:X}:{}}]})}function fH($,J){let Q=j7($).filter((W)=>W.runCount<=J),Z=Q.at(-1);return Z?{latest:Z,history:Q}:void 0}function bP($,J){return $.reduce((Q,Z)=>{if(Z.runCount>J)return Q;if(!Q||Z.runCount>Q.runCount)return Z;return Q},void 0)}function XH($,J){let Q=0;for(let Z=0;Z<$.length;Z+=1){let W=$[Z];if(W?.role!=="user")continue;if(("metadata"in W&&W.metadata&&typeof W.metadata==="object"?W.metadata:void 0)?.kind==="recovery_notice")continue;if(Q+=1,Q===J)return Z}throw Error(`Could not find user message for checkpoint run ${J}`)}function hP($,J){let Q=XH($,J);return $.slice(0,Q+1)}function YH($,J){let Q=XH($,J);return $.slice(0,Q)}function VH($){let J=$.checkpointRunCount;if(!Number.isInteger(J)||J<1)throw Error("checkpointRunCount must be a positive integer");let Q=bP(j7($.session),J);if(!Q)throw Error(`No checkpoint found at or before run ${J} in session ${$.session.sessionId}`);let Z=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Z)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Q,cwd:Z,...$.restoreMessages!==!1?{messages:hP($.messages??[],J)}:{}}}async function HH($,J){if((await y2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await y2("git",["-C",$,"cat-file","-e",`${J.ref}^{commit}`],{windowsHide:!0}),await y2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await y2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),J.kind==="commit"){await y2("git",["-C",$,"reset","--hard",J.ref],{windowsHide:!0});return}await y2("git",["-C",$,"stash","apply",J.ref],{windowsHide:!0})}class a0 extends Error{code;constructor($,J){super(J);this.code=$;this.name="SessionVersioningError"}}function kP($){let J=$.sessionId.trim();if(!J)throw new a0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new a0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new a0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new a0("invalid_restore","checkpointRunCount must be a positive integer");return J}class E2{async restoreCheckpoint($){let J=$.restore?.messages!==!1,Q=$.restore?.workspace!==!1,Z=kP({sessionId:$.sessionId,restoreMessages:J,restoreWorkspace:Q,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),W=await $.getSession(Z);if(!W)throw new a0("session_not_found",`Session ${Z} not found`);let j=J?await $.readMessages(Z):void 0;if(J&&j?.length===0)throw new a0("session_messages_not_found",`No messages found for session ${Z}`);let f=VH({session:W,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:J});if(Q)await($.applyWorkspaceCheckpoint??HH)(f.cwd,f.checkpoint);let X=i1({session:W,messages:j});if(!J)return{checkpoint:f.checkpoint,sourceSnapshot:X};let Y=fH(W,$.checkpointRunCount),V=$.restore?.omitCheckpointMessageFromSession?YH(j??[],$.checkpointRunCount):f.messages??[],H={sourceSession:W,sourceMessages:j,sourceSnapshot:X,plan:f,restoredCheckpointMetadata:Y,initialMessages:V,restoreMessages:J,restoreWorkspace:Q,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new a0("invalid_restore","start is required when restore.messages is true");let B=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,A=await $.startSession(B),K=$.getStartedSessionId?.(A);if(K)await($.retainCheckpointRefs??yY)(f.cwd,K,Y?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:A,messages:f.messages,checkpoint:f.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:i1({session:G,messages:V})}:{}}}}import{hasRuntimeConfigExtension as aP}from"@cline/shared";import{nanoid as sP}from"nanoid";p0();import{appendFileSync as IP,existsSync as b2,mkdirSync as BH,readdirSync as xP,readFileSync as AH,renameSync as gP,writeFileSync as mP}from"node:fs";import{join as f7}from"node:path";import{resolveTeamDataDir as vP}from"@cline/shared/storage";function KH(){return new Date().toISOString()}function X7($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function GH($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class SJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??vP()}init(){this.ensureTeamDir()}listTeamNames(){if(!b2(this.teamDirPath))return[];return xP(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>b2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let J=this.readEnvelope($);return J?.teamState?GH(J.teamState):void 0}readHistory($,J=200){let Q=this.historyPath($);if(!b2(Q))return[];return AH(Q,"utf8").split(`
569
- `).map((Z)=>Z.trim()).filter(Boolean).map((Z)=>{try{return JSON.parse(Z)}catch{return}}).filter((Z)=>Z!==void 0).reverse().slice(0,J)}loadRuntime($){let J=this.readEnvelope($);return{state:J?.teamState?GH(J.teamState):void 0,teammates:J?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,J){this.ensureTeamSubdir($),IP(this.historyPath($),`${JSON.stringify({ts:KH(),eventType:J.type,payload:J})}
570
- `,"utf8")}persistRuntime($,J,Q){this.ensureTeamSubdir($);let Z={version:1,updatedAt:KH(),teamState:J,teammates:Q},W=this.statePath($),j=`${W}.tmp`;mP(j,`${JSON.stringify(Z,null,2)}
571
- `,"utf8"),gP(j,W)}markInProgressRunsInterrupted($,J){let Q=this.readEnvelope($);if(!Q?.teamState?.runs?.length)return[];let Z=Q.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Z.length===0)return[];let W=new Date;return Q.teamState={...Q.teamState,runs:Q.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:J,endedAt:W}:j)},this.persistRuntime($,Q.teamState,Q.teammates),Z}ensureTeamDir(){if(!b2(this.teamDirPath))BH(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let J=f7(this.ensureTeamDir(),X7($));if(!b2(J))BH(J,{recursive:!0});return J}statePath($){return f7(this.ensureTeamDir(),X7($),"state.json")}historyPath($){return f7(this.ensureTeamDir(),X7($),"task-history.jsonl")}readEnvelope($){let J=this.statePath($);if(!b2(J))return;try{let Q=JSON.parse(AH(J,"utf8"));if(Q?.version===1&&Q.teamState)return Q}catch{}return}}import{existsSync as cP,mkdirSync as uP}from"node:fs";import{join as dP}from"node:path";import{safeJsonParse as FH}from"@cline/shared";import{loadSqliteDb as lP,nowIso as Y7}from"@cline/shared/db";import{resolveDbDataDir as pP}from"@cline/shared/storage";function rP(){return pP()}function h2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function iP($){let J=FH($);if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,j=W.agentId,f=W.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof f!=="string"||!f.trim())continue;let X={agentId:j.trim(),rolePrompt:f};if(typeof W.modelId==="string"&&W.modelId.trim())X.modelId=W.modelId.trim();if(typeof W.maxIterations==="number"&&Number.isFinite(W.maxIterations))X.maxIterations=Math.max(1,Math.floor(W.maxIterations));Q.push(X)}return Q}function nP($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class J4{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??rP()}init(){this.getRawDb()}ensureTeamDir(){if(!cP(this.teamDirPath))uP(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return dP(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=lP(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
560
+ `)}function UV($){let J=$.summarizer,Q=(W)=>{if(W.providerId==="openai-codex"){let{maxOutputTokens:j,...f}=W;return{...f,thinking:!1}}return{...W,maxOutputTokens:W.maxOutputTokens??JV,thinking:!1}};if(!J)return Q($.activeProviderConfig);let Z=J.providerConfig?.providerId===J.providerId?J.providerConfig:void 0;return Q({...Z??{},providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey??Z?.apiKey,baseUrl:J.baseUrl??Z?.baseUrl,headers:J.headers??Z?.headers,knownModels:J.knownModels??Z?.knownModels,maxOutputTokens:J.maxOutputTokens??JV})}function RV($){return{role:"user",content:`Context summary:
561
+
562
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function pM($){let J=await lM($.providerConfig),Q="";for await(let Z of J.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Z.type==="text"){Q+=Z.text;continue}if(Z.type==="done"&&!Z.success&&Z.error)throw Error(Z.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Q.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Q.trim()}function rM($){try{return JSON.stringify($).length}catch{return String($).length}}async function zV($){let J=$.context.messages;if(J.length<2)return;let Q=KV(J,$.preserveRecentTokens,$.estimateMessageTokens);if(Q<=0||Q>=J.length)return;let Z=J.slice(0,Q),W=AV(Z),j=W>=0?vZ(Z[W])?.summary:void 0,f=W>=0?Z.slice(W+1):Z;if(f.length===0)return;let X=GV(Z),Y=YV(f),V=DV({previousSummary:j,conversationText:Y,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Z.length,newMessagesToFold:f.length,preservedMessages:J.length-Q,previousSummaryChars:j?.length??0,conversationTextChars:Y.length,summaryRequestChars:V.length,summaryRequestEstimatedTokens:IZ(V.length),newMessagesJsonChars:rM(f),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let H=await pM({providerConfig:UV({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:V,logger:$.logger});if(!H.trim())return;let B=FV(H,X),A=J.reduce((R,D)=>R+$.estimateMessageTokens(D),0),K=[RV({summary:B,fileOps:X,tokensBefore:A}),...J.slice(Q)],G=K.reduce((R,D)=>R+$.estimateMessageTokens(D),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:J.length,messagesAfter:K.length,messagesSummarized:Q,messagesPreserved:J.length-Q,tokensBefore:A,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function OV($){if(a8($))return;if(typeof $.content==="string"){let Q=$.content.trim();return Q?{...$,content:Q}:void 0}let J=$.content.filter((Q)=>Q.type!=="text"||Q.text.trim());if(J.length===0)return;return{...$,content:J.map((Q)=>Q.type==="text"?{...Q,text:Q.text.trim()}:Q.type==="tool_result"?{...Q,content:mZ(Q.content)}:Q)}}function o8($,J){return $.reduce((Q,Z)=>Q+J(Z),0)}function LV($,J){let Q=Math.max(1,J),Z=Math.max(16,Q*4);if(typeof $.content==="string"){let f=t1($.content,Z).trim();return{...$,content:f||"..."}}let W=Z,j=$.content.map((f)=>{if(f.type!=="text"||W<=0)return f;let X=t1(f.text,W).trim();return W-=X.length,{...f,text:X||"..."}});return{...$,content:j}}function iM($,J){let Q=HV($),Z=BJ($),W=BV($),j=[];for(let f=0;f<$.length;f+=1){let X=OV($[f]);if(!X)continue;j.push({index:f,message:X,estimatedTokens:J(X),isFirstUser:f===Q,isLastUser:f===Z,isLastAssistant:f===W})}return j}function _V($,J,Q,Z){let W=$[J];W.message=Q,W.estimatedTokens=Z(Q)}function nM($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_use")J.add(Q.id);return J}function aM($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_result")J.add(Q.tool_use_id);return J}function TV($){return new Set([...nM($.message),...aM($.message)])}function sM($){let J=new Map;for(let Q=0;Q<$.length;Q+=1)for(let Z of TV($[Q])){let W=J.get(Z);if(W)W.add(Q);else J.set(Z,new Set([Q]))}return J}function oM($,J){let Q=sM($),Z=new Set,W=[J];while(W.length>0){let j=W.shift();if(j===void 0||Z.has(j))continue;Z.add(j);for(let f of TV($[j]))for(let X of Q.get(f)??[])if(!Z.has(X))W.push(X)}return Z}function AJ($,J,Q,Z){let W=o8($.map((j)=>j.message),Z);for(let j=0;j<$.length&&W>Q;){if(!J($[j])){j+=1;continue}let f=oM($,j);W-=Array.from(f).reduce((X,Y)=>X+$[Y].estimatedTokens,0);for(let X of Array.from(f).sort((Y,V)=>V-Y))$.splice(X,1)}}function tM($,J,Q){let Z=o8($.map((j)=>j.message),Q);if(Z<=J)return;for(let j=$.length-1;j>=0&&Z>J;j-=1){let f=$[j];if(f.isFirstUser)continue;let X=Math.max(fV,f.estimatedTokens-(Z-J));if(X>=f.estimatedTokens)continue;_V($,j,LV(f.message,X),Q),Z=o8($.map((Y)=>Y.message),Q)}if(Z<=J)return;let W=$.findIndex((j)=>j.isFirstUser);if(W>=0){let j=Math.max(1,$[W].estimatedTokens-(Z-J));_V($,W,LV($[W].message,j),Q)}}function eM($,J){return JSON.stringify($)!==JSON.stringify(J)}function $q($){let J=BJ($);if(J<0||J===0&&!s8($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,J),protectedTail:$.slice(J)}}function MV($){let J=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:Q,protectedTail:Z}=$q($.context.messages);if(Q.length===0)return;let W=iM(Q,$.estimateMessageTokens);if(W.length===0)return;AJ(W,(Y)=>Y.message.role==="assistant"&&!Y.isLastAssistant,J,$.estimateMessageTokens),AJ(W,(Y)=>Y.message.role==="user"&&!Y.isFirstUser&&!Y.isLastUser,J,$.estimateMessageTokens),AJ(W,(Y)=>Y.message.role==="assistant"&&Y.isLastAssistant,J,$.estimateMessageTokens),AJ(W,(Y)=>Y.message.role==="user"&&Y.isLastUser&&!Y.isFirstUser,J,$.estimateMessageTokens),tM(W,J,$.estimateMessageTokens);let j=[...W.map((Y)=>Y.message),...Z];if(!eM($.context.messages,j))return;let f=o8([...Q.map((Y)=>OV(Y)??Y),...Z],$.estimateMessageTokens),X=o8(j,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:j.length,messagesRemoved:$.context.messages.length-j.length,tokensBefore:f,tokensAfter:X,targetTokens:J,maxInputTokens:$.context.maxInputTokens}),{messages:j}}function qV($){try{return JSON.stringify($).length}catch{return String($).length}}function Jq($){let J=0,Q=0,Z=0;for(let W of $){if(!Array.isArray(W.content))continue;for(let j of W.content){if(j.type!=="tool_result")continue;let f=qV(j.content);J+=1,Q+=f,Z=Math.max(Z,f)}}return{toolResultCount:J,toolResultSerializedChars:Q,maxToolResultSerializedChars:Z}}var Qq={basic:({context:$,estimateMessageTokens:J,logger:Q})=>MV({context:$,estimateMessageTokens:J,logger:Q}),agentic:({context:$,providerConfig:J,compaction:Q,mode:Z,estimateMessageTokens:W,logger:j})=>zV({context:$,providerConfig:J,summarizer:Q?.summarizer,preserveRecentTokens:Z==="manual"?Math.min(Q?.preserveRecentTokens??gZ,$.triggerTokens):Q?.preserveRecentTokens??gZ,estimateMessageTokens:W,logger:j})};function Zq($){if(typeof $.config.reserveTokens==="number"){let Z=Math.max(0,$.config.reserveTokens),W=Math.max(0,$.maxInputTokens-Z);return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Z=Math.max(0,Math.min($.maxInputTokens-WV,$.maxInputTokens*xZ));return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}let J=$.config.thresholdRatio??xZ,Q=$.maxInputTokens*J;return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:J}}function Wq($){let J=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Q=Math.min(0.95,Math.max(0.05,J)),Z=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*Q)));return{triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}function cZ($,J={}){let Q=$.compaction;if(Q?.enabled!==!0)return;let Z=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},W=VV(),j=Q?.strategy??"basic",f=Qq[j],X=J.mode??"auto",Y=Q?.compact?"custom":j;return async(V)=>{let H=V.apiMessages.reduce((z,M)=>z+W(M),0),B=Q?.maxInputTokens??V.model.info?.maxInputTokens??V.model.info?.contextWindow??ZV;if(typeof B!=="number"||!Number.isFinite(B)||B<=0)return;let A=Zq({inputTokens:H,maxInputTokens:B,config:{reserveTokens:Q?.reserveTokens,thresholdRatio:Q?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:j,iteration:V.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:H,maxInputTokens:B,triggerTokens:A.triggerTokens,thresholdRatio:A.thresholdRatio,shouldCompact:A.shouldCompact,messageCount:V.messages.length,apiMessageCount:V.apiMessages.length,apiMessagesJsonChars:qV(V.apiMessages),...Jq(V.apiMessages)}),X==="auto"&&!A.shouldCompact)return;let K=X==="manual"?Wq({inputTokens:H,maxInputTokens:B,autoTriggerTokens:A.triggerTokens,manualTargetRatio:J.manualTargetRatio}):A,G={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId,iteration:V.iteration,messages:V.messages,model:V.model,maxInputTokens:B,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:B>0?H/B:0},R=X==="manual"?"manual_compaction":"auto_compaction";V.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:V.iteration,triggerTokens:K.triggerTokens,maxInputTokens:B});let D=V.messages.length,U=Date.now(),F=Q?.compact?await Q.compact(G):await f({context:G,providerConfig:{...Z,abortSignal:V.abortSignal},compaction:Q,mode:X,estimateMessageTokens:W,logger:$.logger}),O=Date.now()-U,T=$.sessionId??V.conversationId,L={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId??void 0};if(F?.messages){let z=F.messages.reduce((M,P)=>M+W(P),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:B,inputTokens:H,afterTokens:z,tokensSaved:H-z,utilizationBefore:`${(H/B*100).toFixed(1)}%`,utilizationAfter:`${(z/B*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length}),P5($.telemetry,{ulid:T,strategy:Y,mode:X,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length,tokensBefore:H,tokensAfter:z,tokensSaved:H-z,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L})}else N5($.telemetry,{ulid:T,strategy:Y,mode:X,reason:"no_result",tokensBefore:H,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L});return F}}F0();function U0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function K0($,J){return{inputTokens:$.inputTokens+Math.max(0,J.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,J.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,J.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,J.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,J.totalCost??0)}}function KJ($){let J=U0();for(let Q of $)J=K0(J,Q);return J}function N2($){return typeof $==="number"&&Number.isFinite($)?$:0}function GJ($){let J=U0();for(let Q of $){let Z=Q.metrics;if(!Z)continue;J=K0(J,{inputTokens:N2(Z.inputTokens),outputTokens:N2(Z.outputTokens),cacheReadTokens:N2(Z.cacheReadTokens),cacheWriteTokens:N2(Z.cacheWriteTokens),totalCost:N2(Z.cost)})}return J}function jq($){for(let J=$.length-1;J>=0;J-=1){let Q=$[J];if(Q?.role!=="assistant")continue;let Z=N2(Q.metrics?.inputTokens);return Z>0?Z:void 0}return}function fq($){if(!$||typeof $!=="object")return;let J=$,Q=J.skill??J.skill_name??J.skillName;if(typeof Q!=="string")return;let Z=Q.trim();return Z.length>0?Z:void 0}function uZ($){if(!$||typeof $!=="object")return{};let J=$;return{agentId:typeof J.agentId==="string"?J.agentId:void 0,conversationId:typeof J.conversationId==="string"?J.conversationId:void 0,parentAgentId:typeof J.parentAgentId==="string"?J.parentAgentId:void 0}}function L1($){let J=$.agentId?.trim();if(!J)return;let Q=$.parentAgentId?.trim()||void 0,Z=$.teamRole,W="root";if(Z==="teammate")W="team_teammate";else if(Z==="lead")W="team_lead";else if(Q)W="subagent";return{agentId:J,agentKind:W,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Q,createdByAgentId:$.createdByAgentId?.trim()||Q||void 0,isSubagent:Boolean(Q),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Z,teamAgentId:$.teamAgentId?.trim()||void 0}}function Xq($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function Yq($){let J=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Q of J){let Z=Q?.trim();if(Z)return Z}return $.isPrimaryAgentEvent?"root":"unknown"}function dZ($,J,Q){let{sessionId:Z,config:W,liveSession:j,emit:f}=$,X=W.telemetry,Y=j?.runtime.teamRuntime,V=Q?.isPrimaryAgentEvent??!0,H=uZ(J),B=L1({agentId:Q?.agentId??H.agentId,conversationId:Q?.conversationId??H.conversationId,parentAgentId:Q?.parentAgentId??H.parentAgentId,createdByAgentId:Q?.createdByAgentId,teamId:Q?.teamId??Y?.getTeamId(),teamName:Q?.teamName??Y?.getTeamName(),teamRole:Q?.teamRole,teamAgentId:Q?.teamAgentId});if(J.type==="content_start"&&J.contentType==="tool"&&J.toolName==="skills"){let A=fq(J.input);if(A)z5(X,{ulid:Z,skillName:A,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:W.providerId,modelId:W.modelId,...B})}if(J.type==="content_end"&&J.contentType==="tool"){let A=J.toolName??"unknown",K=!J.error;if(R5(X,{ulid:Z,tool:A,autoApproved:void 0,success:K,modelId:W.modelId,provider:W.providerId,...B}),!K&&(A==="editor"||A==="apply_patch"))L5(X,{ulid:Z,modelId:W.modelId,provider:W.providerId,errorType:J.error,...B})}if(J.type==="notice"&&J.reason==="api_error")R4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.message,...B});if(J.type==="error")R4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.error?.message??"unknown error",...B});if(J.type==="usage"&&j?.turnUsageBaseline){let A=Xq(J);if(V){j.turnPrimaryUsage=K0(j.turnPrimaryUsage??U0(),A);let G=K0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Z,G),g2(X,{ulid:Z,provider:W.providerId,model:W.modelId,source:"assistant",mode:W.mode,...B}),D5(X,{ulid:Z,tokensIn:J.inputTokens,tokensOut:J.outputTokens,cacheWriteTokens:J.cacheWriteTokens,cacheReadTokens:J.cacheReadTokens,totalCost:J.cost,model:W.modelId,...B})}else{let G=Yq({isPrimaryAgentEvent:V,overrides:Q,eventMetadata:H}),R=j.turnUsageByAgent??new Map;j.turnUsageByAgent=R,R.set(G,K0(R.get(G)??U0(),A))}let K=K0(j.turnPrimaryUsage??U0(),KJ(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Z,K0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,K))}if(J.type==="iteration_end"&&V)$.persistMessages(Z,j?.agent.getMessages()??[],j?.config.systemPrompt);f({type:"agent_event",payload:{sessionId:Z,event:J,teamAgentId:Q?.teamAgentId,teamRole:Q!==void 0?Q.teamRole??(V?"lead":void 0):void 0}}),f({type:"chunk",payload:{sessionId:Z,stream:"agent",chunk:IX(J),ts:Date.now()}})}function e1($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as Iq}from"@cline/shared";import{spawn as Uq}from"node:child_process";import{appendFileSync as Rq,readFileSync as zq}from"node:fs";import{join as Lq}from"node:path";import{augmentNodeCommandForDebug as SV,withResolvedClineBuildEnv as aZ}from"@cline/shared";import{ensureHookLogDir as NV}from"@cline/shared/storage";function FJ($,J){if(!J)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:J}}import{existsSync as Vq,readdirSync as Hq}from"node:fs";import{basename as Bq,extname as Aq,join as Kq}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as PV,resolveHooksConfigSearchPaths as Gq}from"@cline/shared/storage";function lZ($){return Gq($)}var DJ;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(DJ||={});var pZ={["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"},Fq=new Map(Object.values(DJ).map(($)=>[$.toLowerCase(),$])),Dq=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function rZ($){let J=Aq($).toLowerCase();if(!Dq.has(J))return;let Q=Bq($,J).trim().toLowerCase();return Fq.get(Q)}function w2($){let J=[],Q=new Set,Z=lZ($).filter((W)=>Vq(W));for(let W of Z)try{for(let j of Hq(W,{withFileTypes:!0})){if(!j.isFile())continue;let f=rZ(j.name);if(!f)continue;let X=Kq(W,j.name);if(Q.has(X))continue;Q.add(X),J.push({fileName:f,hookEventName:pZ[f],path:X})}}catch{}return J.sort((W,j)=>W.path.localeCompare(j.path))}function RJ($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))J[Q]=typeof Z==="string"?Z:JSON.stringify(Z);return J}function UJ($,J,Q){let Z=Q instanceof Error?`: ${Q.message}`:"",W=`${J}${Z}`;if($){try{$.log(W,{severity:"warn",...Q!==void 0?{error:Q}:{}})}catch{}return}console.warn(W)}function _q($,J){if(!J)return $;if(!$)return{...J};let Q=[$.context,J.context].filter((W)=>typeof W==="string"&&W.length>0).join(`
563
+ `),Z=[...$.appendMessages??[],...J.appendMessages??[]];return{cancel:$.cancel===!0||J.cancel===!0?!0:void 0,review:$.review===!0||J.review===!0?!0:void 0,context:Q||void 0,overrideInput:J.overrideInput!==void 0?J.overrideInput:$.overrideInput,systemPrompt:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,appendMessages:Z.length>0?Z:void 0}}function Oq($){if(!$||typeof $!=="object")return;let J=$,Q=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Q,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function iZ($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function G0($,J){let Q=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Z={rootSessionId:J.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Z,workspaceRoots:J.workspacePath?[J.workspacePath]:[],workspaceInfo:J.workspaceInfo,userId:Q,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function Tq($){let J=$.trim();if(!J)return{};let Z=J.split(`
564
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function Mq($,J){let Q=$.stdin;if(!Q)throw Error("hook command failed to create stdin");await new Promise((Z,W)=>{let j=!1,f=()=>{Q.off("error",Y),Q.off("finish",V),$.off("close",H)},X=(B)=>{if(j)return;if(j=!0,f(),B){let A=B.code;if(A==="EPIPE"||A==="ERR_STREAM_DESTROYED"){Z();return}W(B);return}Z()},Y=(B)=>X(B),V=()=>X(),H=()=>X();Q.on("error",Y),Q.once("finish",V),$.once("close",H);try{Q.end(J)}catch(B){X(B)}})}async function CV($,J){if(J.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await wV($,J)}catch(Q){let Z=Nq(J.command,process.platform,Q);if(!Z)throw Q;return await wV($,{...J,command:Z})}}async function wV($,J){let Q=SV(J.command,{env:J.env,debugRole:"hook"}),Z=Uq(Q[0],Q.slice(1),{cwd:J.cwd,env:aZ(J.env),stdio:J.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:J.detached,windowsHide:!0}),W=new Promise((A)=>{Z.once("spawn",()=>A())}),j=new Promise((A,K)=>{Z.once("error",(G)=>K(G))}),f=JSON.stringify($);if(await Promise.race([W,j]),await Mq(Z,f),J.detached){Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("hook command failed to create stdout/stderr");let X="",Y="",V=!1,H;Z.stdout.on("data",(A)=>{X+=A.toString()}),Z.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,Z.kill("SIGKILL")},J.timeoutMs);Z.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=Tq(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,j])}function qq($){try{let Q=zq($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Q?.startsWith("#!"))return;let Z=Q.slice(2).trim();if(!Z)return;let W=Z.split(/\s+/).filter(Boolean);return W.length>0?W:void 0}catch{return}}function Pq($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function Nq($,J=process.platform,Q){if(J!=="win32"||!Pq(Q))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function yV($){if($.length===0)return;let[J,...Q]=$,Z=J.replace(/\\/g,"/").toLowerCase(),W=Z.split("/").at(-1)??Z;if(W==="env")return yV(Q);if(W==="bash"||W==="sh"||W==="zsh")return[W,...Q];if(W==="python3"||W==="python")return process.platform==="win32"?["py","-3",...Q]:[W,...Q];return $}function wq($){let J=qq($);if(J&&J.length>0)return[...yV(J)??J,$];let Q=$.toLowerCase();if(Q.endsWith(".sh")||Q.endsWith(".bash")||Q.endsWith(".zsh"))return["bash",$];if(Q.endsWith(".js")||Q.endsWith(".mjs")||Q.endsWith(".cjs"))return SV(["node",$],{debugRole:"hook"});if(Q.endsWith(".ts")||Q.endsWith(".mts")||Q.endsWith(".cts"))return["bun","run",$];if(Q.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Q.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function Sq($){let J={};for(let Q of w2($)){if(!Q.hookEventName)continue;let Z=Q.hookEventName,W=J[Z]??[];W.push(wq(Q.path)),J[Z]=W}return J}async function Cq($){let J;for(let Q of $.commands){let Z=Q.join(" ");try{let W=await CV($.payload,{command:Q,cwd:$.cwd,env:aZ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(W?.timedOut){UJ($.logger,`hook command timed out: ${Z}`);continue}if(W?.parseError){UJ($.logger,`hook command returned invalid JSON control output: ${Z} (${W.parseError})`);continue}J=_q(J,Oq(W?.parsedJson))}catch(W){UJ($.logger,`hook command failed: ${Z}`,W)}}return J}function k$($){for(let J of $.commands){let Q=J.join(" ");CV($.payload,{command:J,cwd:$.cwd,env:aZ(process.env),detached:!0}).catch((Z)=>{UJ($.logger,`hook command failed: ${Q}`,Z)})}}function $$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function nZ($,J){return{...$$($.snapshot),userMessage:J}}function EV($){return{...$$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function bV($){return{...$$($.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 hV($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function yq($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}function zJ($){let J={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Q=(Z)=>{let W=`${JSON.stringify({ts:new Date().toISOString(),...Z})}
565
+ `,f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Lq(NV(),"hooks.jsonl");NV(f),Rq(f,W,"utf8")};return{beforeRun:async(Z)=>{let W=nZ(Z,"");Q({...G0(W,J),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Z)=>{let W=EV(Z);Q({...G0(W,J),hookName:"tool_call",iteration:W.iteration,tool_call:{id:W.call.id,name:W.call.name,input:W.call.input},preToolUse:{toolName:W.call.name,parameters:RJ(W.call.input)}});return},afterTool:async(Z)=>{let W=bV(Z);Q({...G0(W,J),hookName:"tool_result",iteration:W.iteration,tool_result:W.record,postToolUse:{toolName:W.record.name,parameters:RJ(W.record.input),result:typeof W.record.output==="string"?W.record.output:JSON.stringify(W.record.output),success:!W.record.error,executionTimeMs:W.record.durationMs}});return},afterRun:async({snapshot:Z,result:W})=>{let j=$$(Z);if(W.status==="completed"){Q({...G0(j,J),hookName:"agent_end",iteration:W.iterations,turn:{outputText:W.outputText,status:W.status},taskComplete:{taskMetadata:{}}});return}if(W.status==="aborted"||iZ(W.error?.message)){Q({...G0(j,J),hookName:"agent_abort",reason:W.error?.message,taskCancel:{taskMetadata:{}}});return}if(W.error)Q({...G0(j,J),hookName:"agent_error",iteration:W.iterations,error:{name:W.error.name,message:W.error.message,stack:W.error.stack}})},onEvent:async(Z)=>{if(Z.type!=="message-added"||Z.message.role!=="user")return;let W=nZ({snapshot:Z.snapshot},hV(Z.message.content));Q({...G0(W,J),hookName:"prompt_submit",userPromptSubmit:{prompt:W.userMessage,attachments:[]}})}}}function sZ($){let J=Sq($.workspacePath);if(!Object.values(J).some((B)=>B.length>0))return;let Z=async(B,A)=>{let K=J[A]??[];if(K.length===0)return;k$({commands:K,cwd:$.cwd,logger:$.logger,payload:A==="agent_resume"?{...G0(B,$),hookName:A,taskResume:{taskMetadata:{},previousState:{}}}:{...G0(B,$),hookName:A,taskStart:{taskMetadata:{}}}})},W=async(B)=>{let A=J.prompt_submit??[];if(A.length>0)k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},j=async(B)=>{let A=J.tool_call??[];if(A.length===0)return;return Cq({commands:A,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...G0(B,$),hookName:"tool_call",iteration:B.iteration,tool_call:{id:B.call.id,name:B.call.name,input:B.call.input},preToolUse:{toolName:B.call.name,parameters:RJ(B.call.input)}}})},f=async(B)=>{let A=J.tool_result??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:RJ(B.record.input),result:typeof B.record.output==="string"?B.record.output:JSON.stringify(B.record.output),success:!B.record.error,executionTimeMs:B.record.durationMs}}})},X=async(B)=>{let A=J.agent_end??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"agent_end",iteration:B.iteration,turn:B.turn,taskComplete:{taskMetadata:{}}}})},Y=async(B)=>{let A=J.agent_error??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"agent_error",iteration:B.iteration,error:{name:B.error.name,message:B.error.message,stack:B.error.stack}}})},V=async(B)=>{if(iZ(B.reason)){let K=J.agent_abort??[];if(K.length>0)k$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let A=J.session_shutdown??[];if(A.length===0)return;k$({commands:A,cwd:$.cwd,logger:$.logger,payload:{...G0(B,$),hookName:"session_shutdown",reason:B.reason}})},H={};if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0||(J.prompt_submit?.length??0)>0){if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0)H.beforeRun=async(B)=>{let A=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Z($$(B.snapshot),A);return};if((J.prompt_submit?.length??0)>0)H.onEvent=async(B)=>{if(B.type!=="message-added"||B.message.role!=="user")return;await W(nZ({snapshot:B.snapshot},hV(B.message.content)))}}if((J.tool_call?.length??0)>0)H.beforeTool=async(B)=>{let A=await j(EV(B));return yq(A)};if((J.tool_result?.length??0)>0)H.afterTool=async(B)=>{await f(bV(B));return};if((J.agent_end?.length??0)>0)H.afterRun=async({snapshot:B,result:A})=>{if(A.status!=="completed")return;await X({...$$(B),iteration:A.iterations,turn:{outputText:A.outputText,status:A.status}})};if((J.agent_error?.length??0)>0||(J.agent_abort?.length??0)>0||(J.session_shutdown?.length??0)>0){let B=H.afterRun;H.afterRun=async(A)=>{await B?.(A);let{snapshot:K,result:G}=A;if(G.status==="aborted"||iZ(G.error?.message)){await V({...$$(K),reason:G.error?.message});return}if(G.error)await Y({...$$(K),iteration:G.iterations,error:G.error})}}return H}function LJ($){return FJ("core.hook_config_files",sZ($))}function I$($,J){let Q=$.map((Z)=>Z[J]).filter((Z)=>typeof Z==="function");if(Q.length===0)return;return async(Z)=>{let W;for(let j of Q){let f=await j(Z);if(!f||typeof f!=="object")continue;let X=f;W={...W??{},...X,stop:W?.stop===!0||X.stop===!0?!0:X.stop,options:W?.options||X.options?{...W?.options??{},...X.options??{}}:void 0}}return W}}function t8($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return;return{beforeRun:I$(J,"beforeRun"),afterRun:I$(J,"afterRun"),beforeModel:I$(J,"beforeModel"),afterModel:I$(J,"afterModel"),beforeTool:I$(J,"beforeTool"),afterTool:I$(J,"afterTool"),onEvent:I$(J,"onEvent")}}import{z as J$}from"zod";var e8=e$;var kV=J$.object({settings:e$,updatedAt:J$.string().datetime(),tokenSource:J$.enum(["manual","oauth","migration"]).default("manual")}),_J=J$.object({version:J$.literal(1),lastUsedProvider:J$.string().min(1).optional(),providers:J$.record(J$.string(),kV)});function S2(){return{version:1,providers:{}}}p0();import{upsertWorkspaceInfo as Eq,WorkspaceManifestSchema as oZ}from"@cline/shared";class OJ{manifest;listeners=new Set;constructor($){this.manifest=oZ.parse($??{workspaces:{}})}async addWorkspacePath($){let J=await c6($);return this.manifest=Eq(this.manifest,J),this.emit({type:"workspace_added",workspace:J}),J}async switchWorkspace($){let J=T$($),Q=this.manifest.workspaces[J];if(Q)return this.manifest=oZ.parse({...this.manifest,currentWorkspacePath:J}),this.emit({type:"workspace_switched",workspace:Q}),Q;let Z=await this.addWorkspacePath(J);return this.manifest=oZ.parse({...this.manifest,currentWorkspacePath:Z.rootPath}),this.emit({type:"workspace_switched",workspace:Z}),Z}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let J=T$($);return this.manifest.workspaces[J]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let J of this.listeners)J($)}}F0();import{createHash as bq}from"node:crypto";var IV=new Set,xV=new Set;function hq($){return bq("sha256").update($).digest("hex")}function kq($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function gV($){if(!$.telemetry)return;let J=hq($.rootPath),Q=$.rootCount??1;if(!IV.has(J))IV.add(J),A5($.telemetry,{root_count:Q,vcs_types:kq($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!xV.has(J)){xV.add(J);let Z=Error($.initError.message);Z.name=$.initError.errorType||"Error",K5($.telemetry,Z,{fallback_to_single_root:!0,workspace_count:Q})}}function xq($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function gq($,J,Q){if(J.length>0)for(let j of J)Q?.log(j.message,{severity:"warn"});if($.length===0)return;let Z=$.slice(0,3).map(xq).join("; "),W=$.length>3?`; and ${$.length-3} more`:"";Q?.log(`Some plugins failed to initialize. ${Z}${W}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Q?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function mq($,J){let Q=typeof $.thinking==="boolean",Z=typeof $.reasoningEffort==="string";if(!Q&&!Z)return J;return{...J??{},...Q?{enabled:$.thinking}:{},...Z?{effort:$.reasoningEffort}:{}}}function mV($,J){return Iq($,J)}function vq($){let J=0;for(let Q of $??[]){if(Q.role!=="user")continue;if(("metadata"in Q&&Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0)?.kind==="recovery_notice")continue;J+=1}return J}function cq($){let J={...$.storedHeaders??{},...$.configHeaders??{}},Q=$.accountId?.trim()||uq($.accessToken);if(J.originator="cline",J.session_id=$.sessionId,J["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,Q)J["ChatGPT-Account-Id"]=Q;return J}function uq($){let J=$?.trim();if(!J)return;let Q=R0(J),Z=Q?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let W=Q?.organizations?.[0]?.id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return}function dq($,J,Q,Z,W){let j=Q.getProviderSettings($.providerId),f=Z||j?.modelCatalog?{...Z??{},...j?.modelCatalog??{}}:void 0,X=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,Y={...j??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??j?.apiKey,baseUrl:$.baseUrl??j?.baseUrl,headers:$.providerId==="openai-codex"?cq({sessionId:J,configHeaders:$.headers,storedHeaders:j?.headers,accountId:j?.auth?.accountId,accessToken:$.apiKey??j?.auth?.accessToken??j?.apiKey}):$.headers??j?.headers,reasoning:mq($,j?.reasoning),modelCatalog:f},V={...V1(Y),...X??{}};if($.knownModels)V.knownModels=$.knownModels;if($.extensionContext)V.extensionContext=$.extensionContext;let B=$.fetch??V.fetch??W;if(B)V.fetch=B;return V}async function vV($){let{input:J,sessionId:Q,providerSettingsManager:Z,defaultTelemetry:W,defaultCapabilities:j,defaultToolPolicies:f,defaultFetch:X,onPluginEvent:Y,onTeamEvent:V,createSubAgentLifecycleCallbacks:H,createSpawnTool:B,localRuntime:A,readSessionMetadata:K,writeSessionMetadata:G}=$,R=e1(J.config),{modelCatalogDefaults:D,userInstructionService:U,configExtensions:F,onTeamRestored:O,...T}=A??{},L=Object.keys(T).length>0?T:void 0,{workspaceInfo:z,workspaceMetadata:M,durationMs:P,vcsType:C,initError:m}=await RX(R),n=L?.extensionContext,o={...n??{},workspace:{...z,...n?.workspace??{}},session:{...n?.session??{},sessionId:Q},logger:n?.logger??L?.logger,telemetry:n?.telemetry??L?.telemetry??W};gV({telemetry:o.telemetry,rootPath:z.rootPath,workspaceInfo:z,rootCount:1,vcsType:C,durationMs:P,initError:m,featureFlagEnabled:!0});let a=LJ({cwd:J.config.cwd,workspacePath:R,rootSessionId:Q,logger:L?.logger,workspaceInfo:z}),l0=kX(L?.hooks)?void 0:zJ({rootSessionId:Q,workspacePath:R,workspaceInfo:z}),f$=t8([L?.hooks,l0]),p;if(mV(F,"plugins"))try{p=await n4({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:J.config.cwd,onEvent:Y,providerId:J.config.providerId,modelId:J.config.modelId,workspaceInfo:z,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),gq(p.failures,p.warnings,L?.logger)}catch(i$){let X5=i$ instanceof Error?i$.message:String(i$);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${X5})`)}let N=r9(a?[a]:void 0,r9(L?.extensions,jQ(p?.extensions))),X0=mV(F,"plugins")?a2(p?.pluginPaths??[]):void 0,J0={...J.config,...L??{},sessionId:Q,hooks:f$,extensions:N,extensionContext:o,telemetry:o.telemetry},T0=dq(J0,Q,Z,D,X),p$=t8([J0.hooks,J0.checkpoint?.enabled===!0?hY({cwd:J0.cwd,sessionId:Q,logger:J0.logger,createCheckpoint:J0.checkpoint?.createCheckpoint,initialRunCount:vq(J.initialMessages),readSessionMetadata:K,writeSessionMetadata:G}):void 0]),j1={...J0,providerConfig:T0,workspaceMetadata:M,hooks:p$},o0=J.toolPolicies??J0.toolPolicies??f,x2=L0(j,J.capabilities),r$=x2?.requestToolApproval,A4=x2?.toolExecutors,f1=H?.(j1),K4=new OJ({currentWorkspacePath:z.rootPath,workspaces:{[z.rootPath]:z}});return{effectiveInput:J,config:j1,providerConfig:T0,workspaceMetadata:M,workspaceInfo:z,extensions:N,hooks:p$,toolPolicies:o0,requestToolApproval:r$,pluginSandboxShutdown:p?.shutdown,runtimeBuilderInput:{config:j1,hooks:p$,extensions:N,onTeamEvent:V,createSpawnTool:B,onTeamRestored:O,onSubAgentEvent:f1?.onSubAgentEvent,onSubAgentStart:f1?.onSubAgentStart,onSubAgentEnd:f1?.onSubAgentEnd,userInstructionService:U,pluginSkillDirectories:X0,configExtensions:F,toolExecutors:A4,toolPolicies:o0,workspaceManager:K4,logger:j1.logger,telemetry:j1.telemetry,requestToolApproval:r$}}}import{resolveDocumentsExtensionPath as lq}from"@cline/shared/storage";F0();function cV($,J,Q,Z,W){if(Q)F5($.telemetry,{ulid:J,apiProvider:$.providerId,...W});else G5($.telemetry,{ulid:J,apiProvider:$.providerId,...W});pq($.telemetry,{workspacePath:Z})}function pq($,J){let Q=lq("Hooks"),Z=w2(J.workspacePath),W=new Map;for(let j of Z){let f=j.hookEventName??"unknown",X=W.get(f)??{global:0,workspace:0};if(j.path===Q||j.path.startsWith(`${Q}/`))X.global+=1;else X.workspace+=1;W.set(f,X)}for(let[j,f]of W.entries())q5($,j,f.global,f.workspace)}function uV($,J){for(let Q of J.mentions)T5($,Q,J.matchedFiles.includes(Q)?1:0,"file",!J.matchedFiles.includes(Q));for(let Q of J.matchedFiles)_5($,"file",Q.length);for(let Q of J.ignoredMentions)O5($,"file","not_found",Q)}import{chmodSync as fH,existsSync as Z7,mkdirSync as MP,readFileSync as qP,writeFileSync as PP}from"node:fs";import{basename as XH,dirname as W7}from"node:path";import{resolveProviderSettingsPath as NP}from"@cline/shared/storage";import{existsSync as rq,mkdirSync as iq,readFileSync as nq,writeFileSync as aq}from"node:fs";import{mkdir as sq,readFile as oq,writeFile as tq}from"node:fs/promises";import{dirname as tZ,join as eq}from"node:path";import*as N0 from"@cline/llms";import{ModelCapabilitySchema as $P,ProviderCapabilitySchema as JP,ProviderClientSchema as QP,ProviderProtocolSchema as ZP}from"@cline/shared";import{z as l}from"zod";var WP=l.object({id:l.string().optional(),name:l.string().optional(),maxTokens:l.number().optional(),contextWindow:l.number().optional(),maxInputTokens:l.number().optional(),capabilities:l.array($P).optional(),supportsVision:l.boolean().optional(),supportsAttachments:l.boolean().optional(),supportsReasoning:l.boolean().optional()}).passthrough(),jP=l.object({name:l.string(),baseUrl:l.string(),defaultModelId:l.string().optional(),protocol:ZP.optional(),client:QP.optional(),capabilities:l.array(JP).optional(),modelsSourceUrl:l.string().optional()}).passthrough(),dV=l.object({provider:jP.optional(),models:l.record(l.string(),WP).optional()}).passthrough(),lV=l.object({version:l.literal(1),providers:l.record(l.string(),dV)}),fP=l.object({version:l.literal(1),providers:l.record(l.string(),l.unknown())}),TJ=new Set;function pV($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function x$($){return eq(tZ($.getFilePath()),"models.json")}function MJ(){return{version:1,providers:{}}}function rV($){let J=fP.safeParse($);if(!J.success)return MJ();let Q={};for(let[Z,W]of Object.entries(J.data.providers)){let j=dV.safeParse(W);if(j.success)Q[Z]=j.data}return{version:1,providers:Q}}function eZ($){if(!rq($))return MJ();try{let J=nq($,"utf8");return rV(JSON.parse(J))}catch{}return MJ()}async function C2($){try{let J=await oq($,"utf8");return rV(JSON.parse(J))}catch{}return MJ()}function iV($,J){iq(tZ($),{recursive:!0});let Q=lV.parse(J);aq($,`${JSON.stringify(Q,null,2)}
566
+ `,"utf8")}async function qJ($,J){await sq(tZ($),{recursive:!0});let Q=lV.parse(J);await tq($,`${JSON.stringify(Q,null,2)}
567
+ `,"utf8")}function nV($,J){return{id:$,name:J.name??$,supportsAttachments:J.capabilities?.includes("files"),supportsVision:J.capabilities?.includes("images"),supportsReasoning:J.capabilities?.includes("reasoning")||J.thinkingConfig!=null}}function aV($){if(!$||$.length===0)return;let J=new Set;if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("tools"))J.add("tools");return J.size>0?[...J]:void 0}function sV($){let J=new Set;if(!$||$.length===0)return[...J];if($.includes("streaming"))J.add("streaming");if($.includes("tools"))J.add("tools");if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("vision"))J.add("images"),J.add("files");return[...J]}function XP($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function oV($,J){return $??J??"openai-chat"}function tV($,J,Q){return $??Q??(J==="openai-responses"?"openai":"openai-compatible")}function eV($,J,Q){let Z=new Set(J?.capabilities??Q??[]);if(J?.supportsVision)Z.add("images");if(J?.supportsAttachments)Z.add("files");if(J?.supportsReasoning)Z.add("reasoning");return{id:$,name:J?.name??$,maxTokens:J?.maxTokens,contextWindow:J?.contextWindow,maxInputTokens:J?.maxInputTokens,capabilities:Z.size>0?[...Z]:void 0}}function YP($,J){for(let[Q,Z]of Object.entries(J??{})){let W=Z.id?.trim()||Q.trim();if(!W)continue;N0.registerModel($,W,eV(W,Z))}}function VP($,J,Q){return{...J??{},id:$,name:J?.name??$,capabilities:J?.capabilities??Q}}function HP($){return Object.assign({},...N0.resolveProviderModelCatalogKeys($).map((Q)=>N0.getGeneratedModelsForProvider(Q)))}function BP($){let J=$.provider.trim();if(!J||N0.isBuiltInProviderId(J))return;let Q=$.baseUrl?.trim();if(!Q)return;let Z=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J],W=HP(J),j=sV($.capabilities),f=j.length>0?j:void 0,X=$.model?.trim(),Y={...W,...Z?.models??{}};if(X)Y[X]=VP(X,Y[X],f);let V=Object.keys(Y).filter(Boolean),H=X||V[0];if(!H)return;let B=oV($.protocol,Z?.provider.protocol),A=tV($.client,B,Z?.provider.client);N0.registerProvider({provider:{id:J,name:Z?.provider.name??pV(J),description:Z?.provider.description,protocol:B,client:A,baseUrl:Q,modelsSourceUrl:Z?.provider.modelsSourceUrl,defaultModelId:H,capabilities:aV($.capabilities)??Z?.provider.capabilities,source:"file"},models:Y})}function PJ($){for(let J of Object.values($.providers))BP(J.settings)}function $4($,J){let Q=J.models??{};if(!XP(J.provider)){YP($,Q);return}let Z=sV(J.provider.capabilities),W=Object.entries(Q).map(([V,H])=>({id:H.id?.trim()||V.trim(),model:H})).filter(({id:V})=>V.length>0),j=J.provider.defaultModelId?.trim()||W[0]?.id||"default",f=oV(J.provider.protocol,void 0),X=tV(J.provider.client,f,void 0),Y=Object.fromEntries(W.map(({id:V,model:H})=>[V,{...eV(V,H,Z.length>0?Z:void 0),status:"active"}]));N0.registerProvider({provider:{id:$,name:J.provider.name.trim()||pV($),protocol:f,client:X,baseUrl:J.provider.baseUrl,modelsSourceUrl:J.provider.modelsSourceUrl,defaultModelId:j,capabilities:aV(J.provider.capabilities),source:"file"},models:Y})}function $H($){let J=x$($);if(TJ.has(J))return;let Q=eZ(J);for(let[Z,W]of Object.entries(Q.providers))$4(Z,W);TJ.add(J)}async function JH($){let J=x$($);if(TJ.has(J))return;let Q=await C2(J);for(let[Z,W]of Object.entries(Q.providers))$4(Z,W);TJ.add(J)}import{existsSync as AP,readFileSync as KP}from"node:fs";import{dirname as GP,join as $7}from"node:path";import*as wJ from"@cline/llms";import{resolveClineDataDir as FP}from"@cline/shared/storage";var NJ="openai",WH=wJ.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,QH=128000;function jH($){let J=$?.trim();if(!J)return;try{let Q=JSON.parse(J);if(!Q)return;let Z=typeof Q.expiresAt==="number"&&Number.isFinite(Q.expiresAt)?Q.expiresAt<10000000000?Q.expiresAt*1000:Q.expiresAt:void 0;return{accessToken:Q.idToken,refreshToken:Q.refreshToken,expiresAt:Z,accountId:Q.userInfo?.id}}catch{return}}function S($){let J=$?.trim();return J?J:void 0}function ZH($){if(!AP($))return;try{let J=KP($,"utf8"),Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return}function DP($){let J=$.dataDir??FP(),Q=$.globalStatePath??$7(J,"globalState.json"),Z=$.secretsPath??$7(J,"secrets.json"),W=ZH(Q),j=ZH(Z);if(!W&&!j)return;return{globalState:W??{},secrets:j??{}}}function J7($){if($===NJ)return WH;return $}function UP($,J,Q,Z){let W=Q==="plan"?"planMode":"actMode",j=J===Z?S(Q==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${W}OpenRouterModelId`,cline:`${W}ClineModelId`,openai:`${W}OpenAiModelId`,ollama:`${W}OllamaModelId`,lmstudio:`${W}LmStudioModelId`,litellm:`${W}LiteLlmModelId`,requesty:`${W}RequestyModelId`,together:`${W}TogetherModelId`,fireworks:`${W}FireworksModelId`,sapaicore:`${W}SapAiCoreModelId`,groq:`${W}GroqModelId`,baseten:`${W}BasetenModelId`,huggingface:`${W}HuggingFaceModelId`,"huawei-cloud-maas":`${W}HuaweiCloudMaasModelId`,oca:`${W}OcaModelId`,aihubmix:`${W}AihubmixModelId`,hicap:`${W}HicapModelId`,nousResearch:`${W}NousResearchModelId`,"vercel-ai-gateway":`${W}VercelAiGatewayModelId`}[J];return(X?S(typeof $[X]==="string"?$[X]:void 0):void 0)??j}function RP($,J,Q){let Z=Q==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,W=Q==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,j=Q==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,f=(J==="gemini"?W:void 0)??Z,X=f==="none"||f==="low"||f==="medium"||f==="high"?f:void 0,Y=typeof j==="number"&&Number.isInteger(j)&&j>0?j:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function zP($){let J=$["openai-codex-oauth-credentials"];if(!J)return;try{let Q=JSON.parse(J),Z=S(Q.access_token),W=S(Q.refresh_token),j=S(Q.accountId);if(!Z&&!W&&!j)return;return{...Z?{apiKey:Z}:{},auth:{...Z?{accessToken:Z}:{},...W?{refreshToken:W}:{},...j?{accountId:j}:{}}}}catch{return}}function LP($){let J=wJ.getGeneratedModelsForProvider($);return Object.keys(J)[0]??void 0}function _P($,J,Q,Z){let W=J7($),j=S(Z==="plan"?J.planModeApiProvider:J.actModeApiProvider),f=UP(J,$,Z,j)??LP(W),X=RP(J,W,Z),Y=typeof J.requestTimeoutMs==="number"&&Number.isInteger(J.requestTimeoutMs)&&J.requestTimeoutMs>0?J.requestTimeoutMs:void 0,V={anthropic:Q.apiKey,cline:Q.clineApiKey,openai:Q.openAiApiKey,"openai-native":Q.openAiNativeApiKey,openrouter:Q.openRouterApiKey,bedrock:Q.awsBedrockApiKey,gemini:Q.geminiApiKey,ollama:Q.ollamaApiKey,deepseek:Q.deepSeekApiKey,requesty:Q.requestyApiKey,together:Q.togetherApiKey,fireworks:Q.fireworksApiKey,qwen:Q.qwenApiKey,doubao:Q.doubaoApiKey,mistral:Q.mistralApiKey,litellm:Q.liteLlmApiKey,asksage:Q.asksageApiKey,xai:Q.xaiApiKey,moonshot:Q.moonshotApiKey,zai:Q.zaiApiKey,huggingface:Q.huggingFaceApiKey,nebius:Q.nebiusApiKey,sambanova:Q.sambanovaApiKey,cerebras:Q.cerebrasApiKey,groq:Q.groqApiKey,"huawei-cloud-maas":Q.huaweiCloudMaasApiKey,baseten:Q.basetenApiKey,"vercel-ai-gateway":Q.vercelAiGatewayApiKey,dify:Q.difyApiKey,minimax:Q.minimaxApiKey,hicap:Q.hicapApiKey,aihubmix:Q.aihubmixApiKey,nousResearch:Q.nousResearchApiKey,oca:Q.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,zP(Q));if($==="cline")try{let U=S(Q["cline:clineAccountId"]);if(U)H.auth={...H.auth??{},...jH(U)}}catch{}if($===NJ&&J.openAiHeaders)H.headers=J.openAiHeaders;if($==="bedrock"){let U=J.awsAuthentication==="profile"||J.awsUseProfile===!0;H.aws={accessKey:S(Q.awsAccessKey),secretKey:S(Q.awsSecretKey),sessionToken:S(Q.awsSessionToken),region:S(J.awsRegion),authentication:J.awsAuthentication,profile:U?S(J.awsProfile):void 0,usePromptCache:J.awsBedrockUsePromptCache,useCrossRegionInference:J.awsUseCrossRegionInference,useGlobalInference:J.awsUseGlobalInference,endpoint:S(J.awsBedrockEndpoint),customModelBaseId:S(Z==="plan"?J.planModeAwsBedrockCustomModelBaseId:J.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:S(J.vertexProjectId),region:S(J.vertexRegion)};if($===NJ&&(J.azureApiVersion||J.azureIdentity!==void 0))H.azure={apiVersion:S(J.azureApiVersion),useIdentity:J.azureIdentity};if($==="sapaicore")H.sap={clientId:S(Q.sapAiCoreClientId),clientSecret:S(Q.sapAiCoreClientSecret),tokenUrl:S(J.sapAiCoreTokenUrl),resourceGroup:S(J.sapAiResourceGroup),deploymentId:S(Z==="plan"?J.planModeSapAiCoreDeploymentId:J.actModeSapAiCoreDeploymentId),useOrchestrationMode:J.sapAiCoreUseOrchestrationMode};if($==="oca"){H.oca={mode:J.ocaMode};let U=S(Q.ocaRefreshToken);if(U)H.auth={...H.auth??{},refreshToken:U}}if($==="qwen")H.apiLine=J.qwenApiLine;if($==="moonshot")H.apiLine=J.moonshotApiLine;if($==="zai")H.apiLine=J.zaiApiLine;if($==="minimax")H.apiLine=J.minimaxApiLine;let B={anthropic:J.anthropicBaseUrl,openai:J.openAiBaseUrl,ollama:J.ollamaBaseUrl,lmstudio:J.lmStudioBaseUrl,litellm:J.liteLlmBaseUrl,gemini:J.geminiBaseUrl,requesty:J.requestyBaseUrl,asksage:J.asksageApiUrl,dify:J.difyBaseUrl,oca:J.ocaBaseUrl,aihubmix:J.aihubmixBaseUrl,sapaicore:J.sapAiCoreBaseUrl},A=S(V[$]),K=S(B[$]),G={provider:W,...A?{apiKey:A}:{},...f?{model:f}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...Y?{timeout:Y}:{},...H},R=e8.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function OP($,J){if($!==WH)return;if(!J.baseUrl||!J.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:J.baseUrl,defaultModelId:J.model},models:{[J.model]:{id:J.model,name:J.model,contextWindow:QH,maxInputTokens:QH,capabilities:["streaming","tools","images"]}}}}function TP($,J){let Q=new Set;for(let W of[$.actModeApiProvider,$.planModeApiProvider]){let j=S(W);if(j)Q.add(j)}if(S(J.apiKey))Q.add("anthropic");if(S(J.openRouterApiKey))Q.add("openrouter");if(S(J.openAiApiKey))Q.add(NJ);if(S(J.openAiNativeApiKey))Q.add("openai-native");if(S(J["openai-codex-oauth-credentials"]))Q.add("openai-codex");if(S(J.geminiApiKey))Q.add("gemini");if(S(J.ollamaApiKey))Q.add("ollama");if(S(J.awsAccessKey)||S(J.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||S($.awsProfile))Q.add("bedrock");if(S($.vertexProjectId)||S($.vertexRegion))Q.add("vertex");if(S(J.clineApiKey))Q.add("cline");let Z=jH(S(J["cline:clineAccountId"]));if(Z?.accessToken||Z?.refreshToken||Z?.accountId)Q.add("cline");if(S(J.ocaApiKey))Q.add("oca");if(S(J.sapAiCoreClientId)||S(J.sapAiCoreClientSecret)||S($.sapAiCoreTokenUrl)||S($.sapAiCoreBaseUrl)||S($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Q.add("sapaicore");return Q}function Q7($){let J=$.providerSettingsManager.read(),Q=DP($);if(!Q)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let{globalState:Z,secrets:W}=Q,j=Z.mode==="plan"?"plan":"act",f=TP(Z,W),X=S2();X.providers={...J.providers},X.lastUsedProvider=J.lastUsedProvider;let Y=new Date().toISOString(),V=0,H=$7(GP($.providerSettingsManager.getFilePath()),"models.json"),B=eZ(H),A=0;for(let R of f){let D=J7(R);if(X.providers[D])continue;let U=_P(R,Z,W,j);if(!U)continue;X.providers[D]={settings:U,updatedAt:Y,tokenSource:"migration"},V+=1;let F=OP(D,U);if(F&&!B.providers[D])B.providers[D]=F,A+=1}if(V===0&&A===0)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let K=S(j==="plan"?Z.planModeApiProvider:Z.actModeApiProvider),G=K?J7(K):void 0;if(X.lastUsedProvider=J.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),A>0)iV(H,B);return{migrated:V>0||A>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}function wP(){return new Date().toISOString()}var SP="cline",CP="cline-pass";function yP($){if(XH($)!=="providers.json")return;let J=W7($);if(XH(J)!=="settings")return;return W7(J)}class Q${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??NP(),this.dataDir=$.dataDir??yP(this.filePath),this.dataDir||!$.filePath)Q7({providerSettingsManager:this,dataDir:this.dataDir});if($H(this),PJ(this.read()),Z7(this.filePath))try{fH(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!Z7(this.filePath))return S2();try{let $=qP(this.filePath,"utf8"),J=JSON.parse($),Q=_J.safeParse(J);if(Q.success)return PJ(Q.data),Q.data}catch{}return S2()}write($){let J=_J.parse($),Q=W7(this.filePath);if(!Z7(Q))MP(Q,{recursive:!0,mode:448});PP(this.filePath,`${JSON.stringify(J,null,2)}
568
+ `,"utf8");try{fH(this.filePath,384)}catch{}PJ(J)}saveProviderSettings($,J={}){let Q=e8.parse($),Z=this.read(),W=Q.provider,j=J.setLastUsed!==!1,f=Z.providers[W],X=J.tokenSource??f?.tokenSource??"manual",Y={...Z,providers:{...Z.providers,[W]:{settings:Q,updatedAt:wP(),tokenSource:X}},lastUsedProvider:j?W:Z.lastUsedProvider};return this.write(Y),Y}resolveProviderSettings($,J){let Q=$.providers[J]?.settings,W=f0(J)?.storageProviderId;if(!W||W===J)return Q;let j=$.providers[W]?.settings;if(!j)return Q;return e8.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Q??{},provider:J})}getProviderSettings($){let J=this.read();return this.resolveProviderSettings(J,$)}resolveLastUsedProviderId($,J){let Q=$.lastUsedProvider;if(Q===CP&&J.isClinePassEnabled===!1)return SP;return Q}getLastUsedProviderSettings($={}){let J=this.read(),Q=this.resolveLastUsedProviderId(J,$);if(!Q)return;return this.resolveProviderSettings(J,Q)}getProviderConfig($,J){let Q=this.getProviderSettings($);if(!Q)return;return V1(Q,J)}getLastUsedProviderConfig($={}){let J=this.getLastUsedProviderSettings($);if(!J)return;return V1(J,$)}async refreshCatalog(){try{await h4({})}catch{}}}F0();q2();import{execFile as EP}from"node:child_process";import{promisify as bP}from"node:util";var y2=bP(EP);function j7($){let J=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(J?.history)?J.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let W=String(Z.ref??"").trim(),j=Number(Z.createdAt??0),f=Number(Z.runCount??0);if(W.length===0||!Number.isFinite(j)||!Number.isInteger(f)||f<1)return[];let X=Z.kind==="stash"||Z.kind==="commit"?Z.kind:void 0;return[{ref:W,createdAt:j,runCount:f,...X?{kind:X}:{}}]})}function YH($,J){let Q=j7($).filter((W)=>W.runCount<=J),Z=Q.at(-1);return Z?{latest:Z,history:Q}:void 0}function hP($,J){return $.reduce((Q,Z)=>{if(Z.runCount>J)return Q;if(!Q||Z.runCount>Q.runCount)return Z;return Q},void 0)}function VH($,J){let Q=0;for(let Z=0;Z<$.length;Z+=1){let W=$[Z];if(W?.role!=="user")continue;if(("metadata"in W&&W.metadata&&typeof W.metadata==="object"?W.metadata:void 0)?.kind==="recovery_notice")continue;if(Q+=1,Q===J)return Z}throw Error(`Could not find user message for checkpoint run ${J}`)}function kP($,J){let Q=VH($,J);return $.slice(0,Q+1)}function HH($,J){let Q=VH($,J);return $.slice(0,Q)}function BH($){let J=$.checkpointRunCount;if(!Number.isInteger(J)||J<1)throw Error("checkpointRunCount must be a positive integer");let Q=hP(j7($.session),J);if(!Q)throw Error(`No checkpoint found at or before run ${J} in session ${$.session.sessionId}`);let Z=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Z)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Q,cwd:Z,...$.restoreMessages!==!1?{messages:kP($.messages??[],J)}:{}}}async function AH($,J){if((await y2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await y2("git",["-C",$,"cat-file","-e",`${J.ref}^{commit}`],{windowsHide:!0}),await y2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await y2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),J.kind==="commit"){await y2("git",["-C",$,"reset","--hard",J.ref],{windowsHide:!0});return}await y2("git",["-C",$,"stash","apply",J.ref],{windowsHide:!0})}class a0 extends Error{code;constructor($,J){super(J);this.code=$;this.name="SessionVersioningError"}}function IP($){let J=$.sessionId.trim();if(!J)throw new a0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new a0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new a0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new a0("invalid_restore","checkpointRunCount must be a positive integer");return J}class E2{async restoreCheckpoint($){let J=$.restore?.messages!==!1,Q=$.restore?.workspace!==!1,Z=IP({sessionId:$.sessionId,restoreMessages:J,restoreWorkspace:Q,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),W=await $.getSession(Z);if(!W)throw new a0("session_not_found",`Session ${Z} not found`);let j=J?await $.readMessages(Z):void 0;if(J&&j?.length===0)throw new a0("session_messages_not_found",`No messages found for session ${Z}`);let f=BH({session:W,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:J});if(Q)await($.applyWorkspaceCheckpoint??AH)(f.cwd,f.checkpoint);let X=i1({session:W,messages:j});if(!J)return{checkpoint:f.checkpoint,sourceSnapshot:X};let Y=YH(W,$.checkpointRunCount),V=$.restore?.omitCheckpointMessageFromSession?HH(j??[],$.checkpointRunCount):f.messages??[],H={sourceSession:W,sourceMessages:j,sourceSnapshot:X,plan:f,restoredCheckpointMetadata:Y,initialMessages:V,restoreMessages:J,restoreWorkspace:Q,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new a0("invalid_restore","start is required when restore.messages is true");let B=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,A=await $.startSession(B),K=$.getStartedSessionId?.(A);if(K)await($.retainCheckpointRefs??bY)(f.cwd,K,Y?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:A,messages:f.messages,checkpoint:f.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:i1({session:G,messages:V})}:{}}}}import{hasRuntimeConfigExtension as sP}from"@cline/shared";import{nanoid as oP}from"nanoid";p0();import{appendFileSync as xP,existsSync as b2,mkdirSync as KH,readdirSync as gP,readFileSync as GH,renameSync as mP,writeFileSync as vP}from"node:fs";import{join as f7}from"node:path";import{resolveTeamDataDir as cP}from"@cline/shared/storage";function FH(){return new Date().toISOString()}function X7($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function DH($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class SJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??cP()}init(){this.ensureTeamDir()}listTeamNames(){if(!b2(this.teamDirPath))return[];return gP(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>b2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let J=this.readEnvelope($);return J?.teamState?DH(J.teamState):void 0}readHistory($,J=200){let Q=this.historyPath($);if(!b2(Q))return[];return GH(Q,"utf8").split(`
569
+ `).map((Z)=>Z.trim()).filter(Boolean).map((Z)=>{try{return JSON.parse(Z)}catch{return}}).filter((Z)=>Z!==void 0).reverse().slice(0,J)}loadRuntime($){let J=this.readEnvelope($);return{state:J?.teamState?DH(J.teamState):void 0,teammates:J?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,J){this.ensureTeamSubdir($),xP(this.historyPath($),`${JSON.stringify({ts:FH(),eventType:J.type,payload:J})}
570
+ `,"utf8")}persistRuntime($,J,Q){this.ensureTeamSubdir($);let Z={version:1,updatedAt:FH(),teamState:J,teammates:Q},W=this.statePath($),j=`${W}.tmp`;vP(j,`${JSON.stringify(Z,null,2)}
571
+ `,"utf8"),mP(j,W)}markInProgressRunsInterrupted($,J){let Q=this.readEnvelope($);if(!Q?.teamState?.runs?.length)return[];let Z=Q.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Z.length===0)return[];let W=new Date;return Q.teamState={...Q.teamState,runs:Q.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:J,endedAt:W}:j)},this.persistRuntime($,Q.teamState,Q.teammates),Z}ensureTeamDir(){if(!b2(this.teamDirPath))KH(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let J=f7(this.ensureTeamDir(),X7($));if(!b2(J))KH(J,{recursive:!0});return J}statePath($){return f7(this.ensureTeamDir(),X7($),"state.json")}historyPath($){return f7(this.ensureTeamDir(),X7($),"task-history.jsonl")}readEnvelope($){let J=this.statePath($);if(!b2(J))return;try{let Q=JSON.parse(GH(J,"utf8"));if(Q?.version===1&&Q.teamState)return Q}catch{}return}}import{existsSync as uP,mkdirSync as dP}from"node:fs";import{join as lP}from"node:path";import{safeJsonParse as UH}from"@cline/shared";import{loadSqliteDb as pP,nowIso as Y7}from"@cline/shared/db";import{resolveDbDataDir as rP}from"@cline/shared/storage";function iP(){return rP()}function h2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function nP($){let J=UH($);if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,j=W.agentId,f=W.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof f!=="string"||!f.trim())continue;let X={agentId:j.trim(),rolePrompt:f};if(typeof W.modelId==="string"&&W.modelId.trim())X.modelId=W.modelId.trim();if(typeof W.maxIterations==="number"&&Number.isFinite(W.maxIterations))X.maxIterations=Math.max(1,Math.floor(W.maxIterations));Q.push(X)}return Q}function aP($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class J4{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??iP()}init(){this.getRawDb()}ensureTeamDir(){if(!uP(this.teamDirPath))dP(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return lP(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=pP(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
572
572
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
573
573
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
574
574
  version INTEGER NOT NULL
@@ -652,7 +652,7 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
652
652
  version INTEGER NOT NULL DEFAULT 1,
653
653
  PRIMARY KEY(team_name, fragment_id)
654
654
  );
655
- `)}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}withTransaction($){let J=this.getRawDb();J.exec("BEGIN IMMEDIATE;");try{$(),J.exec("COMMIT;")}catch(Q){try{J.exec("ROLLBACK;")}catch{}throw Q}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let J=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[h2($)]);if(!J)return;let Q=FH(J.state_json);if(!Q)return;try{return nP(Q)}catch{return}}readHistory($,J=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[h2($),J]).flatMap((Q)=>{try{return[{eventType:Q.event_type,payload:JSON.parse(Q.payload_json),ts:Q.ts}]}catch{return[]}})}loadRuntime($){let J=h2($),Q=this.readState(J),Z=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[J]),W=Z?iP(Z.teammates_json):[];return{state:Q,teammates:W,interruptedRunIds:[]}}appendTeamEvent($,J,Q,Z){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
655
+ `)}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}withTransaction($){let J=this.getRawDb();J.exec("BEGIN IMMEDIATE;");try{$(),J.exec("COMMIT;")}catch(Q){try{J.exec("ROLLBACK;")}catch{}throw Q}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let J=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[h2($)]);if(!J)return;let Q=UH(J.state_json);if(!Q)return;try{return aP(Q)}catch{return}}readHistory($,J=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[h2($),J]).flatMap((Q)=>{try{return[{eventType:Q.event_type,payload:JSON.parse(Q.payload_json),ts:Q.ts}]}catch{return[]}})}loadRuntime($){let J=h2($),Q=this.readState(J),Z=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[J]),W=Z?nP(Z.teammates_json):[];return{state:Q,teammates:W,interruptedRunIds:[]}}appendTeamEvent($,J,Q,Z){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
656
656
  VALUES (?, ?, ?, ?, NULL, ?)`,[h2($),Y7(),J,JSON.stringify(Q),Z??null])}persistRuntime($,J,Q){let Z=h2($),W=Y7();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
657
657
  VALUES (?, ?, ?, ?)
658
658
  ON CONFLICT(team_name) DO UPDATE SET
@@ -699,29 +699,29 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
699
699
  reviewed_by = excluded.reviewed_by,
700
700
  reviewed_at = excluded.reviewed_at,
701
701
  version = team_outcome_fragments.version + 1`,[Z,j.outcomeId,j.id,j.section,j.sourceAgentId,j.sourceRunId??null,j.content,j.status,j.reviewedBy??null,j.reviewedAt?j.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,J){let Q=h2($),Z=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Q]);if(Z.length===0)return[];let W=Y7();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
702
- WHERE team_name = ? AND status IN ('queued', 'running')`,[J,W,Q]),Z.map((j)=>j.run_id)}handleTeamEvent($,J){this.appendTeamEvent($,J.type,J)}}function DH($={}){try{let J=new J4($);return J.init(),J}catch{let J=new SJ({teamDir:$.teamDir});return J.init(),J}}function CJ($,J){return aP($,J)}function oP($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function tP($,J){return $.filter((Q)=>oP(Q.name,J))}function V7($,J){return y1(tP($,J))}var eP={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 $N($){let J=$.trim().toLowerCase();return eP[J]??J}function JN($,J){if(J.tools===void 0)return $;let Q=new Set(J.tools.map($N));if(J.skills!==void 0)Q.add("skills");return $.filter((Z)=>Q.has(Z.name))}function UH(){return`team-${sP(5)}`}function yJ($,J,Q,Z,W,j,f,X){let Y=$1[x1({mode:Q})],V=Z8(J,Z,Q,W??Q8);return V7(H8({cwd:$,...Y,enableSkills:!!f,...V,executors:{...f?{skills:f}:{},...X??{}}}),j)}function QN($){return yJ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,ZN,$.toolExecutors).some((J)=>J.name==="skills")}var ZN=async()=>"";async function WN($){let J=H0();if(!L$({filePath:J}))return{tools:[]};let Q=new R8({clientFactory:h6({settingsPath:J})}),Z;try{Z=await U8(Q,{filePath:J})}catch(X){await Q.dispose().catch(()=>{});let Y=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${Y}`),{tools:[]}}let W=Z.filter((X)=>X.disabled!==!0),j=await Promise.allSettled(W.map((X)=>I6({serverName:X.name,provider:Q}))),f=[];for(let[X,Y]of j.entries())if(Y.status==="fulfilled")f.push(...Y.value);else{let V=Y.reason instanceof Error?Y.reason.message:String(Y.reason);$?.log(`[mcp] Failed to load tools from MCP server "${W[X].name}", skipping: ${V}`)}return{tools:f,shutdown:async()=>{await Q.dispose()}}}function jN($,J){if(!$)return;for(let Q of $.getTeammateIds())try{$.shutdownTeammate(Q,J)}catch{}}function fN($){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 XN($){let J=$1[x1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??J.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??J.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class EJ{teamRuntimeEntries=new Map;async build($){let{config:J,hooks:Q,extensions:Z,logger:W,telemetry:j,createSpawnTool:f,onTeamRestored:X,userInstructionService:Y,configExtensions:V,toolExecutors:H}=$,B=$.onTeamEvent??(()=>{}),A=XN(J),K=J.workspaceRoot??J.cwd,G=$.toolPolicies??J.toolPolicies,R=H1(),D=[],U=J.teamName?.trim()||UH(),F=J.sessionId?.trim()||U,O=A.enableSpawnAgent?jJ({workspaceRoot:K}):{configs:[],errors:[]},T=O.configs.some((I)=>I.skills!==void 0),L=CJ(V,"rules"),z=CJ(V,"skills"),M=z||T,P=CJ(V,"workflows"),C=CJ(V,"plugins"),m=L||z||P,n=!1,o=Boolean(Y),a=Y,l0;for(let I of O.errors)(W??J.logger)?.log?.(`[agents] Failed to load agent config at ${I.path}: ${I.error.message}`);if(!a&&(m||T))a=U2({skills:M?{workspacePath:K,includePluginSkills:C,pluginSkillDirectories:C?$.pluginSkillDirectories:void 0,pluginPaths:J.pluginPaths,cwd:J.cwd}:{workspacePath:K},rules:{workspacePath:J.cwd},workflows:{workspacePath:J.cwd}});if(a)await a.start().catch(()=>{});let f$=A.enableTools&&z&&Boolean(a)&&a?.hasConfiguredSkills(J.skills)===!0&&QN({cwd:J.cwd,providerId:J.providerId,mode:A.mode,modelId:J.modelId,toolRoutingRules:J.toolRoutingRules,toolPolicies:G,toolExecutors:H}),p=a&&m?a.createExtension({includeRules:L,includeSkills:z,includeWorkflows:P,registerSkillsTool:f$,allowedSkillNames:J.skills}):void 0,W1=p?[...Z??J.extensions??[],p]:Z??J.extensions;if(A.enableTools){if(D.push(...yJ(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H)),!A.disableMcpSettingsTools){let I=await WN(J.logger);D.push(...I.tools),l0=I.shutdown}}let N,X0=A.enableAgentTeams?DH():void 0,J0=X0?.loadRuntime(F),T0=J0?.state,p$=J0?.teammates??[],j1=new Map(p$.map((I)=>[I.agentId,I])),o0=J.sessionId||U,x2,r$=[],A4=!1,f1=G2({providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey??"",baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:Q,extensions:W1,logger:W??J.logger,telemetry:$.telemetry??J.telemetry,workspaceMetadata:J.workspaceMetadata});if(A.enableSpawnAgent){if(O.configs.length>0)D.push(...V7(XJ({configProvider:f1,agents:O.configs,createSubAgentTools:(I)=>A.enableTools?JN(yJ(J.cwd,I.providerId??J.providerId,A.mode,I.modelId??J.modelId,J.toolRoutingRules,G,I.skills!==void 0&&a?.createSkillsExecutor?a.createSkillsExecutor(I.skills):void 0,H),I):[],hookErrorMode:J.hookErrorMode,toolPolicies:G,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),G))}if(!this.teamRuntimeEntries.has(o0))this.teamRuntimeEntries.set(o0,{delegatedAgentConfigProvider:f1});let K4=()=>{if(!A.enableAgentTeams)return;let I=this.teamRuntimeEntries.get(o0)??{delegatedAgentConfigProvider:f1};if(this.teamRuntimeEntries.set(o0,I),N=I.runtime,!N){if(N=new l8({teamName:U,leadAgentId:J.sessionId||"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(t)=>{if(B(t),N&&X0){if(t.type==="teammate_spawned"&&t.teammate?.rolePrompt){let X1={agentId:t.agentId,rolePrompt:t.teammate.rolePrompt,modelId:t.teammate.modelId,maxIterations:t.teammate.maxIterations};j1.set(X1.agentId,X1)}if(t.type==="teammate_shutdown"&&!fN(t.reason))j1.delete(t.agentId);X0.handleTeamEvent(F,t),X0.persistRuntime(F,N.exportState(),Array.from(j1.values()))}}}),T0)N.hydrateState(T0),A4=!0;I.runtime=N}if(!n){if(!N)return;n=!0;let t=w6({runtime:N,leadAgentId:J.sessionId||"lead",restoredFromPersistence:Boolean(T0),restoredTeammates:p$,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(X1)=>{r$=X1,x2?.addTools(X1)},createBaseTools:A.enableTools?()=>yJ(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H):void 0,teammateConfigProvider:f1});if(A4)N.recoverActiveRuns("runtime_recovered");if(t.restoredFromPersistence)X?.();D.push(...t.tools)}return N};if(A.enableSpawnAgent&&f){let I=f();D.push({...I,execute:async(t,X1)=>{return K4(),I.execute(t,X1)}})}if(A.enableAgentTeams)K4();let i$=V7(D,G),X5=i$.some((I)=>I.name==="submit_and_exit"&&I.lifecycle?.completesRun===!0),G4=A.enableAgentTeams?()=>{let I=this.teamRuntimeEntries.get(o0)?.runtime;if(!I)return;let t=I.listTasks(),X1=t.some((T1)=>T1.status==="in_progress"||T1.status==="pending"),XW=I.listRuns({}),UA=XW.some((T1)=>T1.status==="running"||T1.status==="queued");if(X1||UA){let T1=t.filter((S0)=>S0.status==="in_progress"||S0.status==="pending").map((S0)=>`${S0.id} (${S0.status}): ${S0.title}`).join(", "),YW=XW.filter((S0)=>S0.status==="running"||S0.status==="queued").map((S0)=>`${S0.id} (${S0.status})`).join(", "),Y5=[];if(T1)Y5.push(`Unfinished tasks: ${T1}`);if(YW)Y5.push(`Active runs: ${YW}`);return`[SYSTEM] You still have team obligations. ${Y5.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,DA=X5?{requireCompletionTool:!0,...G4?{completionGuard:G4}:{}}:G4?{completionGuard:G4}:void 0;return{tools:i$,logger:W??J.logger,telemetry:j??J.telemetry,teamRuntime:N,teamRestoredFromPersistence:Boolean(T0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(o0)?.delegatedAgentConfigProvider??f1,extensions:W1,completionPolicy:DA,registerLeadAgent:(I)=>{if(x2=I,r$.length>0)I.addTools(y1(r$,[...R]))},shutdown:async(I)=>{if(jN(N,I),this.teamRuntimeEntries.delete(o0),await l0?.(),!o)a?.stop()}}}}function YN($,J){let Q=$?.expiresAt,Z=J?.expiresAt;return $?.accessToken===J?.accessToken&&$?.refreshToken===J?.refreshToken&&$?.accountId===J?.accountId&&Q===Z}class bJ 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 H7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new Q$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let J=f0($.providerId);if(!J)return null;return this.resolveWithSingleFlight(J.providerId,J.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,J,Q=!1){let Z=this.refreshInFlight.get(J);if(Z)return Z;let W=this.resolveProviderApiKeyInternal($,J,Q).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(J)});return this.refreshInFlight.set(J,W),W}async resolveProviderApiKeyInternal($,J,Q){let Z=f0($);if(!Z)return null;let W=this.providerSettingsManager.getProviderSettings(J);if(!W)return null;let j=p5($,W);if(!j)return null;let f=await Z.refresh({settings:W,credentials:j,forceRefresh:Q,telemetry:this.telemetry});if(!f)throw new bJ($);let X=c2({manager:this.providerSettingsManager,providerId:$,settings:W,credentials:f,setLastUsed:!1,save:!1}),Y=!YN(W.auth,X.auth);if(Y)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:Z.getApiKey(X)??f.access,accountId:f.accountId,refreshed:Y}}}import{normalizeUserInput as VN}from"@cline/shared";import{nanoid as HN}from"nanoid";class RH{list($){return $?m0($):[]}update($,J){if(!$)return{sessionId:J.sessionId,prompts:[],updated:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((Y)=>Y.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:m0($),updated:!1};let W=$.pendingPrompts[Z];if(!W)return{sessionId:J.sessionId,prompts:m0($),updated:!1};let j=J.prompt===void 0?W.prompt:VN(J.prompt).trim();if(!j)throw Error("prompt cannot be empty");let f=J.delivery??W.delivery,X={...W,prompt:j,mode:J.mode??W.mode,delivery:f};return $.pendingPrompts.splice(Z,1),BN($,X,Z,W.delivery),{sessionId:J.sessionId,prompts:m0($),prompt:hJ(X),updated:!0}}delete($,J){if(!$)return{sessionId:J.sessionId,prompts:[],removed:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((j)=>j.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:m0($),removed:!1};let[W]=$.pendingPrompts.splice(Z,1);return{sessionId:J.sessionId,prompts:m0($),prompt:W?hJ(W):void 0,removed:!0}}enqueue($,J){let{prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f}=J,X=$.pendingPrompts.findIndex((Y)=>Y.prompt===Q);if(X>=0){let[Y]=$.pendingPrompts.splice(X,1),V={...Y,prompt:Q,mode:Z??Y.mode,userImages:j??Y.userImages,userFiles:f??Y.userFiles};if(W==="steer"||Y.delivery==="steer")$.pendingPrompts.unshift({...V,delivery:"steer"});else $.pendingPrompts.push(V)}else{let Y={id:`pending_${Date.now()}_${HN(5)}`,prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f};if(W==="steer")$.pendingPrompts.unshift(Y);else $.pendingPrompts.push(Y)}return m0($)}consumeSteer($){let J=$.pendingPrompts.findIndex((Z)=>Z.delivery==="steer");if(J<0)return{prompts:m0($)};let[Q]=$.pendingPrompts.splice(J,1);return{entry:Q,prompts:m0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:m0($)}}requeueFront($,J){return $.pendingPrompts.unshift(J),m0($)}clear($){return $.pendingPrompts.length=0,[]}}class B7{deps;service=new RH;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Q=this.service.update(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}delete($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Q=this.service.delete(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}enqueue($,J){let Q=this.deps.getSession($);if(!Q||Q.aborting)return;this.service.enqueue(Q,J),this.emitPrompts(Q),this.scheduleDrain($,Q)}consumeSteer($){let J=this.deps.getSession($);if(!J)return;let{entry:Q}=this.service.consumeSteer(J);if(!Q)return;return this.emitPrompts(J),this.emitSubmitted(J,Q),Q}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:m0($)}})}scheduleDrain($,J){if(J.pendingPrompts.length===0||J.aborting||J.drainingPendingPrompts||!J.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let J=this.deps.getSession($);if(!J)return;if(J.aborting||J.drainingPendingPrompts)return;if(!J.agent.canStartRun())return;let{entry:Q}=this.service.shiftNext(J);if(!Q)return;this.emitPrompts(J),this.emitSubmitted(J,Q),J.drainingPendingPrompts=!0;let Z=!0;try{await this.deps.send({sessionId:$,prompt:Q.prompt,...Q.mode?{mode:Q.mode}:{},userImages:Q.userImages,userFiles:Q.userFiles})}catch{Z=!1,this.service.requeueFront(J,Q),this.emitPrompts(J)}finally{if(J.drainingPendingPrompts=!1,Z&&J.pendingPrompts.length>0&&J.status!=="failed"&&J.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,J){let Q=hJ(J);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}})}}function hJ($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function m0($){return $.pendingPrompts.map(hJ)}function BN($,J,Q,Z){if(J.delivery==="steer")$.pendingPrompts.unshift(J);else if(Z==="steer")$.pendingPrompts.push(J);else $.pendingPrompts.splice(Q,0,J)}F0();class K7{deps;constructor($){this.deps=$}dispatchAgentEvent($,J,Q){let Z=this.deps.getSession($),W={sessionId:$,config:J,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=uZ(Q),f=!!Z&&(!j.agentId||j.agentId===A7(Z.agent));dZ(W,Q,f?{isPrimaryAgentEvent:!0,agentId:A7(Z.agent),conversationId:Z.agent.getConversationId(),...Z?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,J){let Q=this.deps.getSession($);if(Q){if(TZ(Q,J),J.type==="agent_event"){let Z={sessionId:$,config:Q.config,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};dZ(Z,J.event,{agentId:J.agentId,teamRole:"teammate",teamAgentId:J.agentId,isPrimaryAgentEvent:!1})}if(J.type==="teammate_spawned"){let Z=L1({agentId:J.teammate.runtimeAgentId??J.agentId,conversationId:J.teammate.conversationId,parentAgentId:J.teammate.parentAgentId,createdByAgentId:A7(Q.agent),teamId:Q.runtime.teamRuntime?.getTeamId(),teamName:Q.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:J.agentId});if(Z)V$(Q.config.telemetry,{ulid:$,modelId:J.teammate.modelId??Q.config.modelId,provider:Q.config.providerId,...Z})}}if(await MZ($,J,this.deps.invokeBackendOptional),Q)qZ(Q,$,J,this.deps.emit)}async handlePluginEvent($,J,Q){if(J.name==="plugin_log"){this.handlePluginLog($,J.payload);return}if(J.name==="automation_event"){let Y=this.deps.getSession($)?.config.extensionContext?.automation??Q;if(!Y)return;let V=J.payload&&typeof J.payload==="object"?J.payload:void 0;if(!V)return;await Y.ingestEvent(V);return}if(J.name!=="steer_message"&&J.name!=="queue_message"&&J.name!=="pending_prompt")return;let Z=J.payload&&typeof J.payload==="object"?J.payload:void 0,W=typeof Z?.sessionId==="string"&&Z.sessionId.trim().length>0?Z.sessionId.trim():$,j=typeof Z?.prompt==="string"?Z.prompt.trim():"";if(!j)return;let f=J.name==="steer_message"?"steer":J.name==="queue_message"?"queue":Z?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(W,{prompt:j,delivery:f})}handlePluginLog($,J,Q){let Z=this.deps.getSession($),W=Q??Z?.config.extensionContext?.logger??Z?.config.logger;if(!W||!J||typeof J!=="object")return;let j=J,f=typeof j.message==="string"?j.message:"";if(!f)return;let X=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(X.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)X.pluginName=j.pluginName;if(j.level==="debug"){W.debug(f,X);return}if(j.level==="error"){if(W.error)W.error(f,X);else W.log(f,{...X,severity:"error"});return}W.log(f,X)}}function A7($){return $.getAgentId()}function G7($){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:e1($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function F7($,J){let Q=$[J];return typeof Q==="function"?Q:null}async function zH($,J,...Q){let Z=F7($,J);if(!Z)throw Error(`session service method not available: ${J}`);return Promise.resolve(Z.apply($,Q))}async function LH($,J,...Q){let Z=F7($,J);if(!Z)return;await Promise.resolve(Z.apply($,Q))}async function _H($,J,...Q){let Z=F7($,J);if(!Z)return;return await Promise.resolve(Z.apply($,Q))}p0();F0();function D7($,J,Q){return{onSubAgentEvent:(Z)=>$.onAgentEvent(Q,J,Z),onSubAgentStart:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime;$.subAgentStarts.set(Z.subAgentId,{startedAt:Date.now(),rootSessionId:Q});let j=L1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId});if(j)V$(J.telemetry,{ulid:Q,modelId:J.modelId,provider:J.providerId,...j});z4(J.telemetry,{event:"started",ulid:Q,durationMs:0,parentId:Z.parentAgentId,agentId:Z.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Q,Z)},onSubAgentEnd:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime,j=$.subAgentStarts.get(Z.subAgentId),f=j?Date.now()-j.startedAt:0,X=Z.result?.text?Z.result.text.split(`
703
- `).length:0;z4(J.telemetry,{event:"ended",ulid:Q,durationMs:f,outputLines:X,errorMessage:Z.error?String(Z.error):void 0,agentId:Z.subAgentId,parentId:Z.parentAgentId,...L1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId})}),$.subAgentStarts.delete(Z.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Q,Z)}}}function U7($,J,Q,Z){let W=D7($,J,Q);return D2({configProvider:{getRuntimeConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:J.hooks,extensions:J.extensions,logger:J.logger,telemetry:J.telemetry},getConnectionConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let f=J.enableTools?H8({cwd:J.cwd,...$1[x1({mode:J.mode})],executors:Z}):[];if(J.enableSpawnAgent)f.push(U7($,J,Q,Z));return y1(f)},...W})}import{readFile as AN,stat as KN}from"node:fs/promises";var GN=20480000;async function OH($){let J=await KN($);if(!J.isFile())throw Error("Path is not a file");if(J.size>GN)throw Error("File is too large to read into context.");let Q=await AN($,"utf8");if(Q.includes("\x00"))throw Error("Cannot read binary file into context.");return Q}var TH=5000;function Q4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function ON($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=Q4(J.inputTokens),Z=Q4(J.outputTokens),W=Q4(J.cacheReadTokens),j=Q4(J.cacheWriteTokens),f=Q4(J.totalCost);if(Q===void 0||Z===void 0||W===void 0||j===void 0||f===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:W,cacheWriteTokens:j,totalCost:f}}function TN($,J){return{inputTokens:Math.max($.inputTokens,J.inputTokens),outputTokens:Math.max($.outputTokens,J.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,J.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,J.cacheWriteTokens),totalCost:Math.max($.totalCost,J.totalCost)}}class Z${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new h8;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new E2;constructor($){let J=DN();if(J)_N(J);let Q=g0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new EJ,this.createAgentInstance=$.createAgent??((Z)=>new g1(Z)),this.defaultCapabilities=L0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new Q$,this.oauthTokenManager=$.oauthTokenManager??new H7({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Q),this.defaultFetch=$.fetch,this.pendingPromptsController=new B7({getSession:(Z)=>this.sessions.get(Z),emit:(Z)=>this.emit(Z),send:(Z)=>this.runTurn(Z)}),this.pendingPrompts={list:async(Z)=>this.pendingPromptsController.list(Z.sessionId),update:async(Z)=>this.pendingPromptsController.update(Z),delete:async(Z)=>this.pendingPromptsController.delete(Z)},this.eventBridge=new K7({getSession:(Z)=>this.sessions.get(Z),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Z)=>this.emit(Z),persistMessages:(Z,W,j)=>{this.invoke("persistSessionMessages",Z,W,j)},enqueuePendingPrompt:(Z,W)=>this.pendingPromptsController.enqueue(Z,W),invokeBackendOptional:(Z,...W)=>this.invokeOptional(Z,...W)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!J?.apiKey)return $;return{...$,config:{...$.config,apiKey:J.apiKey}}}async startSession($){let J=$.source??z0.CLI,Q=s(),Z=$.config.sessionId?.trim()??"",W=Z||RN(),j=await this.applyInitialOAuthCredentials($),f=j.initialMessages??[],X=f.length>0?GJ(f):U0(),Y=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Y)throw Error("session service method not available: ensureSessionsDir");let V=R7(Y,W),H=R7(V,`${W}.messages.json`),B=R7(V,`${W}.json`),A=e1($.config),K=P0.parse({version:1,session_id:W,source:J,pid:process.pid,started_at:Q,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:A,team_name:j.config.teamName,enable_tools:j.config.enableTools,enable_spawn:j.config.enableSpawnAgent,enable_teams:j.config.enableAgentTeams,prompt:j.prompt?.trim()||void 0,messages_path:H}),G;if(Z.length>0&&f.length>0&&!j.prompt?.trim()){let N=await this.invokeOptionalValue("readSessionManifest",W);if(N)K=N,G={manifestPath:B,messagesPath:N.messages_path||H,manifest:N}}let D=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:V,rootMessagesPath:G?.messagesPath??H,manifest:K});this.usageBySession.set(W,X),this.aggregateUsageBySession.set(W,D);let U=L0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,z,M={getSession:(N)=>this.sessions.get(N),subAgentStarts:this.subAgentStarts,onAgentEvent:(N,X0,J0)=>this.eventBridge.dispatchAgentEvent(N,X0,J0),invokeBackendOptional:(N,...X0)=>this.invokeOptional(N,...X0)};z=await gV({input:j,localRuntime:$.localRuntime,sessionId:W,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(N)=>{if(N.name==="plugin_log"){this.eventBridge.handlePluginLog(W,N.payload,T);return}this.eventBridge.handlePluginEvent(W,N,L)},onTeamEvent:(N)=>{this.eventBridge.handleTeamEvent(W,N),z.config.onTeamEvent?.(N)},createSpawnTool:()=>U7(M,z.config,W,F),createSubAgentLifecycleCallbacks:(N)=>D7(M,N,W),readSessionMetadata:async()=>(await this.getSession(W))?.metadata,writeSessionMetadata:async(N)=>{await this.persistSessionMetadata(W,()=>N)}});let P=await this.runtimeBuilder.build(z.runtimeBuilderInput),C=z.config,m=z.providerConfig;if(P.teamRuntime&&!C.teamName?.trim())C.teamName=P.teamRuntime.getTeamName();let n=[...P.tools,...C.extraTools??[]],o=P.extensions??z.extensions,a={sessionId:W,providerId:m.providerId,modelId:m.modelId,apiKey:m.apiKey,baseUrl:m.baseUrl,headers:m.headers,knownModels:m.knownModels,providerConfig:m,thinking:C.thinking,reasoningEffort:C.reasoningEffort??m.reasoningEffort,systemPrompt:C.systemPrompt,maxIterations:C.maxIterations,execution:C.execution,prepareTurn:cZ(C),tools:n,hooks:z.hooks,extensions:o,hookErrorMode:C.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:OH,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval?async(N)=>{let X0=z.requestToolApproval,J0=this.sessions.get(W);if(J0)await this.markTurnPending(J0);try{if(!X0)return{approved:!1,reason:"Tool approval callback is not configured."};return await X0(N)}finally{let T0=this.sessions.get(W);if(T0?.status==="pending")await this.markTurnRunning(T0)}}:void 0,telemetry:C.telemetry,onConsecutiveMistakeLimitReached:C.onConsecutiveMistakeLimitReached,completionPolicy:P.completionPolicy,consumePendingUserMessage:()=>{let N=this.pendingPromptsController.consumeSteer(W);return N?r8(N.prompt,N.mode??C.mode):void 0},logger:P.logger??C.logger,extensionContext:C.extensionContext,onEvent:(N)=>this.eventBridge.dispatchAgentEvent(W,C,N)};a.hooks={...a.hooks,onEvent:async(N)=>{if(await z.hooks?.onEvent?.(N),N.type!=="assistant-message")return;let X0=this.sessions.get(W);if(!X0)return;let J0=X0.agent.getMessages();try{await this.invoke("persistSessionMessages",W,J0,C.systemPrompt)}catch(T0){C.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:W,error:T0}),g$(C.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:T0,severity:"warn",handled:!0,context:{sessionId:W,providerId:C.providerId,modelId:C.modelId}})}}};let l0=this.createAgentInstance(a);if(a.onEvent)l0.subscribeEvents(a.onEvent);P.registerLeadAgent?.(l0);let f$=L1({agentId:l0.getAgentId(),conversationId:l0.getConversationId(),teamId:P.teamRuntime?.getTeamId(),teamName:P.teamRuntime?.getTeamName(),teamRole:P.teamRuntime?"lead":void 0});if(mV(C,W,Z.length>0,A,f$),f$)V$(C.telemetry,{ulid:W,modelId:C.modelId,provider:C.providerId,...f$});if(P.teamRuntime)M5(C.telemetry,{ulid:W,teamId:P.teamRuntime.getTeamId(),teamName:P.teamRuntime.getTeamName(),leadAgentId:l0.getAgentId(),restoredFromPersistence:P.teamRestoredFromPersistence===!0});let p={sessionId:W,config:C,sessionMetadata:j.sessionMetadata,...G?{artifacts:G}:{},source:J,startedAt:G?.manifest.started_at??Q,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??Q,pendingPrompt:K.prompt,runtime:P,agent:l0,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:f,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(W,p),this.emitStatus(W,"running"),f.length>0&&!G){if(await this.ensureSessionPersisted(p),await this.invoke("persistSessionMessages",p.sessionId,f,p.config.systemPrompt),!j.prompt?.trim())await this.updateStatus(p,"completed",0)}let W1;try{if(j.prompt?.trim())if(W1=await this.executeTurn(p,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!p.interactive)await this.finalizeSingleRun(p,W1.finishReason);else await this.completeInteractiveTurn(p,W1.finishReason)}catch(N){if(p.interactive&&p.aborting)W1=await this.completeAbortedInteractiveTurn(p);else throw g$(p.config.telemetry,{component:"core",operation:"session.start",error:N,severity:"error",handled:!1,context:{sessionId:p.sessionId,providerId:p.config.providerId,modelId:p.config.modelId}}),await this.failSession(p),N}return{sessionId:W,manifest:K,manifestPath:B,messagesPath:H,result:W1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(J)=>this.getSession(J),readMessages:(J)=>this.readSessionMessages(J),buildStartInput:(J,Q)=>{let Z=J.restoredCheckpointMetadata?{...Q.sessionMetadata??{},checkpoint:J.restoredCheckpointMetadata}:Q.sessionMetadata;return{...Q,...Z?{sessionMetadata:Z}:{},initialMessages:J.initialMessages}},startSession:(J)=>this.startSession(J),getStartedSessionId:(J)=>J.sessionId,readRestoredSession:(J)=>this.getSession(J)})}async runTurn($){let J=this.getSessionOrThrow($.sessionId),Q=J.agent.canStartRun(),Z=$.delivery??(J.interactive&&!Q?"queue":void 0);if(J.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Z??"immediate"}}),Z==="queue"||Z==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Z,userImages:$.userImages,userFiles:$.userFiles});return}try{let W=await this.executeTurn(J,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!J.interactive)await this.finalizeSingleRun(J,W.finishReason);else await this.completeInteractiveTurn(J,W.finishReason);if(W.finishReason==="error"||W.finishReason==="aborted")return W;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),W}catch(W){if(J.interactive&&J.aborting)return await this.completeAbortedInteractiveTurn(J);throw g$(J.config.telemetry,{component:"core",operation:"session.submit",error:W,severity:"error",handled:!1,context:{sessionId:J.sessionId,providerId:J.config.providerId,modelId:J.config.modelId}}),await this.failSession(J),W}}async getAccumulatedUsage($){let J=s9(this.usageBySession.get($)),Q=s9(this.aggregateUsageBySession.get($));return J||Q?{usage:J,aggregateUsage:Q}:void 0}async abort($,J){let Q=this.sessions.get($);if(!Q)return;Q.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Q.aborting=!0,this.pendingPromptsController.clearAborted(Q),Q.agent.abort(J)}async stopSession($){let J=this.sessions.get($);if(!J)return;if(J.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),J.interactive&&!Z0(J.status)){await this.releaseSessionRuntime(J,"session_stop");return}if(J.interactive&&J.agent.canStartRun()){await this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:"session_stop",endReason:"stopped"});return}J.aborting=!0,J.agent.abort(Error("session_stop")),await this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let J=[...this.sessions.values()];if(J.length===0)return;await Promise.allSettled(J.map((Q)=>Q.interactive&&!Z0(Q.status)?this.releaseSessionRuntime(Q,$):Q.interactive&&Q.agent.canStartRun()?this.shutdownSession(Q,{status:this.resolveInteractiveStopStatus(Q),exitCode:this.resolveInteractiveStopExitCode(Q),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Q,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let J=this.sessions.get($);if(J)return G7(J);let Q=$.trim();if(!Q)return;let Z=await this.getRow(Q);if(Z)return E8(Z);let W=await this.readManifest(Q);return W?e9(W):void 0}async listSessions($=200){let Q=(await this.listRows($)).map(E8),Z=new Set(Q.map((W)=>W.sessionId));for(let W of this.sessions.values()){if(Z.has(W.sessionId))continue;Q.unshift(G7(W))}return Q.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let J=await this.invoke("deleteSession",$);if(J.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return J.deleted}async updateSession($,J){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:J.prompt,metadata:J.metadata,title:J.title}))?.updated===!0}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.getRow(J);if(Q?.messagesPath)return d1(Q.messagesPath);let Z=await this.readManifest(J);return d1(Z?.messages_path)}async dispatchHookEvent($){await vX($,{queueSpawnRequest:(J)=>this.invokeOptional("queueSpawnRequest",J),upsertSubagentSessionFromHook:(J)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",J),appendSubagentHookAudit:(J,Q)=>this.invokeOptional("appendSubagentHookAudit",J,Q),applySubagentStatus:(J,Q)=>this.invokeOptional("applySubagentStatus",J,Q)})}subscribe($,J){return this.events.subscribe($,J)}async updateSessionModel($,J){let Q=this.getSessionOrThrow($);Q.config.modelId=J,Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:J}),Q.agent.updateConnection({modelId:J})}handlePluginEvent($,J,Q){return this.eventBridge.handlePluginEvent($,J,Q)}async executeTurn($,J){let Q=await this.prepareTurnInput($,J),Z=Q.prompt.trim();if(!Z)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Z;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let W=await this.executeAgentTurn($,Z,Q.userImages,Q.userFiles);while(PZ($,W.finishReason)){let j=await NZ($);if(j.length===0)break;let f=wZ($,j);W=await this.executeAgentTurn($,f)}return W}async completeInteractiveTurn($,J){if(p8($))return;$.lastInteractiveTurnFinishReason=J,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let J=$.lastInteractiveTurnFinishReason;if(!J)return"cancelled";switch(J){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return J}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let J=new Date,Q=$.agent.getMessages(),Z=U0();return $.persistedMessages=Q,$.started=$.started||Q.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Z}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Z,messages:Q,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:J,endedAt:J,durationMs:0}}async executeAgentTurn($,J,Q,Z){let W=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),f=this.usageBySession.get($.sessionId)??U0(),X=this.aggregateUsageBySession.get($.sessionId)??f;$.turnUsageBaseline=f,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=U0(),$.turnUsageByAgent=new Map,U5($.config.telemetry,$.sessionId,$.config.mode),g2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let Y=W?()=>$.agent.continue(J,Q,Z):()=>$.agent.run(J,Q,Z),V=await this.runWithAuthRetry($,Y,j);$.started=!0;let H=r6(V.messages,V,j);$.persistedMessages=H;let B=KJ($.turnUsageByAgent?.values()??[]),A=K0(f,V.usage),K=K0(K0(U0(),V.usage),B),G=K0(X,K);return this.usageBySession.set($.sessionId,A),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:A.totalCost,aggregatedAgentsCost:G.totalCost,usage:A,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,V),V}catch(Y){throw g$($.config.telemetry,{component:"core",operation:"session.turn",error:Y,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),Y}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,J){if($.submitAndExitObserved)return;if(!J.toolCalls.some((Z)=>Z.name===D0.SUBMIT_AND_EXIT&&Z.error===void 0))return;$.submitAndExitObserved=!0,U4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,J){let Q=e1($.config),Z=LN(J.prompt).trim();if(!Z)return{prompt:"",userImages:J.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles)};let W=await R6(Z,Q);vV($.config.telemetry,W);let j=r8(W.prompt,J.mode??$.config.mode),f=this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles),X=this.resolveAbsoluteFilePaths(Q,W.matchedFiles),Y=Array.from(new Set([...f,...X]));return{prompt:j,userImages:J.userImages,userFiles:Y.length>0?Y:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let J=e1($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:J,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,J){let Q=this.sessions.get($),Z=await this.invokeOptionalValue("readSessionManifest",$)??Q?.artifacts?.manifest,W=J(Z?.metadata);if(!Q?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:W}))?.updated===!1)return;Q.sessionMetadata=W,Q.artifacts.manifest.metadata=W}async finalizeSingleRun($,J){if(p8($))return;let Q=J==="aborted"||$.aborting,Z=J==="error";await this.shutdownSession($,{status:Q?"cancelled":Z?"failed":"completed",exitCode:Z?1:0,shutdownReason:Z?"session_error":"session_complete",endReason:J})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,J){if(J.status==="completed"&&!$.submitAndExitObserved)U4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});HJ($);let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),g$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,status:J.status,shutdownReason:J.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,J.status,J.exitCode)}catch(W){Z("update_status",W)}try{await $.agent.shutdown(J.shutdownReason)}catch(W){Z("agent_shutdown",W)}}try{await Promise.resolve($.runtime.shutdown(J.shutdownReason))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:J.endReason,ts:Date.now()}}),Q.length>0&&J.status==="failed")throw Q[0]}async releaseSessionRuntime($,J){let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),g$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,reason:J,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(J)}catch(W){Z("agent_shutdown",W)}try{await Promise.resolve($.runtime.shutdown(J))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),Q.length>0)throw Q[0]}async updateStatus($,J,Q){if(!$.artifacts)return;let Z=await this.invoke("updateSessionStatus",$.sessionId,J,Q);if(!Z.updated)return;let W=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(W.status=J,Z0(J))delete W.ended_at,W.exit_code=null;else W.ended_at=Z.endedAt??s(),W.exit_code=typeof Q==="number"?Q:null;$.artifacts.manifest=W,$.status=J,$.updatedAt=Z.endedAt??s(),$.endedAt=Z0(J)?null:W.ended_at,$.exitCode=W.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,W),this.emitStatus($.sessionId,J)}async runWithAuthRetry($,J,Q){try{return await J()}catch(Z){if(!v2($.config.providerId)||!zN(Z))throw Z;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Q),J()}}async syncOAuthCredentials($,J){let Q=null;try{Q=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:J?.forceRefresh})}catch(Z){if(Z instanceof bJ)throw Error(`${Z.providerId} requires re-authentication.`);throw Z}if(!Q?.apiKey||$.config.apiKey===Q.apiKey)return;$.config.apiKey=Q.apiKey,$.agent.updateConnection({apiKey:Q.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Q.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Q.apiKey})}getSessionOrThrow($){let J=this.sessions.get($);if(!J){let Q=new _$($);throw g$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Q,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Q}return J}resolveAbsoluteFilePaths($,J){if(!J||J.length===0)return[];let Q=J.map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>UN(Z)?Z:z7($,Z));return Array.from(new Set(Q))}getSessionAgentTelemetryIdentity($){return L1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let J=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Q=K0($.initialUsage,J);return this.withPersistedAggregateUsageFloor(Q,$.manifest)}async summarizePersistedTeammateUsage($,J,Q){let Z=z7(J),W=`${Q}.messages.json`,j;try{j=FN($)}catch{return U0()}let f=U0();for(let X of j){if(!X.endsWith(".messages.json"))continue;if(X===W)continue;let Y=z7($,X);if(Y===Z)continue;let V=await d1(Y);if(V.length===0)continue;f=K0(f,GJ(V))}return f}withPersistedAggregateUsageFloor($,J){let Q=ON(J.metadata?.aggregateUsage);if(Q)return TN($,Q);let Z=J.metadata?.aggregatedAgentsCost;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=$.totalCost)return $;return{...$,totalCost:Z}}emitStatus($,J){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:J}})}async emitSessionSnapshot($){let J=await this.getSession($);if(!J)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:i1({session:J,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),TH))}async getRow($){let J=$.trim();if(!J)return;return(await this.listRows(TH)).find((Z)=>Z.sessionId===J)}async readManifest($){let J=$.trim();if(!J)return;return await this.invokeOptionalValue("readSessionManifest",J)}invoke($,...J){return zH(this.sessionService,$,...J)}invokeOptional($,...J){return LH(this.sessionService,$,...J)}invokeOptionalValue($,...J){return _H(this.sessionService,$,...J)}}function MN($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let J=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(J==="local"||J==="hub"||J==="remote")return J;return"auto"}var Z4,W4;function qN($,J){if($!=="auto"&&$!=="hub")return;if(J.hub?.endpoint?.trim())return;VY(J.hub?.workspaceRoot?.trim()||J.hub?.cwd?.trim()||process.cwd())}async function PN($){await $.reconcileDeadSessions?.().catch(()=>{})}function PH($){try{let J=new s1;return J.init(),new o1(J,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(J){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),qH($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:J,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new EZ(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function MH($,J,Q){return new Z$({sessionService:Q??$.sessionService??PH($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:J,fetch:$.fetch})}async function NN($){if(Z4)return Z4;if(W4)return await W4;return W4=(async()=>{return Z4=PH($),await PN(Z4),Z4})().finally(()=>{W4=void 0}),await W4}async function kJ($){let J=g0($.distinctId);$.telemetry?.setDistinctId(J);let Q=MN($);if(qN(Q,$),Q==="remote"){let Z=$.remote?.endpoint?.trim();if(!Z)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Z}),new $J({endpoint:Z,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Q==="hub"){let Z=$.hub?.endpoint?.trim(),W=Z||await m8({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!W)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:W,explicitEndpoint:Z||void 0}),new b$({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Q==="auto"){let Z=await VZ({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Z){$.logger?.log("Using discovered local hub runtime host",{url:Z});let W=new b$({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await W.connect(),W}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),qH($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),MH($,J)}return MH($,J)}import{existsSync as wN,mkdirSync as SN,readFileSync as CN,writeFileSync as yN}from"node:fs";import{dirname as EN}from"node:path";import{FEATURE_FLAGS as NH,FeatureFlagDefaultValue as L7}from"@cline/shared";var bN=3600000,hN=604800000,wH=1;class j4{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??bN,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??hN,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let J=$??this.context.userId??null,Q=Date.now();if(Q-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===J)return}let Z=this.cacheInfo;this.cacheInfo={updateTime:Q,userId:J||null};try{let W=await this.provider.getAllFlagsAndPayloads({flagKeys:NH.length>0?NH:void 0,context:{...this.context,userId:J}});if(this.cacheInfo.userId!==J)return;this.cacheInfo.flagsPayload=W,this.rebuildCacheFromSnapshot(W),this.writePersistentCache()}catch(W){if(this.cacheInfo.userId!==J)return;throw this.cacheInfo=Z.updateTime?Z:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:W}),W}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((J)=>this.isFeatureFlagPayload(J));if(typeof $==="object")return Object.values($).every((J)=>this.isFeatureFlagPayload(J));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=Object.entries($).filter(([,Z])=>this.isFeatureFlagPayload(Z));if(J.length===0)return;let Q={};for(let[Z,W]of J)Q[Z]=W;return Q}readPersistentCache(){try{if(!this.cacheFilePath||!wN(this.cacheFilePath))return;let $=JSON.parse(CN(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let J=$;if(J.version!==wH||typeof J.updatedAt!=="number"||!Number.isFinite(J.updatedAt)||Date.now()-J.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:J.updatedAt,userId:J.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(J.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(J.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;SN(EN(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),J={version:wH,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};yN(this.cacheFilePath,`${JSON.stringify(J,null,2)}
704
- `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let J=new Map;for(let Q of this.getReturnedFlagKeys($)){let Z=this.getFeatureFlag(Q);J.set(Q,Z??!1)}this.cache=J}getFeatureFlag($){try{let J=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Q=this.cacheInfo.flagsPayload?.featureFlags?.[$],Z=J??Q??L7[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Z)this.telemetry?.capture({event:k.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Q}});return Z}catch(J){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:J}),L7[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??L7[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,J){if(process.env.IS_TEST==="true")this.cache.set($,J)}async dispose(){await this.provider.dispose()}}class f4{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}q2();class _7{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,J,Q,Z,W,j,f,X,Y,V){this.clientName=J,this.runtimeAddress=Q,this.host=$,this.prepare=Z,this.capabilities=W,this.logger=j,this.telemetry=f,this.distinctId=X,this.featureFlags=Y,this.settings=YX($),this.pendingPrompts=VX($),this.automation=new JQ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=V?new S8({workspaceRoot:V.workspaceRoot??process.cwd(),specs:{cronSpecsDir:V.cronSpecsDir??V.cronDir,scope:j3(V.cronScope),workspaceRoot:V.workspaceRoot},runtimeHandlers:f3({host:$,getExtensionContext:()=>I4({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:V.dbPath,logger:V.logger,pollIntervalMs:V.pollIntervalMs,claimLeaseSeconds:V.claimLeaseSeconds,globalMaxConcurrency:V.globalMaxConcurrency,watcherDebounceMs:V.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let J=g0($.distinctId),Q=L0($.capabilities),Z={...$,capabilities:Q,distinctId:J},W=await kJ(Z),j=W3($.automation),f=$.featureFlags||new j4({provider:new f4,telemetry:$.telemetry,logger:$.logger,context:{distinctId:J,clientName:$.clientName}}),X=new _7(W,$.clientName,W.runtimeAddress,$.prepare,Q,$.logger,$.telemetry,J,f,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await X.automation.start();return X}async disposeSessionBootstrap($){let J=this.activeSessionBootstraps.get($);if(!J)return;this.activeSessionBootstraps.delete($),await Promise.resolve(J.dispose?.())}async start($){let J=HX($),Q=await this.prepare?.(J);try{let Z=Q?await Q.applyToStartSessionInput(J):J,W=await this.host.startSession(O9(Z,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>I4({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Q)if(await this.host.getSession(W.sessionId))this.activeSessionBootstraps.set(W.sessionId,Q);else await Promise.resolve(Q.dispose?.());return BX({input:Z,sessionId:W.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),W}catch(Z){throw await Promise.resolve(Q?.dispose?.()),Z}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let J=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(J.map((Q)=>this.disposeSessionBootstrap(Q)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await $Z(this.host,$);list=async($=200,J={})=>await this.listHistory({...J,limit:$});delete=async($)=>{let J=await this.host.deleteSession($);if(J)await this.disposeSessionBootstrap($);return J};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let J=$.start?O9($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>I4({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:J})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,J){return this.host.subscribe($,J)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}import{HookEventNameSchema as CH,HookEventPayloadSchema as yH,parseHookEventPayload as xJ,resolveHookSessionContext as cN}from"@cline/shared";import{z as m$}from"zod";import{spawn as kN}from"node:child_process";import{augmentNodeCommandForDebug as IN,withResolvedClineBuildEnv as xN}from"@cline/shared";function gN($){let J=$.trim();if(!J)return{};let Z=J.split(`
705
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function mN($,J){let Q=$ instanceof Error?$:Error(String($)),Z=Q,W=J.join(" ");if(Z.code==="EACCES")return Error(`Failed to execute hook command "${W}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${W}": ${Q.message}`)}async function vN($,J){let Q=$.stdin;if(!Q)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Z,W)=>{let j=(f)=>{Q.off("error",j);let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f)};Q.once("error",j),Q.end(J,(f)=>{if(Q.off("error",j),f){let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f);return}Z()})})}async function IJ($,J){let Q=IN(J.command,{env:J.env,debugRole:"hook"});if(!Array.isArray(Q)||Q.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Z=!!J.detached,W=kN(Q[0],Q.slice(1),{cwd:J.cwd,env:xN(J.env),stdio:Z?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Z,windowsHide:!0}),j=new Promise((A)=>{W.once("spawn",()=>{try{J.onSpawn?.({command:Q,pid:W.pid??void 0,detached:Z})}catch{}A()})}),f=new Promise((A,K)=>{W.once("error",(G)=>{K(mN(G,Q))})});if(await vN(W,JSON.stringify($)),Z){await Promise.race([j,f]),W.unref();return}if(!W.stdout||!W.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",Y="",V=!1,H;W.stdout.on("data",(A)=>{X+=A.toString()}),W.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,W.kill("SIGKILL")},J.timeoutMs);W.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=gN(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,f])}var uN=m$.object({contextModification:m$.string().optional(),cancel:m$.boolean().optional(),review:m$.boolean().optional(),errorMessage:m$.string().optional(),context:m$.string().optional(),overrideInput:m$.unknown().optional()}).passthrough();var dN=["agent","hook"];async function gJ($,J={}){let Q=J.command??dN;return await IJ($,{command:Q,cwd:J.cwd,env:J.env,detached:J.detached,timeoutMs:J.timeoutMs,onSpawn:J.onSpawn})}function EH($){return $ instanceof Error?$:Error(String($))}function lN($){if(!$||typeof $!=="object")return;let J=uN.safeParse($);if(!J.success)return;let Q=J.data;if(!(("cancel"in Q)||("review"in Q)||("context"in Q)||("contextModification"in Q)||("overrideInput"in Q)||("errorMessage"in Q)))return;let W=typeof Q.context==="string"?Q.context:typeof Q.contextModification==="string"?Q.contextModification:typeof Q.errorMessage==="string"&&Q.errorMessage.length>0?Q.errorMessage:void 0;return{cancel:typeof Q.cancel==="boolean"?Q.cancel:void 0,review:typeof Q.review==="boolean"?Q.review:void 0,context:W,overrideInput:Object.hasOwn(Q,"overrideInput")?Q.overrideInput:void 0}}function SH($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))if(typeof Z==="string")J[Q]=Z;else J[Q]=JSON.stringify(Z);return J}function _1($,J,Q){let Z=Q.env??process.env,W=Z.CLINE_USER_ID?.trim()||Z.USER?.trim()||"unknown",j=Q.cwd||process.cwd();return{clineVersion:Z.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:J.conversationId,sessionContext:cN(Q.sessionContext,{hookName:$,conversationId:J.conversationId,agentId:J.agentId,parentAgentId:J.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Q.workspaceInfo,userId:W,agent_id:J.agentId,parent_agent_id:J.parentAgentId}}function pN($){return{name:$.name,message:$.message,stack:$.stack}}function rN($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function iN($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function nN($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function aN($){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 sN($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}async function v$($,J){try{let Q=await gJ($,{command:J.command,cwd:J.cwd,env:J.env,detached:!0,onSpawn:J.onSpawn});J.onDispatch?.({payload:$,result:Q,detached:!0})}catch(Q){J.onDispatchError?.(EH(Q),$)}}function bH($={}){return{hooks:{beforeRun:async(X)=>{let Y=iN(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={..._1("agent_resume",Y,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await v$(H,$)}else{let H={..._1("agent_start",Y,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await v$(H,$)}return},beforeTool:async(X)=>{let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={..._1("tool_call",Y,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:SH(X.input)}};try{let H=await gJ(V,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:V,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return sN(lN(H?.parsedJson))}catch(H){$.onDispatchError?.(EH(H),V);return}},afterTool:async(X)=>{let Y=aN(X),V={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},H={..._1("tool_result",V,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:Y,postToolUse:{toolName:Y.name,parameters:SH(Y.input),result:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output),success:!Y.error,executionTimeMs:Y.durationMs}};await v$(H,$);return},afterRun:async({snapshot:X,result:Y})=>{let V={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(Y.status==="completed"){let A={..._1("agent_end",V,$),hookName:"agent_end",iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status},taskComplete:{taskMetadata:{}}};await v$(A,$);return}let H=Y.status==="aborted"||rN(Y.error?.message)?"agent_abort":"agent_error",B=H==="agent_error"?{..._1(H,V,$),hookName:H,iteration:Y.iterations,error:pN(Y.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{..._1(H,V,$),hookName:H,reason:Y.error?.message,taskCancel:{taskMetadata:{}}};await v$(B,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={..._1("prompt_submit",Y,$),hookName:"prompt_submit",userPromptSubmit:{prompt:nN(X.message.content),attachments:[]}};await v$(V,$)}},shutdown:async({agentId:X,conversationId:Y,parentAgentId:V,reason:H})=>{let B={..._1("session_shutdown",{agentId:X,conversationId:Y,parentAgentId:V},$),hookName:"session_shutdown",reason:H};await v$(B,$)}}}import{createSessionId as oN}from"@cline/shared";function v0($,J){return{version:$.version,requestId:$.requestId,ok:!0,payload:J}}function hH($,J,Q){return{version:$.version,requestId:$.requestId??oN("hubreq_"),ok:!1,error:{code:J,message:Q}}}class mJ{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return v0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return v0($,{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 v0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return v0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return v0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return v0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return v0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return v0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return v0($,{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 v0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return v0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return v0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return hH($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(J){return hH($,"schedule_command_failed",J instanceof Error?J.message:String(J))}}toCreateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:J}}toUpdateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:J}}}function cJ($){return $?new Date($).getTime():void 0}function tN($){let J=$.metadata?{...$.metadata}:void 0;if(J)delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions;return J}function vJ($){let J=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof J?.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:cJ($.nextRunAt),lastRunAt:cJ($.lastRunAt),createdBy:typeof J?.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:J?.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0,metadata:tN($)}}function eN($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function O7($,J){return{executionId:$.runId,scheduleId:J,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:cJ($.startedAt),endedAt:cJ($.completedAt),status:eN($.status),errorMessage:$.error}}class uJ{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new w8({dbPath:$.dbPath}),this.materializer=new T8({store:this.store}),this.runner=new M8({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(b9($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return vJ(this.store.createHubSchedule($))}getSchedule($){let J=this.store.getHubSchedule($);return J?vJ(J):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((J)=>vJ(J))}updateSchedule($,J){if(J.cronPattern!==void 0)b9(J.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let Z=J.workspaceRoot!==void 0?J.workspaceRoot.trim():Q.workspaceRoot;if((J.enabled??Q.enabled)&&!Z)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...J,scheduleId:$});return j?vJ(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;await this.runner.tick();let Q=this.store.getRun(J.runId)??J;return O7(Q,$)}triggerScheduleNowDetached($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;return this.runner.tick().catch(()=>{return}),O7(J,$)}listScheduleExecutions($){let J=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:J?.specId,limit:$.limit};return this.store.listRuns(Q).map((W)=>{let j=J??this.store.getSpec(W.specId);if(!j||j.source!=="hub-schedule")return;return O7(W,j.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let J=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(J.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,Z=0,W=0,j;for(let f of J){if(f.status==="success"||f.status==="completed")Q+=1;if(!j&&f.status!=="success"&&f.status!=="completed")j=f;if(f.startedAt&&f.endedAt)W+=f.endedAt-f.startedAt,Z+=1}return{totalRuns:J.length,successRate:Q/J.length,avgDurationSeconds:Z>0?W/Z/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let J=this.store.getSpec($.specId);if(!J||J.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:J.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:J.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+J.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let J={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(J).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,Z)=>String(Q.nextRunAt).localeCompare(String(Z.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:Z})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:Z}))}}rJ();import{resolveClineBuildEnv as Ow}from"@cline/shared";function Tw($,J){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${J} (${Q} event before socket open).`:`Failed to connect to hub at ${J}.`)}var Mw="cline-hub-auth.";function qw($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function Pw($,J){let Q=new URL($),Z=new URL(J);return Q.search="",Q.hash="",Z.search="",Z.hash="",Q.toString()===Z.toString()}function xH(){return Ow()==="production"?p1():D1()}async function Nw($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=xH(),Z=await A0(Q.discoveryPath);if(Z?.url&&Pw($.toString(),Z.url))return Z.authToken;return}async function ww($={}){let J=l1($);if(!qw($)){let Q=xH(),Z=await A0(Q.discoveryPath);if(Z?.url)return Z.url}return F1(J.host,J.port,J.pathname)}async function gH($){return await new Promise((J,Q)=>{(async()=>{let Z=new URL($),W=await Nw(Z);Z.hash="";let j=new WebSocket(Z.toString(),W?[`${Mw}${W}`]:void 0),f=new Map,X=0;j.addEventListener("open",()=>{J({send(Y){let V=Y.requestId??`hub-client-${++X}`;return new Promise((H,B)=>{f.set(V,{resolve:H,reject:B});let A={kind:"command",envelope:{...Y,requestId:V}};j.send(JSON.stringify(A))})},close(){j.close()}})}),j.addEventListener("message",(Y)=>{let V=JSON.parse(String(Y.data));if(V.kind==="reply"&&V.envelope.requestId){let H=f.get(V.envelope.requestId);if(H)f.delete(V.envelope.requestId),H.resolve(V.envelope)}}),j.addEventListener("close",()=>{for(let Y of f.values())Y.reject(Error("Hub connection closed"));f.clear()}),j.addEventListener("error",(Y)=>{Q(Tw(Y,$))})})().catch(Q)})}async function rp($){try{return(await gH($)).close(),!0}catch{return!1}}async function ip($,J){let Q=await ww($),Z=await gH(Q);try{return await Z.send({version:J.version??"v1",clientId:J.clientId??"hub-client",...J})}finally{Z.close()}}function P7($){return $?JSON.parse(JSON.stringify($)):{}}function iJ($){let J=$?.session&&typeof $.session==="object"?$.session:void 0;if(!J)return;let Q=J.metadata&&typeof J.metadata==="object"?P7(J.metadata):void 0;return{sessionId:typeof J.sessionId==="string"?J.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function mH($,J){return $.error?.message??`hub command failed: ${J}`}function Sw($){let J=P7($);if(typeof J.error==="string"&&J.error.trim())return{...J,error:J.error.trim()};let Q=J.result&&typeof J.result==="object"?J.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...J,error:Q.text.trim()};let Z=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof Z?.message==="string"&&Z.message.trim())return{...J,error:Z.message.trim()};return J}function vH($){let J=$?.sessionId;return typeof J==="string"&&J.trim()?J.trim():void 0}function Cw($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))throw Error("hub checkpoint restore returned no checkpoint");let Q=J;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function yw($){let J=P7($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||vH(J)||"",eventType:"schedule.execution.completed",payload:J};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||vH(J)||"",eventType:"schedule.execution.failed",payload:J};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:J};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:J};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:J};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:J};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:J};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:J};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:J};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:J};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:Sw($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:J};default:return}}class Ew{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new U1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let J=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Q=iJ(J.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,J,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:J.prompt,mode:J.config.mode,attachments:J.attachments,delivery:J.delivery,timeoutSeconds:J.config.timeoutSeconds},$,Q)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(O$(Q))return;throw Q}return iJ(J.payload)}async readMessages($){let J=$.trim();if(!J)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw Error(mH(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async restore($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Z=$.config,W=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,sessionConfig:{providerId:Z.provider,modelId:Z.model,apiKey:Z.apiKey,cwd:Z.cwd??Z.workspaceRoot,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Z.mode??"act",rules:Z.rules,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},metadata:{source:Z.source??"cli",provider:Z.provider,model:Z.model,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,prompt:void 0,interactive:Z.interactive!==!1},runtimeOptions:{mode:Z.mode,systemPrompt:Z.systemPrompt,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,autoApproveTools:Z.autoApproveTools,configExtensions:Z.configExtensions},modelSelection:{provider:Z.provider,model:Z.model,apiKey:Z.apiKey},toolPolicies:Z.toolPolicies}:{}},J);if(!W.ok)throw Error(mH(W,"session.restore"));let j=iJ(W.payload);if(Q&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let f=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,X=Cw(W.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...f?{messages:f}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let J=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(J.payload?.sessions)?J.payload?.sessions:[]).map((Z)=>iJ({session:Z})).filter((Z)=>Boolean(Z?.sessionId))}async deleteSession($,J=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:J})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,J){let Q=new Set(($.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),Z=this.client.subscribe((W)=>{let j=yw(W);if(!j)return;if(Q.size>0&&!Q.has(j.sessionId))return;J.onEvent?.(j)});return this.ensureMetadataApplied().catch((W)=>{J.onError?.(W instanceof Error?W:Error(String(W)))}),Z}streamTeamProgress($,J){let Q=this.client.subscribe((Z)=>{if(Z.event!=="team.progress"||!Z.payload)return;J.onProjection?.(Z.payload)});return this.ensureMetadataApplied().catch((Z)=>{J.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list");return Array.isArray(J.payload?.schedules)?J.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,J){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...J})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,J){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:J});return Array.isArray(Q.payload?.executions)?Q.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(J.payload?.upcoming)?J.payload?.upcoming:[]}}class bw{client;constructor($){this.client=new U1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let J=await this.client.command("session.list",{limit:$});return Array.isArray(J.payload?.sessions)?J.payload.sessions:[]}subscribeUI($){return this.client.subscribe((J)=>{switch(J.event){case"ui.notify":$.onNotify?.(J.payload);break;case"ui.show_window":$.onShowWindow?.(J.payload);break;case"hub.client.registered":$.onClientRegistered?.(J.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(J.payload??{});break;case"session.created":$.onSessionCreated?.(J.payload??{});break;case"session.updated":$.onSessionUpdated?.(J.payload??{});break;case"session.detached":$.onSessionDetached?.(J.payload??{});break}})}}import{normalizeProviderId as hw}from"@cline/llms";function kw($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function Iw($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function jr($={}){let J=new Z$({sessionService:new o1(new s1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||z0.CLI,interactive:!1,config:{providerId:hw(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Iw(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content)});if(!W)throw Error("local hub schedule runtime returned no turn result");return{result:kw(W)}},async abortSession(Q){return await J.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}import{resolveClineBuildEnv as kB}from"@cline/shared";function xw($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Q)=>{if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text.trim();return""}).filter(Boolean).join(`
706
- `).trim()||void 0}var cH=120,N7="...";function w7($){let J=$.trim();if(!J)return"";if(Buffer.byteLength(J,"utf8")<=cH)return J;let Q=cH-Buffer.byteLength(N7,"utf8");if(Q<=0)return N7;let Z="";for(let W of J){if(Buffer.byteLength(Z+W,"utf8")>Q)break;Z+=W}return`${Z}${N7}`}async function uH($){let J=$?.sessionId?.trim()||"unknown",Q=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,W=[...await d1(Q)].reverse().find((Y)=>Y.role==="assistant"),j=W?xw(W.content):void 0,f=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():f;return{title:`Task completed (${J})`,body:w7(j&&j.length>0?j:X.length>0?X:f),severity:"info"}}import{captureSdkError as oJ,createSessionId as AS}from"@cline/shared";import{createSessionId as cw}from"@cline/shared";import{createSessionId as vw}from"@cline/shared";function gw($){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 mw($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())J.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())J.parentAgentId=$.parentAgentId;if($.agentId?.trim())J.agentId=$.agentId;if($.conversationId?.trim())J.conversationId=$.conversationId;if($.messagesPath?.trim())J.messagesPath=$.messagesPath;if($.prompt?.trim())J.prompt=$.prompt;if($.provider?.trim())J.provider=$.provider;if($.model?.trim())J.model=$.model;if($.source?.trim())J.source=$.source;if(typeof $.pid==="number")J.pid=$.pid;return Object.keys(J).length>0?J:void 0}function nJ($,J,Q,Z){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:J?.createdByClientId??"hub",status:gw($.status),participants:J?[...J.participants.values()]:[],metadata:mw($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Q?{usage:{...Q}}:{},...Z?{aggregateUsage:{...Z}}:{}}}function c($,J){return{version:$.version,requestId:$.requestId,ok:!0,...J!==void 0?{payload:J}:{}}}function x($,J,Q){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:J,message:Q}}}function aJ($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function w0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function u$($,J,Q){return{version:"v1",event:$,eventId:vw("hevt_"),sessionId:Q,timestamp:Date.now(),payload:J}}async function c0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let Z=await $.sessionHost.getAccumulatedUsage?.(J);return nJ(Q,$.sessionState.get(J),Z?.usage,Z?.aggregateUsage)}async function u0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let[Z,W]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(J):[],$.sessionHost.getAccumulatedUsage?.(J)]);return i1({session:Q,messages:Z,usage:W?.usage,aggregateUsage:W?.aggregateUsage})}function sJ($,J,Q,Z,W={}){let j=$.sessionState.get(J);if(j){if(W.interactive!==void 0)j.interactive=W.interactive;if(!j.participants.has(Q))j.participants.set(Q,{clientId:Q,attachedAt:Date.now(),role:Z});return j}let f={createdByClientId:Q,interactive:W.interactive??!0,participants:new Map([[Q,{clientId:Q,attachedAt:Date.now(),role:Z}]])};return $.sessionState.set(J,f),f}async function S7($,J){let Q=cw("approval_"),Z=J.sessionId;if($.sessionState.get(Z)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Q,{sessionId:Z,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Q,sessionId:J.sessionId,agentId:J.agentId,conversationId:J.conversationId,iteration:J.iteration,toolCallId:J.toolCallId,toolName:J.toolName,inputJson:JSON.stringify(J.input??null),policy:J.policy},Z))})}function C7($,J,Q){let Z=$.pendingApprovals.get(J);if(!Z)return;return $.pendingApprovals.delete(J),Z.resolve(Q),{sessionId:Z.sessionId}}function y7($,J,Q){let Z=0;for(let[W,j]of[...$.pendingApprovals.entries()]){if(!J({approvalId:W,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(W),j.resolve({approved:!1,reason:Q}),$.publish($.buildEvent("approval.resolved",{approvalId:W,approved:!1,cancelled:!0,reason:Q},j.sessionId)),Z+=1}return Z}async function dH($,J){let Q=typeof J.payload?.approvalId==="string"?J.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Q))return x(J,"approval_not_found",`Unknown approval: ${Q}`);let W=typeof J.payload?.reason==="string"?J.payload.reason:J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)&&typeof J.payload.payload.reason==="string"?J.payload.payload.reason:void 0,j=J.payload?.approved===!0,f=C7($,Q,{approved:j,reason:W});if(!f)return x(J,"approval_not_found",`Unknown approval: ${Q}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Q,approved:j,reason:W},f.sessionId)),c(J,{approvalId:Q,approved:j})}import{createSessionId as lw}from"@cline/shared";function uw($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var lH={debug:10,info:20,warn:30,error:40,silent:50};function dw(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function g($,J,Q={}){if(lH[$]<lH[dw()])return;let Z=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:J,...Object.fromEntries(Object.entries(Q).map(([W,j])=>[W,uw(j)]).filter(([,W])=>W!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Z}`);return}console.log(`[hub] ${Z}`)}function E7($,J){let Q=J instanceof Error?J.stack||J.message:String(J);g("error",$,{error:Q})}async function pH($,J,Q,Z,W,j){let f=lw("capreq_"),X=performance.now();return g("info","capability.request.start",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W}),await new Promise((Y,V)=>{$.pendingCapabilityRequests.set(f,{sessionId:J,targetClientId:W,capabilityName:Q,onProgress:j,resolve:(H)=>{if(g(H.ok?"info":"warn","capability.request.end",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-X)}),!H.ok){V(Error(H.error||`Capability ${Q} was rejected by ${W}.`));return}Y(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:f,targetClientId:W,capabilityName:Q,payload:Z},J)),g("info","capability.request.published",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W})})}function rH($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return x(J,"capability_not_found",`Unknown capability request: ${Q}`);if((J.clientId?.trim()||"")!==Z.targetClientId)return x(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return x(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{};return Z.onProgress?.(j),c(J,{requestId:Q})}function W$($,J,Q){let Z=0;for(let[W,j]of[...$.pendingCapabilityRequests.entries()]){if(!J({requestId:W,...j}))continue;$.pendingCapabilityRequests.delete(W),g("warn","capability.request.cancelled",{requestId:W,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Q}),j.resolve({ok:!1,error:Q}),$.publish($.buildEvent("capability.resolved",{requestId:W,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Q},j.sessionId)),Z+=1}return Z}async function iH($,J){let Q=typeof J.payload?.sessionId==="string"?J.payload.sessionId.trim():J.sessionId?.trim()||"",Z=typeof J.payload?.capabilityName==="string"?J.payload.capabilityName.trim():"",W=typeof J.payload?.targetClientId==="string"?J.payload.targetClientId.trim():"";if(!Q||!Z||!W)return x(J,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{},f=await $.requestCapability(Q,Z,j,W);return c(J,f)}catch(j){return x(J,"capability_request_failed",j instanceof Error?j.message:String(j))}}function nH($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return x(J,"capability_not_found",`Unknown capability request: ${Q}`);let W=J.clientId?.trim()||"";if(W!==Z.targetClientId)return x(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return x(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);$.pendingCapabilityRequests.delete(Q);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:void 0,f=typeof J.payload?.error==="string"?J.payload.error:void 0,X=J.payload?.ok===!0;return g(X?"info":"warn","capability.respond",{requestId:Q,sessionId:Z.sessionId,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,error:f}),Z.resolve({ok:X,payload:j,error:f}),$.publish($.buildEvent("capability.resolved",{requestId:Q,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,payload:j,error:f},Z.sessionId)),c(J,{requestId:Q,ok:X})}import{createSessionId as pw}from"@cline/shared";function aH($,J){let Q=J.payload,Z=Q?.clientId?.trim()||J.clientId?.trim()||pw("client_");return $.clients.set(Z,{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,actorKind:Q?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Q?.transport??"native",capabilities:Q?.capabilities??[],metadata:Q?.metadata,workspaceContext:Q?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,connectedAt:Date.now()})),c(J,{clientId:Z})}function sH($,J){let Q=J.clientId?.trim(),Z=Q?$.clients.get(Q):void 0;if(!Q||!Z)return x(J,"client_not_found","Client is not registered with this hub.");let W=aJ(J.payload?.metadata);if(Z.lastSeenAt=Date.now(),W)Z.metadata=JSON.parse(JSON.stringify(W));return c(J)}function oH($,J,Q){let Z=J.clientId?.trim();if(Z)$.clients.delete(Z),Q(Z),$.publish($.buildEvent("hub.client.disconnected",{clientId:Z}));return c(J)}function tH($,J){return c(J,{clients:[...$.clients.values()]})}var rw=30000;function iw($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function nw($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function aw($,J,Q){let Z=Q instanceof Error&&Q.message.trim()?Q.message:`Unknown session: ${J}`;return x($,_8,Z)}function sw($){return $?$:void 0}function ow($){let J=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J);let Q=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Q&&Number.isFinite(Q)&&Q>0)return Math.floor(Q*1000);return}async function tw($,J,Q,Z){let W=performance.now(),j=!1,f={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q.sessionId,timeoutMs:Z},X=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-W);g("warn","run.heartbeat",{...f,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:J.requestId,elapsedMs:H,...Z?{timeoutMs:Z}:{}},Q.sessionId))},rw),Y=$.sessionHost.runTurn(Q);Y.then((H)=>{if(!j)return;g("warn","run.late_end",{...f,elapsedMs:Math.round(performance.now()-W),finishReason:H?.finishReason})},(H)=>{if(!j)return;g("error","run.late_error",{...f,elapsedMs:Math.round(performance.now()-W),error:H})});let V;try{if(!Z)return await Y;return await Promise.race([Y,new Promise((H,B)=>{V=setTimeout(()=>{let A=`Hub run ${J.command} timed out after ${Z}ms.`;j=!0,clearInterval(X),B(Error(A)),g("error","run.timeout",{...f,elapsedMs:Math.round(performance.now()-W)}),y7($,(K)=>K.sessionId===Q.sessionId,A),W$($,(K)=>K.sessionId===Q.sessionId,A),$.sessionHost.abort(Q.sessionId,A).catch((K)=>{g("error","run.timeout_abort_failed",{...f,error:K})})},Z)})])}finally{if(j=!0,clearInterval(X),V)clearTimeout(V)}}async function eH($,J){let Q=w0(J),Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.prompt==="string"?Z.prompt:typeof Z.input==="string"?Z.input:"";if(!W.trim())return x(J,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Q));let j=Z.attachments&&typeof Z.attachments==="object"&&!Array.isArray(Z.attachments)?Z.attachments:void 0,f=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,X=ow(Z);$.suppressNextTerminalEventBySession.set(Q,"run.start.reply");let Y;try{Y=await tw($,J,{sessionId:Q,prompt:W,mode:sw(Z.mode),delivery:Z.delivery==="queue"||Z.delivery==="steer"?Z.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:f,timeoutMs:X},X)}catch(H){if($.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q);if(O$(H))return aw(J,Q,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Q)),H}if(Y){let H=await u0($,Q),B=nw(Y);if($.publish($.buildEvent(iw(Y.finishReason),{reason:Y.finishReason,...B?{error:B}:{},result:Y,...H?{snapshot:H}:{}},Q)),$.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q)}else $.suppressNextTerminalEventBySession.delete(Q);let V=await u0($,Q);return c(J,Y||V?{...Y?{result:Y}:{},...V?{snapshot:V}:{}}:void 0)}async function $B($,J){let Q=w0(J),Z=typeof J.payload?.reason==="string"?J.payload.reason:"Run was aborted before pending approval or capability request was resolved.";y7($,(W)=>W.sessionId===Q,Z);try{await $.sessionHost.abort(Q,J.payload?.reason)}catch(W){g("warn","run.abort_failed",{command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q,error:W})}finally{W$($,(W)=>W.sessionId===Q,Z)}return c(J,{applied:!0})}async function JB($,J){let Q=xJ(J.payload?.payload);if(!Q)return x(J,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Q),c(J,{applied:!0})}async function QB($,J){switch(J.type){case"chunk":return;case"agent_event":await ew($,J);return;case"hook":if(J.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:J.payload.toolName},J.payload.sessionId));else if(J.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:J.payload.toolName},J.payload.sessionId));return;case"team_progress":{let Q={type:"team_progress_projection",version:1,sessionId:J.payload.sessionId,summary:J.payload.summary,lastEvent:J.payload.lifecycle};$.publish($.buildEvent("team.progress",Q,J.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:J.payload.sessionId,prompts:J.payload.prompts},J.payload.sessionId));return;case"pending_prompt_submitted":{let Q={id:J.payload.id,prompt:J.payload.prompt,delivery:J.payload.delivery,attachmentCount:J.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:J.payload.sessionId,prompt:Q},J.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:J.payload.sessionId,snapshot:J.payload.snapshot},J.payload.sessionId));return;case"status":{let[Q,Z]=await Promise.all([c0($,J.payload.sessionId),u0($,J.payload.sessionId)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J.payload.sessionId));return}case"ended":await $S($,J);return;default:return}}async function ew($,J){let{sessionId:Q,event:Z}=J.payload;if(Z.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Z.iteration},Q));return}if(Z.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Z.iteration,hadToolCalls:Z.hadToolCalls,toolCallCount:Z.toolCallCount},Q));return}if(Z.type==="content_start"){if(Z.contentType==="text"&&typeof Z.text==="string"&&Z.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Z.text},Q));return}if(Z.contentType==="reasoning"){if(Z.redacted&&!Z.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Q));return}if(typeof Z.reasoning==="string"&&Z.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Z.reasoning,redacted:Z.redacted===!0},Q));return}if(Z.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Z.toolCallId,toolName:Z.toolName,input:Z.input},Q));return}}if(Z.type==="content_end"){switch(Z.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Z.text},Q));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Z.reasoning},Q));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Z.toolCallId,toolName:Z.toolName,output:Z.output,error:Z.error},Q));break}return}if(Z.type==="usage"){let W;try{W=await $.sessionHost.getAccumulatedUsage?.(Q)}catch{W=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Q,delta:{inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadTokens:Z.cacheReadTokens??0,cacheWriteTokens:Z.cacheWriteTokens??0,totalCost:Z.cost??0},totals:{inputTokens:Z.totalInputTokens,outputTokens:Z.totalOutputTokens,cacheReadTokens:Z.totalCacheReadTokens??0,cacheWriteTokens:Z.totalCacheWriteTokens??0,totalCost:Z.totalCost??0},usage:W?.usage,aggregateUsage:W?.aggregateUsage,agent:{kind:J.payload.teamRole==="teammate"?"teammate":Z.parentAgentId?"subagent":"lead",agentId:Z.agentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamAgentId:J.payload.teamAgentId,teamRole:J.payload.teamRole}},Q));return}if(Z.type==="done")$.publish($.buildEvent("agent.done",{reason:Z.reason,text:Z.text,iterations:Z.iterations,usage:Z.usage},Q))}async function $S($,J){let Q=$.suppressNextTerminalEventBySession.get(J.payload.sessionId),Z=Q===J.payload.reason||Q==="run.start.reply";if(Z)$.suppressNextTerminalEventBySession.delete(J.payload.sessionId);let[W,j]=await Promise.all([c0($,J.payload.sessionId),u0($,J.payload.sessionId)]);if(J.payload.reason==="completed"){let f=await uH(W);$.publish($.buildEvent("ui.notify",f,J.payload.sessionId))}if(Z)return;$.publish($.buildEvent(J.payload.reason==="aborted"?"run.aborted":J.payload.reason==="error"||J.payload.reason==="failed"?"run.failed":"run.completed",{reason:J.payload.reason,...j?{snapshot:j}:{}},J.payload.sessionId))}import{createSessionId as jB,parseRuntimeConfigExtensions as fB}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Ir,HUB_COMPACTION_CAPABILITY as xr,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as gr,HUB_HOOK_CAPABILITY_PREFIX as mr,HUB_MISTAKE_LIMIT_CAPABILITY as vr,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as cr,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ur,isHubToolExecutorName as JS}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as ir,HUB_COMPACTION_CAPABILITY as nr,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ar,HUB_HOOK_CAPABILITY_PREFIX as sr,HUB_MISTAKE_LIMIT_CAPABILITY as or,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as tr,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as er}from"@cline/shared";var QS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function d$($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function ZS($,J){let Q=typeof $.name==="string"?$.name.trim():"",Z=typeof $.description==="string"?$.description:"",W=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=d$($.inputSchema);if(!Q||!Z||!j||!W||J.has(W))return;return J.add(W),{kind:"tool",capabilityName:W,name:Q,description:Z,inputSchema:j,...d$($.lifecycle)?{lifecycle:d$($.lifecycle)}:{}}}function h7($){if(!Array.isArray($))return[];let J=[],Q=new Set;for(let Z of $){if(!Z||typeof Z!=="object"||Array.isArray(Z))continue;let W=Z,j=W.kind,f=typeof W.capabilityName==="string"?W.capabilityName.trim():"";if(!f||Q.has(f))continue;if(j==="tool"){let X=ZS(W,Q);if(X)J.push(X);continue}if(j==="toolExecutor"){let X=W.executor;if(!JS(X))continue;Q.add(f),J.push({kind:"toolExecutor",capabilityName:f,executor:X});continue}if(j==="hook"){let X=typeof W.name==="string"?W.name.trim():"";if(!X)continue;Q.add(f),J.push({kind:"hook",capabilityName:f,name:X});continue}if(j==="compaction"){Q.add(f),J.push({kind:"compaction",capabilityName:f,...d$(W.config)?{config:d$(W.config)}:{}});continue}if(j==="checkpoint"){Q.add(f),J.push({kind:"checkpoint",capabilityName:f,...d$(W.config)?{config:d$(W.config)}:{}});continue}if(j==="mistakeLimit"){Q.add(f),J.push({kind:"mistakeLimit",capabilityName:f});continue}if(j==="userInstructionService")Q.add(f),J.push({kind:"userInstructionService",capabilityName:f})}return J}function WB($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function WS($){return Object.hasOwn($,"update")?$.update:$}function H4($){return $.trim().replace(/^\/+/,"").toLowerCase()}function jS($){let J=($??[]).map(H4).filter(Boolean);return J.length>0?new Set(J):void 0}function fS($,J,Q){if(!Q)return!0;let Z=H4($),W=H4(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function b7($,J){let Q=jS(J);return $.records.skill.map((Z)=>({id:Z.id,name:Z.item.name,description:"description"in Z.item&&typeof Z.item.description==="string"?Z.item.description:void 0,disabled:Z.item.disabled===!0,skill:Z.item})).filter((Z)=>fS(Z.id,Z.name,Q))}function ZB($,J){let Q=async(Z,W)=>{let j=H4(Z),X=b7($,J).filter((A)=>A.id===j||H4(A.name)===j||A.id.endsWith(`:${j}`)).filter((A)=>!A.disabled);if(X.length!==1)return X.length>1?`Skill "${Z}" is ambiguous. Use one of: ${X.map((A)=>A.id).join(", ")}`:`Skill "${Z}" not found.`;let Y=X[0].skill,V=W?.trim(),H=V?`
702
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[J,W,Q]),Z.map((j)=>j.run_id)}handleTeamEvent($,J){this.appendTeamEvent($,J.type,J)}}function RH($={}){try{let J=new J4($);return J.init(),J}catch{let J=new SJ({teamDir:$.teamDir});return J.init(),J}}function CJ($,J){return sP($,J)}function tP($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function eP($,J){return $.filter((Q)=>tP(Q.name,J))}function V7($,J){return y1(eP($,J))}var $N={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 JN($){let J=$.trim().toLowerCase();return $N[J]??J}function QN($,J){if(J.tools===void 0)return $;let Q=new Set(J.tools.map(JN));if(J.skills!==void 0)Q.add("skills");return $.filter((Z)=>Q.has(Z.name))}function zH(){return`team-${oP(5)}`}function yJ($,J,Q,Z,W,j,f,X){let Y=$1[x1({mode:Q})],V=Z8(J,Z,Q,W??Q8);return V7(H8({cwd:$,...Y,enableSkills:!!f,...V,executors:{...f?{skills:f}:{},...X??{}}}),j)}function ZN($){return yJ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,WN,$.toolExecutors).some((J)=>J.name==="skills")}var WN=async()=>"";async function jN($){let J=H0();if(!L$({filePath:J}))return{tools:[]};let Q=new R8({clientFactory:h6({settingsPath:J})}),Z;try{Z=await U8(Q,{filePath:J})}catch(X){await Q.dispose().catch(()=>{});let Y=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${Y}`),{tools:[]}}let W=Z.filter((X)=>X.disabled!==!0),j=await Promise.allSettled(W.map((X)=>I6({serverName:X.name,provider:Q}))),f=[];for(let[X,Y]of j.entries())if(Y.status==="fulfilled")f.push(...Y.value);else{let V=Y.reason instanceof Error?Y.reason.message:String(Y.reason);$?.log(`[mcp] Failed to load tools from MCP server "${W[X].name}", skipping: ${V}`)}return{tools:f,shutdown:async()=>{await Q.dispose()}}}function fN($,J){if(!$)return;for(let Q of $.getTeammateIds())try{$.shutdownTeammate(Q,J)}catch{}}function XN($){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 YN($){let J=$1[x1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??J.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??J.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class EJ{teamRuntimeEntries=new Map;async build($){let{config:J,hooks:Q,extensions:Z,logger:W,telemetry:j,createSpawnTool:f,onTeamRestored:X,userInstructionService:Y,configExtensions:V,toolExecutors:H}=$,B=$.onTeamEvent??(()=>{}),A=YN(J),K=J.workspaceRoot??J.cwd,G=$.toolPolicies??J.toolPolicies,R=H1(),D=[],U=J.teamName?.trim()||zH(),F=J.sessionId?.trim()||U,O=A.enableSpawnAgent?jJ({workspaceRoot:K}):{configs:[],errors:[]},T=O.configs.some((I)=>I.skills!==void 0),L=CJ(V,"rules"),z=CJ(V,"skills"),M=z||T,P=CJ(V,"workflows"),C=CJ(V,"plugins"),m=L||z||P,n=!1,o=Boolean(Y),a=Y,l0;for(let I of O.errors)(W??J.logger)?.log?.(`[agents] Failed to load agent config at ${I.path}: ${I.error.message}`);if(!a&&(m||T))a=U2({skills:M?{workspacePath:K,includePluginSkills:C,pluginSkillDirectories:C?$.pluginSkillDirectories:void 0,pluginPaths:J.pluginPaths,cwd:J.cwd}:{workspacePath:K},rules:{workspacePath:J.cwd},workflows:{workspacePath:J.cwd}});if(a)await a.start().catch(()=>{});let f$=A.enableTools&&z&&Boolean(a)&&a?.hasConfiguredSkills(J.skills)===!0&&ZN({cwd:J.cwd,providerId:J.providerId,mode:A.mode,modelId:J.modelId,toolRoutingRules:J.toolRoutingRules,toolPolicies:G,toolExecutors:H}),p=a&&m?a.createExtension({includeRules:L,includeSkills:z,includeWorkflows:P,registerSkillsTool:f$,allowedSkillNames:J.skills}):void 0,W1=p?[...Z??J.extensions??[],p]:Z??J.extensions;if(A.enableTools){if(D.push(...yJ(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H)),!A.disableMcpSettingsTools){let I=await jN(J.logger);D.push(...I.tools),l0=I.shutdown}}let N,X0=A.enableAgentTeams?RH():void 0,J0=X0?.loadRuntime(F),T0=J0?.state,p$=J0?.teammates??[],j1=new Map(p$.map((I)=>[I.agentId,I])),o0=J.sessionId||U,x2,r$=[],A4=!1,f1=G2({providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey??"",baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:Q,extensions:W1,logger:W??J.logger,telemetry:$.telemetry??J.telemetry,workspaceMetadata:J.workspaceMetadata});if(A.enableSpawnAgent){if(O.configs.length>0)D.push(...V7(XJ({configProvider:f1,agents:O.configs,createSubAgentTools:(I)=>A.enableTools?QN(yJ(J.cwd,I.providerId??J.providerId,A.mode,I.modelId??J.modelId,J.toolRoutingRules,G,I.skills!==void 0&&a?.createSkillsExecutor?a.createSkillsExecutor(I.skills):void 0,H),I):[],hookErrorMode:J.hookErrorMode,toolPolicies:G,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),G))}if(!this.teamRuntimeEntries.has(o0))this.teamRuntimeEntries.set(o0,{delegatedAgentConfigProvider:f1});let K4=()=>{if(!A.enableAgentTeams)return;let I=this.teamRuntimeEntries.get(o0)??{delegatedAgentConfigProvider:f1};if(this.teamRuntimeEntries.set(o0,I),N=I.runtime,!N){if(N=new l8({teamName:U,leadAgentId:J.sessionId||"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(t)=>{if(B(t),N&&X0){if(t.type==="teammate_spawned"&&t.teammate?.rolePrompt){let X1={agentId:t.agentId,rolePrompt:t.teammate.rolePrompt,modelId:t.teammate.modelId,maxIterations:t.teammate.maxIterations};j1.set(X1.agentId,X1)}if(t.type==="teammate_shutdown"&&!XN(t.reason))j1.delete(t.agentId);X0.handleTeamEvent(F,t),X0.persistRuntime(F,N.exportState(),Array.from(j1.values()))}}}),T0)N.hydrateState(T0),A4=!0;I.runtime=N}if(!n){if(!N)return;n=!0;let t=w6({runtime:N,leadAgentId:J.sessionId||"lead",restoredFromPersistence:Boolean(T0),restoredTeammates:p$,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(X1)=>{r$=X1,x2?.addTools(X1)},createBaseTools:A.enableTools?()=>yJ(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H):void 0,teammateConfigProvider:f1});if(A4)N.recoverActiveRuns("runtime_recovered");if(t.restoredFromPersistence)X?.();D.push(...t.tools)}return N};if(A.enableSpawnAgent&&f){let I=f();D.push({...I,execute:async(t,X1)=>{return K4(),I.execute(t,X1)}})}if(A.enableAgentTeams)K4();let i$=V7(D,G),X5=i$.some((I)=>I.name==="submit_and_exit"&&I.lifecycle?.completesRun===!0),G4=A.enableAgentTeams?()=>{let I=this.teamRuntimeEntries.get(o0)?.runtime;if(!I)return;let t=I.listTasks(),X1=t.some((T1)=>T1.status==="in_progress"||T1.status==="pending"),YW=I.listRuns({}),RA=YW.some((T1)=>T1.status==="running"||T1.status==="queued");if(X1||RA){let T1=t.filter((S0)=>S0.status==="in_progress"||S0.status==="pending").map((S0)=>`${S0.id} (${S0.status}): ${S0.title}`).join(", "),VW=YW.filter((S0)=>S0.status==="running"||S0.status==="queued").map((S0)=>`${S0.id} (${S0.status})`).join(", "),Y5=[];if(T1)Y5.push(`Unfinished tasks: ${T1}`);if(VW)Y5.push(`Active runs: ${VW}`);return`[SYSTEM] You still have team obligations. ${Y5.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,UA=X5?{requireCompletionTool:!0,...G4?{completionGuard:G4}:{}}:G4?{completionGuard:G4}:void 0;return{tools:i$,logger:W??J.logger,telemetry:j??J.telemetry,teamRuntime:N,teamRestoredFromPersistence:Boolean(T0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(o0)?.delegatedAgentConfigProvider??f1,extensions:W1,completionPolicy:UA,registerLeadAgent:(I)=>{if(x2=I,r$.length>0)I.addTools(y1(r$,[...R]))},shutdown:async(I)=>{if(fN(N,I),this.teamRuntimeEntries.delete(o0),await l0?.(),!o)a?.stop()}}}}function VN($,J){let Q=$?.expiresAt,Z=J?.expiresAt;return $?.accessToken===J?.accessToken&&$?.refreshToken===J?.refreshToken&&$?.accountId===J?.accountId&&Q===Z}class bJ 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 H7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new Q$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let J=f0($.providerId);if(!J)return null;return this.resolveWithSingleFlight(J.providerId,J.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,J,Q=!1){let Z=this.refreshInFlight.get(J);if(Z)return Z;let W=this.resolveProviderApiKeyInternal($,J,Q).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(J)});return this.refreshInFlight.set(J,W),W}async resolveProviderApiKeyInternal($,J,Q){let Z=f0($);if(!Z)return null;let W=this.providerSettingsManager.getProviderSettings(J);if(!W)return null;let j=p5($,W);if(!j)return null;let f=await Z.refresh({settings:W,credentials:j,forceRefresh:Q,telemetry:this.telemetry});if(!f)throw new bJ($);let X=c2({manager:this.providerSettingsManager,providerId:$,settings:W,credentials:f,setLastUsed:!1,save:!1}),Y=!VN(W.auth,X.auth);if(Y)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:Z.getApiKey(X)??f.access,accountId:f.accountId,refreshed:Y}}}import{normalizeUserInput as HN}from"@cline/shared";import{nanoid as BN}from"nanoid";class LH{list($){return $?m0($):[]}update($,J){if(!$)return{sessionId:J.sessionId,prompts:[],updated:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((Y)=>Y.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:m0($),updated:!1};let W=$.pendingPrompts[Z];if(!W)return{sessionId:J.sessionId,prompts:m0($),updated:!1};let j=J.prompt===void 0?W.prompt:HN(J.prompt).trim();if(!j)throw Error("prompt cannot be empty");let f=J.delivery??W.delivery,X={...W,prompt:j,mode:J.mode??W.mode,delivery:f};return $.pendingPrompts.splice(Z,1),AN($,X,Z,W.delivery),{sessionId:J.sessionId,prompts:m0($),prompt:hJ(X),updated:!0}}delete($,J){if(!$)return{sessionId:J.sessionId,prompts:[],removed:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((j)=>j.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:m0($),removed:!1};let[W]=$.pendingPrompts.splice(Z,1);return{sessionId:J.sessionId,prompts:m0($),prompt:W?hJ(W):void 0,removed:!0}}enqueue($,J){let{prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f}=J,X=$.pendingPrompts.findIndex((Y)=>Y.prompt===Q);if(X>=0){let[Y]=$.pendingPrompts.splice(X,1),V={...Y,prompt:Q,mode:Z??Y.mode,userImages:j??Y.userImages,userFiles:f??Y.userFiles};if(W==="steer"||Y.delivery==="steer")$.pendingPrompts.unshift({...V,delivery:"steer"});else $.pendingPrompts.push(V)}else{let Y={id:`pending_${Date.now()}_${BN(5)}`,prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f};if(W==="steer")$.pendingPrompts.unshift(Y);else $.pendingPrompts.push(Y)}return m0($)}consumeSteer($){let J=$.pendingPrompts.findIndex((Z)=>Z.delivery==="steer");if(J<0)return{prompts:m0($)};let[Q]=$.pendingPrompts.splice(J,1);return{entry:Q,prompts:m0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:m0($)}}requeueFront($,J){return $.pendingPrompts.unshift(J),m0($)}clear($){return $.pendingPrompts.length=0,[]}}class B7{deps;service=new LH;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Q=this.service.update(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}delete($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Q=this.service.delete(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}enqueue($,J){let Q=this.deps.getSession($);if(!Q||Q.aborting)return;this.service.enqueue(Q,J),this.emitPrompts(Q),this.scheduleDrain($,Q)}consumeSteer($){let J=this.deps.getSession($);if(!J)return;let{entry:Q}=this.service.consumeSteer(J);if(!Q)return;return this.emitPrompts(J),this.emitSubmitted(J,Q),Q}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:m0($)}})}scheduleDrain($,J){if(J.pendingPrompts.length===0||J.aborting||J.drainingPendingPrompts||!J.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let J=this.deps.getSession($);if(!J)return;if(J.aborting||J.drainingPendingPrompts)return;if(!J.agent.canStartRun())return;let{entry:Q}=this.service.shiftNext(J);if(!Q)return;this.emitPrompts(J),this.emitSubmitted(J,Q),J.drainingPendingPrompts=!0;let Z=!0;try{await this.deps.send({sessionId:$,prompt:Q.prompt,...Q.mode?{mode:Q.mode}:{},userImages:Q.userImages,userFiles:Q.userFiles})}catch{Z=!1,this.service.requeueFront(J,Q),this.emitPrompts(J)}finally{if(J.drainingPendingPrompts=!1,Z&&J.pendingPrompts.length>0&&J.status!=="failed"&&J.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,J){let Q=hJ(J);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}})}}function hJ($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function m0($){return $.pendingPrompts.map(hJ)}function AN($,J,Q,Z){if(J.delivery==="steer")$.pendingPrompts.unshift(J);else if(Z==="steer")$.pendingPrompts.push(J);else $.pendingPrompts.splice(Q,0,J)}F0();class K7{deps;constructor($){this.deps=$}dispatchAgentEvent($,J,Q){let Z=this.deps.getSession($),W={sessionId:$,config:J,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=uZ(Q),f=!!Z&&(!j.agentId||j.agentId===A7(Z.agent));dZ(W,Q,f?{isPrimaryAgentEvent:!0,agentId:A7(Z.agent),conversationId:Z.agent.getConversationId(),...Z?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,J){let Q=this.deps.getSession($);if(Q){if(TZ(Q,J),J.type==="agent_event"){let Z={sessionId:$,config:Q.config,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};dZ(Z,J.event,{agentId:J.agentId,teamRole:"teammate",teamAgentId:J.agentId,isPrimaryAgentEvent:!1})}if(J.type==="teammate_spawned"){let Z=L1({agentId:J.teammate.runtimeAgentId??J.agentId,conversationId:J.teammate.conversationId,parentAgentId:J.teammate.parentAgentId,createdByAgentId:A7(Q.agent),teamId:Q.runtime.teamRuntime?.getTeamId(),teamName:Q.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:J.agentId});if(Z)V$(Q.config.telemetry,{ulid:$,modelId:J.teammate.modelId??Q.config.modelId,provider:Q.config.providerId,...Z})}}if(await MZ($,J,this.deps.invokeBackendOptional),Q)qZ(Q,$,J,this.deps.emit)}async handlePluginEvent($,J,Q){if(J.name==="plugin_log"){this.handlePluginLog($,J.payload);return}if(J.name==="automation_event"){let Y=this.deps.getSession($)?.config.extensionContext?.automation??Q;if(!Y)return;let V=J.payload&&typeof J.payload==="object"?J.payload:void 0;if(!V)return;await Y.ingestEvent(V);return}if(J.name!=="steer_message"&&J.name!=="queue_message"&&J.name!=="pending_prompt")return;let Z=J.payload&&typeof J.payload==="object"?J.payload:void 0,W=typeof Z?.sessionId==="string"&&Z.sessionId.trim().length>0?Z.sessionId.trim():$,j=typeof Z?.prompt==="string"?Z.prompt.trim():"";if(!j)return;let f=J.name==="steer_message"?"steer":J.name==="queue_message"?"queue":Z?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(W,{prompt:j,delivery:f})}handlePluginLog($,J,Q){let Z=this.deps.getSession($),W=Q??Z?.config.extensionContext?.logger??Z?.config.logger;if(!W||!J||typeof J!=="object")return;let j=J,f=typeof j.message==="string"?j.message:"";if(!f)return;let X=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(X.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)X.pluginName=j.pluginName;if(j.level==="debug"){W.debug(f,X);return}if(j.level==="error"){if(W.error)W.error(f,X);else W.log(f,{...X,severity:"error"});return}W.log(f,X)}}function A7($){return $.getAgentId()}function G7($){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:e1($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function F7($,J){let Q=$[J];return typeof Q==="function"?Q:null}async function _H($,J,...Q){let Z=F7($,J);if(!Z)throw Error(`session service method not available: ${J}`);return Promise.resolve(Z.apply($,Q))}async function OH($,J,...Q){let Z=F7($,J);if(!Z)return;await Promise.resolve(Z.apply($,Q))}async function TH($,J,...Q){let Z=F7($,J);if(!Z)return;return await Promise.resolve(Z.apply($,Q))}p0();F0();function D7($,J,Q){return{onSubAgentEvent:(Z)=>$.onAgentEvent(Q,J,Z),onSubAgentStart:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime;$.subAgentStarts.set(Z.subAgentId,{startedAt:Date.now(),rootSessionId:Q});let j=L1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId});if(j)V$(J.telemetry,{ulid:Q,modelId:J.modelId,provider:J.providerId,...j});z4(J.telemetry,{event:"started",ulid:Q,durationMs:0,parentId:Z.parentAgentId,agentId:Z.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Q,Z)},onSubAgentEnd:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime,j=$.subAgentStarts.get(Z.subAgentId),f=j?Date.now()-j.startedAt:0,X=Z.result?.text?Z.result.text.split(`
703
+ `).length:0;z4(J.telemetry,{event:"ended",ulid:Q,durationMs:f,outputLines:X,errorMessage:Z.error?String(Z.error):void 0,agentId:Z.subAgentId,parentId:Z.parentAgentId,...L1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId})}),$.subAgentStarts.delete(Z.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Q,Z)}}}function U7($,J,Q,Z){let W=D7($,J,Q);return D2({configProvider:{getRuntimeConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:J.hooks,extensions:J.extensions,logger:J.logger,telemetry:J.telemetry},getConnectionConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let f=J.enableTools?H8({cwd:J.cwd,...$1[x1({mode:J.mode})],executors:Z}):[];if(J.enableSpawnAgent)f.push(U7($,J,Q,Z));return y1(f)},...W})}import{readFile as KN,stat as GN}from"node:fs/promises";var FN=20480000;async function MH($){let J=await GN($);if(!J.isFile())throw Error("Path is not a file");if(J.size>FN)throw Error("File is too large to read into context.");let Q=await KN($,"utf8");if(Q.includes("\x00"))throw Error("Cannot read binary file into context.");return Q}var qH=5000;function Q4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function TN($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=Q4(J.inputTokens),Z=Q4(J.outputTokens),W=Q4(J.cacheReadTokens),j=Q4(J.cacheWriteTokens),f=Q4(J.totalCost);if(Q===void 0||Z===void 0||W===void 0||j===void 0||f===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:W,cacheWriteTokens:j,totalCost:f}}function MN($,J){return{inputTokens:Math.max($.inputTokens,J.inputTokens),outputTokens:Math.max($.outputTokens,J.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,J.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,J.cacheWriteTokens),totalCost:Math.max($.totalCost,J.totalCost)}}class Z${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new h8;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new E2;constructor($){let J=UN();if(J)ON(J);let Q=g0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new EJ,this.createAgentInstance=$.createAgent??((Z)=>new g1(Z)),this.defaultCapabilities=L0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new Q$,this.oauthTokenManager=$.oauthTokenManager??new H7({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Q),this.defaultFetch=$.fetch,this.pendingPromptsController=new B7({getSession:(Z)=>this.sessions.get(Z),emit:(Z)=>this.emit(Z),send:(Z)=>this.runTurn(Z)}),this.pendingPrompts={list:async(Z)=>this.pendingPromptsController.list(Z.sessionId),update:async(Z)=>this.pendingPromptsController.update(Z),delete:async(Z)=>this.pendingPromptsController.delete(Z)},this.eventBridge=new K7({getSession:(Z)=>this.sessions.get(Z),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Z)=>this.emit(Z),persistMessages:(Z,W,j)=>{this.invoke("persistSessionMessages",Z,W,j)},enqueuePendingPrompt:(Z,W)=>this.pendingPromptsController.enqueue(Z,W),invokeBackendOptional:(Z,...W)=>this.invokeOptional(Z,...W)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!J?.apiKey)return $;return{...$,config:{...$.config,apiKey:J.apiKey}}}async startSession($){let J=$.source??z0.CLI,Q=s(),Z=$.config.sessionId?.trim()??"",W=Z||zN(),j=await this.applyInitialOAuthCredentials($),f=j.initialMessages??[],X=f.length>0?GJ(f):U0(),Y=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Y)throw Error("session service method not available: ensureSessionsDir");let V=R7(Y,W),H=R7(V,`${W}.messages.json`),B=R7(V,`${W}.json`),A=e1($.config),K=P0.parse({version:1,session_id:W,source:J,pid:process.pid,started_at:Q,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:A,team_name:j.config.teamName,enable_tools:j.config.enableTools,enable_spawn:j.config.enableSpawnAgent,enable_teams:j.config.enableAgentTeams,prompt:j.prompt?.trim()||void 0,messages_path:H}),G;if(Z.length>0&&f.length>0&&!j.prompt?.trim()){let N=await this.invokeOptionalValue("readSessionManifest",W);if(N)K=N,G={manifestPath:B,messagesPath:N.messages_path||H,manifest:N}}let D=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:V,rootMessagesPath:G?.messagesPath??H,manifest:K});this.usageBySession.set(W,X),this.aggregateUsageBySession.set(W,D);let U=L0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,z,M={getSession:(N)=>this.sessions.get(N),subAgentStarts:this.subAgentStarts,onAgentEvent:(N,X0,J0)=>this.eventBridge.dispatchAgentEvent(N,X0,J0),invokeBackendOptional:(N,...X0)=>this.invokeOptional(N,...X0)};z=await vV({input:j,localRuntime:$.localRuntime,sessionId:W,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(N)=>{if(N.name==="plugin_log"){this.eventBridge.handlePluginLog(W,N.payload,T);return}this.eventBridge.handlePluginEvent(W,N,L)},onTeamEvent:(N)=>{this.eventBridge.handleTeamEvent(W,N),z.config.onTeamEvent?.(N)},createSpawnTool:()=>U7(M,z.config,W,F),createSubAgentLifecycleCallbacks:(N)=>D7(M,N,W),readSessionMetadata:async()=>(await this.getSession(W))?.metadata,writeSessionMetadata:async(N)=>{await this.persistSessionMetadata(W,()=>N)}});let P=await this.runtimeBuilder.build(z.runtimeBuilderInput),C=z.config,m=z.providerConfig;if(P.teamRuntime&&!C.teamName?.trim())C.teamName=P.teamRuntime.getTeamName();let n=[...P.tools,...C.extraTools??[]],o=P.extensions??z.extensions,a={sessionId:W,providerId:m.providerId,modelId:m.modelId,apiKey:m.apiKey,baseUrl:m.baseUrl,headers:m.headers,knownModels:m.knownModels,providerConfig:m,thinking:C.thinking,reasoningEffort:C.reasoningEffort??m.reasoningEffort,systemPrompt:C.systemPrompt,maxIterations:C.maxIterations,execution:C.execution,prepareTurn:cZ(C),tools:n,hooks:z.hooks,extensions:o,hookErrorMode:C.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:MH,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval?async(N)=>{let X0=z.requestToolApproval,J0=this.sessions.get(W);if(J0)await this.markTurnPending(J0);try{if(!X0)return{approved:!1,reason:"Tool approval callback is not configured."};return await X0(N)}finally{let T0=this.sessions.get(W);if(T0?.status==="pending")await this.markTurnRunning(T0)}}:void 0,telemetry:C.telemetry,onConsecutiveMistakeLimitReached:C.onConsecutiveMistakeLimitReached,completionPolicy:P.completionPolicy,consumePendingUserMessage:()=>{let N=this.pendingPromptsController.consumeSteer(W);return N?r8(N.prompt,N.mode??C.mode):void 0},logger:P.logger??C.logger,extensionContext:C.extensionContext,onEvent:(N)=>this.eventBridge.dispatchAgentEvent(W,C,N)};a.hooks={...a.hooks,onEvent:async(N)=>{if(await z.hooks?.onEvent?.(N),N.type!=="assistant-message")return;let X0=this.sessions.get(W);if(!X0)return;let J0=X0.agent.getMessages();try{await this.invoke("persistSessionMessages",W,J0,C.systemPrompt)}catch(T0){C.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:W,error:T0}),g$(C.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:T0,severity:"warn",handled:!0,context:{sessionId:W,providerId:C.providerId,modelId:C.modelId}})}}};let l0=this.createAgentInstance(a);if(a.onEvent)l0.subscribeEvents(a.onEvent);P.registerLeadAgent?.(l0);let f$=L1({agentId:l0.getAgentId(),conversationId:l0.getConversationId(),teamId:P.teamRuntime?.getTeamId(),teamName:P.teamRuntime?.getTeamName(),teamRole:P.teamRuntime?"lead":void 0});if(cV(C,W,Z.length>0,A,f$),f$)V$(C.telemetry,{ulid:W,modelId:C.modelId,provider:C.providerId,...f$});if(P.teamRuntime)M5(C.telemetry,{ulid:W,teamId:P.teamRuntime.getTeamId(),teamName:P.teamRuntime.getTeamName(),leadAgentId:l0.getAgentId(),restoredFromPersistence:P.teamRestoredFromPersistence===!0});let p={sessionId:W,config:C,sessionMetadata:j.sessionMetadata,...G?{artifacts:G}:{},source:J,startedAt:G?.manifest.started_at??Q,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??Q,pendingPrompt:K.prompt,runtime:P,agent:l0,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:f,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(W,p),this.emitStatus(W,"running"),f.length>0&&!G){if(await this.ensureSessionPersisted(p),await this.invoke("persistSessionMessages",p.sessionId,f,p.config.systemPrompt),!j.prompt?.trim())await this.updateStatus(p,"completed",0)}let W1;try{if(j.prompt?.trim())if(W1=await this.executeTurn(p,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!p.interactive)await this.finalizeSingleRun(p,W1.finishReason);else await this.completeInteractiveTurn(p,W1.finishReason)}catch(N){if(p.interactive&&p.aborting)W1=await this.completeAbortedInteractiveTurn(p);else throw g$(p.config.telemetry,{component:"core",operation:"session.start",error:N,severity:"error",handled:!1,context:{sessionId:p.sessionId,providerId:p.config.providerId,modelId:p.config.modelId}}),await this.failSession(p),N}return{sessionId:W,manifest:K,manifestPath:B,messagesPath:H,result:W1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(J)=>this.getSession(J),readMessages:(J)=>this.readSessionMessages(J),buildStartInput:(J,Q)=>{let Z=J.restoredCheckpointMetadata?{...Q.sessionMetadata??{},checkpoint:J.restoredCheckpointMetadata}:Q.sessionMetadata;return{...Q,...Z?{sessionMetadata:Z}:{},initialMessages:J.initialMessages}},startSession:(J)=>this.startSession(J),getStartedSessionId:(J)=>J.sessionId,readRestoredSession:(J)=>this.getSession(J)})}async runTurn($){let J=this.getSessionOrThrow($.sessionId),Q=J.agent.canStartRun(),Z=$.delivery??(J.interactive&&!Q?"queue":void 0);if(J.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Z??"immediate"}}),Z==="queue"||Z==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Z,userImages:$.userImages,userFiles:$.userFiles});return}try{let W=await this.executeTurn(J,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!J.interactive)await this.finalizeSingleRun(J,W.finishReason);else await this.completeInteractiveTurn(J,W.finishReason);if(W.finishReason==="error"||W.finishReason==="aborted")return W;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),W}catch(W){if(J.interactive&&J.aborting)return await this.completeAbortedInteractiveTurn(J);throw g$(J.config.telemetry,{component:"core",operation:"session.submit",error:W,severity:"error",handled:!1,context:{sessionId:J.sessionId,providerId:J.config.providerId,modelId:J.config.modelId}}),await this.failSession(J),W}}async getAccumulatedUsage($){let J=s9(this.usageBySession.get($)),Q=s9(this.aggregateUsageBySession.get($));return J||Q?{usage:J,aggregateUsage:Q}:void 0}async abort($,J){let Q=this.sessions.get($);if(!Q)return;Q.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Q.aborting=!0,this.pendingPromptsController.clearAborted(Q),Q.agent.abort(J)}async stopSession($){let J=this.sessions.get($);if(!J)return;if(J.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),J.interactive&&!Z0(J.status)){await this.releaseSessionRuntime(J,"session_stop");return}if(J.interactive&&J.agent.canStartRun()){await this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:"session_stop",endReason:"stopped"});return}J.aborting=!0,J.agent.abort(Error("session_stop")),await this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let J=[...this.sessions.values()];if(J.length===0)return;await Promise.allSettled(J.map((Q)=>Q.interactive&&!Z0(Q.status)?this.releaseSessionRuntime(Q,$):Q.interactive&&Q.agent.canStartRun()?this.shutdownSession(Q,{status:this.resolveInteractiveStopStatus(Q),exitCode:this.resolveInteractiveStopExitCode(Q),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Q,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let J=this.sessions.get($);if(J)return G7(J);let Q=$.trim();if(!Q)return;let Z=await this.getRow(Q);if(Z)return E8(Z);let W=await this.readManifest(Q);return W?e9(W):void 0}async listSessions($=200){let Q=(await this.listRows($)).map(E8),Z=new Set(Q.map((W)=>W.sessionId));for(let W of this.sessions.values()){if(Z.has(W.sessionId))continue;Q.unshift(G7(W))}return Q.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let J=await this.invoke("deleteSession",$);if(J.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return J.deleted}async updateSession($,J){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:J.prompt,metadata:J.metadata,title:J.title}))?.updated===!0}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.getRow(J);if(Q?.messagesPath)return d1(Q.messagesPath);let Z=await this.readManifest(J);return d1(Z?.messages_path)}async dispatchHookEvent($){await uX($,{queueSpawnRequest:(J)=>this.invokeOptional("queueSpawnRequest",J),upsertSubagentSessionFromHook:(J)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",J),appendSubagentHookAudit:(J,Q)=>this.invokeOptional("appendSubagentHookAudit",J,Q),applySubagentStatus:(J,Q)=>this.invokeOptional("applySubagentStatus",J,Q)})}subscribe($,J){return this.events.subscribe($,J)}async updateSessionModel($,J){let Q=this.getSessionOrThrow($);Q.config.modelId=J,Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:J}),Q.agent.updateConnection({modelId:J})}handlePluginEvent($,J,Q){return this.eventBridge.handlePluginEvent($,J,Q)}async executeTurn($,J){let Q=await this.prepareTurnInput($,J),Z=Q.prompt.trim();if(!Z)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Z;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let W=await this.executeAgentTurn($,Z,Q.userImages,Q.userFiles);while(PZ($,W.finishReason)){let j=await NZ($);if(j.length===0)break;let f=wZ($,j);W=await this.executeAgentTurn($,f)}return W}async completeInteractiveTurn($,J){if(p8($))return;$.lastInteractiveTurnFinishReason=J,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let J=$.lastInteractiveTurnFinishReason;if(!J)return"cancelled";switch(J){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return J}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let J=new Date,Q=$.agent.getMessages(),Z=U0();return $.persistedMessages=Q,$.started=$.started||Q.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Z}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Z,messages:Q,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:J,endedAt:J,durationMs:0}}async executeAgentTurn($,J,Q,Z){let W=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),f=this.usageBySession.get($.sessionId)??U0(),X=this.aggregateUsageBySession.get($.sessionId)??f;$.turnUsageBaseline=f,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=U0(),$.turnUsageByAgent=new Map,U5($.config.telemetry,$.sessionId,$.config.mode),g2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let Y=W?()=>$.agent.continue(J,Q,Z):()=>$.agent.run(J,Q,Z),V=await this.runWithAuthRetry($,Y,j);$.started=!0;let H=r6(V.messages,V,j);$.persistedMessages=H;let B=KJ($.turnUsageByAgent?.values()??[]),A=K0(f,V.usage),K=K0(K0(U0(),V.usage),B),G=K0(X,K);return this.usageBySession.set($.sessionId,A),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:A.totalCost,aggregatedAgentsCost:G.totalCost,usage:A,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,V),V}catch(Y){throw g$($.config.telemetry,{component:"core",operation:"session.turn",error:Y,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),Y}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,J){if($.submitAndExitObserved)return;if(!J.toolCalls.some((Z)=>Z.name===D0.SUBMIT_AND_EXIT&&Z.error===void 0))return;$.submitAndExitObserved=!0,U4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,J){let Q=e1($.config),Z=_N(J.prompt).trim();if(!Z)return{prompt:"",userImages:J.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles)};let W=await R6(Z,Q);uV($.config.telemetry,W);let j=r8(W.prompt,J.mode??$.config.mode),f=this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles),X=this.resolveAbsoluteFilePaths(Q,W.matchedFiles),Y=Array.from(new Set([...f,...X]));return{prompt:j,userImages:J.userImages,userFiles:Y.length>0?Y:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let J=e1($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:J,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,J){let Q=this.sessions.get($),Z=await this.invokeOptionalValue("readSessionManifest",$)??Q?.artifacts?.manifest,W=J(Z?.metadata);if(!Q?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:W}))?.updated===!1)return;Q.sessionMetadata=W,Q.artifacts.manifest.metadata=W}async finalizeSingleRun($,J){if(p8($))return;let Q=J==="aborted"||$.aborting,Z=J==="error";await this.shutdownSession($,{status:Q?"cancelled":Z?"failed":"completed",exitCode:Z?1:0,shutdownReason:Z?"session_error":"session_complete",endReason:J})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,J){if(J.status==="completed"&&!$.submitAndExitObserved)U4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});HJ($);let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),g$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,status:J.status,shutdownReason:J.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,J.status,J.exitCode)}catch(W){Z("update_status",W)}try{await $.agent.shutdown(J.shutdownReason)}catch(W){Z("agent_shutdown",W)}}try{await Promise.resolve($.runtime.shutdown(J.shutdownReason))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:J.endReason,ts:Date.now()}}),Q.length>0&&J.status==="failed")throw Q[0]}async releaseSessionRuntime($,J){let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),g$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,reason:J,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(J)}catch(W){Z("agent_shutdown",W)}try{await Promise.resolve($.runtime.shutdown(J))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),Q.length>0)throw Q[0]}async updateStatus($,J,Q){if(!$.artifacts)return;let Z=await this.invoke("updateSessionStatus",$.sessionId,J,Q);if(!Z.updated)return;let W=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(W.status=J,Z0(J))delete W.ended_at,W.exit_code=null;else W.ended_at=Z.endedAt??s(),W.exit_code=typeof Q==="number"?Q:null;$.artifacts.manifest=W,$.status=J,$.updatedAt=Z.endedAt??s(),$.endedAt=Z0(J)?null:W.ended_at,$.exitCode=W.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,W),this.emitStatus($.sessionId,J)}async runWithAuthRetry($,J,Q){try{return await J()}catch(Z){if(!v2($.config.providerId)||!LN(Z))throw Z;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Q),J()}}async syncOAuthCredentials($,J){let Q=null;try{Q=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:J?.forceRefresh})}catch(Z){if(Z instanceof bJ)throw Error(`${Z.providerId} requires re-authentication.`);throw Z}if(!Q?.apiKey||$.config.apiKey===Q.apiKey)return;$.config.apiKey=Q.apiKey,$.agent.updateConnection({apiKey:Q.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Q.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Q.apiKey})}getSessionOrThrow($){let J=this.sessions.get($);if(!J){let Q=new _$($);throw g$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Q,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Q}return J}resolveAbsoluteFilePaths($,J){if(!J||J.length===0)return[];let Q=J.map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>RN(Z)?Z:z7($,Z));return Array.from(new Set(Q))}getSessionAgentTelemetryIdentity($){return L1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let J=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Q=K0($.initialUsage,J);return this.withPersistedAggregateUsageFloor(Q,$.manifest)}async summarizePersistedTeammateUsage($,J,Q){let Z=z7(J),W=`${Q}.messages.json`,j;try{j=DN($)}catch{return U0()}let f=U0();for(let X of j){if(!X.endsWith(".messages.json"))continue;if(X===W)continue;let Y=z7($,X);if(Y===Z)continue;let V=await d1(Y);if(V.length===0)continue;f=K0(f,GJ(V))}return f}withPersistedAggregateUsageFloor($,J){let Q=TN(J.metadata?.aggregateUsage);if(Q)return MN($,Q);let Z=J.metadata?.aggregatedAgentsCost;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=$.totalCost)return $;return{...$,totalCost:Z}}emitStatus($,J){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:J}})}async emitSessionSnapshot($){let J=await this.getSession($);if(!J)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:i1({session:J,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),qH))}async getRow($){let J=$.trim();if(!J)return;return(await this.listRows(qH)).find((Z)=>Z.sessionId===J)}async readManifest($){let J=$.trim();if(!J)return;return await this.invokeOptionalValue("readSessionManifest",J)}invoke($,...J){return _H(this.sessionService,$,...J)}invokeOptional($,...J){return OH(this.sessionService,$,...J)}invokeOptionalValue($,...J){return TH(this.sessionService,$,...J)}}function qN($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let J=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(J==="local"||J==="hub"||J==="remote")return J;return"auto"}var Z4,W4;function PN($,J){if($!=="auto"&&$!=="hub")return;if(J.hub?.endpoint?.trim())return;BY(J.hub?.workspaceRoot?.trim()||J.hub?.cwd?.trim()||process.cwd())}async function NN($){await $.reconcileDeadSessions?.().catch(()=>{})}function wH($){try{let J=new s1;return J.init(),new o1(J,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(J){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),NH($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:J,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new EZ(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function PH($,J,Q){return new Z$({sessionService:Q??$.sessionService??wH($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:J,fetch:$.fetch})}async function wN($){if(Z4)return Z4;if(W4)return await W4;return W4=(async()=>{return Z4=wH($),await NN(Z4),Z4})().finally(()=>{W4=void 0}),await W4}async function kJ($){let J=g0($.distinctId);$.telemetry?.setDistinctId(J);let Q=qN($);if(PN(Q,$),Q==="remote"){let Z=$.remote?.endpoint?.trim();if(!Z)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Z}),new $J({endpoint:Z,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Q==="hub"){let Z=$.hub?.endpoint?.trim(),W=Z||await m8({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!W)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:W,explicitEndpoint:Z||void 0}),new b$({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Q==="auto"){let Z=await VZ({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Z){$.logger?.log("Using discovered local hub runtime host",{url:Z});let W=new b$({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await W.connect(),W}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),NH($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),PH($,J)}return PH($,J)}import{existsSync as SN,mkdirSync as CN,readFileSync as yN,writeFileSync as EN}from"node:fs";import{dirname as bN}from"node:path";import{FEATURE_FLAGS as SH,FeatureFlagDefaultValue as L7}from"@cline/shared";var hN=3600000,kN=604800000,CH=1;class j4{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??hN,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??kN,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let J=$??this.context.userId??null,Q=Date.now();if(Q-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===J)return}let Z=this.cacheInfo;this.cacheInfo={updateTime:Q,userId:J||null};try{let W=await this.provider.getAllFlagsAndPayloads({flagKeys:SH.length>0?SH:void 0,context:{...this.context,userId:J}});if(this.cacheInfo.userId!==J)return;this.cacheInfo.flagsPayload=W,this.rebuildCacheFromSnapshot(W),this.writePersistentCache()}catch(W){if(this.cacheInfo.userId!==J)return;throw this.cacheInfo=Z.updateTime?Z:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:W}),W}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((J)=>this.isFeatureFlagPayload(J));if(typeof $==="object")return Object.values($).every((J)=>this.isFeatureFlagPayload(J));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=Object.entries($).filter(([,Z])=>this.isFeatureFlagPayload(Z));if(J.length===0)return;let Q={};for(let[Z,W]of J)Q[Z]=W;return Q}readPersistentCache(){try{if(!this.cacheFilePath||!SN(this.cacheFilePath))return;let $=JSON.parse(yN(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let J=$;if(J.version!==CH||typeof J.updatedAt!=="number"||!Number.isFinite(J.updatedAt)||Date.now()-J.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:J.updatedAt,userId:J.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(J.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(J.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;CN(bN(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),J={version:CH,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};EN(this.cacheFilePath,`${JSON.stringify(J,null,2)}
704
+ `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let J=new Map;for(let Q of this.getReturnedFlagKeys($)){let Z=this.getFeatureFlag(Q);J.set(Q,Z??!1)}this.cache=J}getFeatureFlag($){try{let J=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Q=this.cacheInfo.flagsPayload?.featureFlags?.[$],Z=J??Q??L7[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Z)this.telemetry?.capture({event:k.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Q}});return Z}catch(J){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:J}),L7[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??L7[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,J){if(process.env.IS_TEST==="true")this.cache.set($,J)}async dispose(){await this.provider.dispose()}}class f4{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}q2();class _7{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,J,Q,Z,W,j,f,X,Y,V){this.clientName=J,this.runtimeAddress=Q,this.host=$,this.prepare=Z,this.capabilities=W,this.logger=j,this.telemetry=f,this.distinctId=X,this.featureFlags=Y,this.settings=HX($),this.pendingPrompts=BX($),this.automation=new JQ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=V?new S8({workspaceRoot:V.workspaceRoot??process.cwd(),specs:{cronSpecsDir:V.cronSpecsDir??V.cronDir,scope:f3(V.cronScope),workspaceRoot:V.workspaceRoot},runtimeHandlers:X3({host:$,getExtensionContext:()=>I4({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:V.dbPath,logger:V.logger,pollIntervalMs:V.pollIntervalMs,claimLeaseSeconds:V.claimLeaseSeconds,globalMaxConcurrency:V.globalMaxConcurrency,watcherDebounceMs:V.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let J=g0($.distinctId),Q=L0($.capabilities),Z={...$,capabilities:Q,distinctId:J},W=await kJ(Z),j=j3($.automation),f=$.featureFlags||new j4({provider:new f4,telemetry:$.telemetry,logger:$.logger,context:{distinctId:J,clientName:$.clientName}}),X=new _7(W,$.clientName,W.runtimeAddress,$.prepare,Q,$.logger,$.telemetry,J,f,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await X.automation.start();return X}async disposeSessionBootstrap($){let J=this.activeSessionBootstraps.get($);if(!J)return;this.activeSessionBootstraps.delete($),await Promise.resolve(J.dispose?.())}async start($){let J=AX($),Q=await this.prepare?.(J);try{let Z=Q?await Q.applyToStartSessionInput(J):J,W=await this.host.startSession(O9(Z,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>I4({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Q)if(await this.host.getSession(W.sessionId))this.activeSessionBootstraps.set(W.sessionId,Q);else await Promise.resolve(Q.dispose?.());return KX({input:Z,sessionId:W.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),W}catch(Z){throw await Promise.resolve(Q?.dispose?.()),Z}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let J=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(J.map((Q)=>this.disposeSessionBootstrap(Q)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await $Z(this.host,$);list=async($=200,J={})=>await this.listHistory({...J,limit:$});delete=async($)=>{let J=await this.host.deleteSession($);if(J)await this.disposeSessionBootstrap($);return J};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let J=$.start?O9($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>I4({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:J})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,J){return this.host.subscribe($,J)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}import{HookEventNameSchema as EH,HookEventPayloadSchema as bH,parseHookEventPayload as xJ,resolveHookSessionContext as uN}from"@cline/shared";import{z as m$}from"zod";import{spawn as IN}from"node:child_process";import{augmentNodeCommandForDebug as xN,withResolvedClineBuildEnv as gN}from"@cline/shared";function mN($){let J=$.trim();if(!J)return{};let Z=J.split(`
705
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function vN($,J){let Q=$ instanceof Error?$:Error(String($)),Z=Q,W=J.join(" ");if(Z.code==="EACCES")return Error(`Failed to execute hook command "${W}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${W}": ${Q.message}`)}async function cN($,J){let Q=$.stdin;if(!Q)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Z,W)=>{let j=(f)=>{Q.off("error",j);let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f)};Q.once("error",j),Q.end(J,(f)=>{if(Q.off("error",j),f){let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f);return}Z()})})}async function IJ($,J){let Q=xN(J.command,{env:J.env,debugRole:"hook"});if(!Array.isArray(Q)||Q.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Z=!!J.detached,W=IN(Q[0],Q.slice(1),{cwd:J.cwd,env:gN(J.env),stdio:Z?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Z,windowsHide:!0}),j=new Promise((A)=>{W.once("spawn",()=>{try{J.onSpawn?.({command:Q,pid:W.pid??void 0,detached:Z})}catch{}A()})}),f=new Promise((A,K)=>{W.once("error",(G)=>{K(vN(G,Q))})});if(await cN(W,JSON.stringify($)),Z){await Promise.race([j,f]),W.unref();return}if(!W.stdout||!W.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",Y="",V=!1,H;W.stdout.on("data",(A)=>{X+=A.toString()}),W.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,W.kill("SIGKILL")},J.timeoutMs);W.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=mN(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,f])}var dN=m$.object({contextModification:m$.string().optional(),cancel:m$.boolean().optional(),review:m$.boolean().optional(),errorMessage:m$.string().optional(),context:m$.string().optional(),overrideInput:m$.unknown().optional()}).passthrough();var lN=["agent","hook"];async function gJ($,J={}){let Q=J.command??lN;return await IJ($,{command:Q,cwd:J.cwd,env:J.env,detached:J.detached,timeoutMs:J.timeoutMs,onSpawn:J.onSpawn})}function hH($){return $ instanceof Error?$:Error(String($))}function pN($){if(!$||typeof $!=="object")return;let J=dN.safeParse($);if(!J.success)return;let Q=J.data;if(!(("cancel"in Q)||("review"in Q)||("context"in Q)||("contextModification"in Q)||("overrideInput"in Q)||("errorMessage"in Q)))return;let W=typeof Q.context==="string"?Q.context:typeof Q.contextModification==="string"?Q.contextModification:typeof Q.errorMessage==="string"&&Q.errorMessage.length>0?Q.errorMessage:void 0;return{cancel:typeof Q.cancel==="boolean"?Q.cancel:void 0,review:typeof Q.review==="boolean"?Q.review:void 0,context:W,overrideInput:Object.hasOwn(Q,"overrideInput")?Q.overrideInput:void 0}}function yH($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))if(typeof Z==="string")J[Q]=Z;else J[Q]=JSON.stringify(Z);return J}function _1($,J,Q){let Z=Q.env??process.env,W=Z.CLINE_USER_ID?.trim()||Z.USER?.trim()||"unknown",j=Q.cwd||process.cwd();return{clineVersion:Z.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:J.conversationId,sessionContext:uN(Q.sessionContext,{hookName:$,conversationId:J.conversationId,agentId:J.agentId,parentAgentId:J.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Q.workspaceInfo,userId:W,agent_id:J.agentId,parent_agent_id:J.parentAgentId}}function rN($){return{name:$.name,message:$.message,stack:$.stack}}function iN($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function nN($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function aN($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function sN($){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 oN($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}async function v$($,J){try{let Q=await gJ($,{command:J.command,cwd:J.cwd,env:J.env,detached:!0,onSpawn:J.onSpawn});J.onDispatch?.({payload:$,result:Q,detached:!0})}catch(Q){J.onDispatchError?.(hH(Q),$)}}function kH($={}){return{hooks:{beforeRun:async(X)=>{let Y=nN(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={..._1("agent_resume",Y,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await v$(H,$)}else{let H={..._1("agent_start",Y,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await v$(H,$)}return},beforeTool:async(X)=>{let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={..._1("tool_call",Y,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:yH(X.input)}};try{let H=await gJ(V,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:V,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return oN(pN(H?.parsedJson))}catch(H){$.onDispatchError?.(hH(H),V);return}},afterTool:async(X)=>{let Y=sN(X),V={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},H={..._1("tool_result",V,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:Y,postToolUse:{toolName:Y.name,parameters:yH(Y.input),result:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output),success:!Y.error,executionTimeMs:Y.durationMs}};await v$(H,$);return},afterRun:async({snapshot:X,result:Y})=>{let V={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(Y.status==="completed"){let A={..._1("agent_end",V,$),hookName:"agent_end",iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status},taskComplete:{taskMetadata:{}}};await v$(A,$);return}let H=Y.status==="aborted"||iN(Y.error?.message)?"agent_abort":"agent_error",B=H==="agent_error"?{..._1(H,V,$),hookName:H,iteration:Y.iterations,error:rN(Y.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{..._1(H,V,$),hookName:H,reason:Y.error?.message,taskCancel:{taskMetadata:{}}};await v$(B,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={..._1("prompt_submit",Y,$),hookName:"prompt_submit",userPromptSubmit:{prompt:aN(X.message.content),attachments:[]}};await v$(V,$)}},shutdown:async({agentId:X,conversationId:Y,parentAgentId:V,reason:H})=>{let B={..._1("session_shutdown",{agentId:X,conversationId:Y,parentAgentId:V},$),hookName:"session_shutdown",reason:H};await v$(B,$)}}}import{createSessionId as tN}from"@cline/shared";function v0($,J){return{version:$.version,requestId:$.requestId,ok:!0,payload:J}}function IH($,J,Q){return{version:$.version,requestId:$.requestId??tN("hubreq_"),ok:!1,error:{code:J,message:Q}}}class mJ{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return v0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return v0($,{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 v0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return v0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return v0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return v0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return v0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return v0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return v0($,{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 v0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return v0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return v0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return IH($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(J){return IH($,"schedule_command_failed",J instanceof Error?J.message:String(J))}}toCreateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:J}}toUpdateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:J}}}function cJ($){return $?new Date($).getTime():void 0}function eN($){let J=$.metadata?{...$.metadata}:void 0;if(J)delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions;return J}function vJ($){let J=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof J?.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:cJ($.nextRunAt),lastRunAt:cJ($.lastRunAt),createdBy:typeof J?.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:J?.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0,metadata:eN($)}}function $w($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function O7($,J){return{executionId:$.runId,scheduleId:J,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:cJ($.startedAt),endedAt:cJ($.completedAt),status:$w($.status),errorMessage:$.error}}class uJ{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new w8({dbPath:$.dbPath}),this.materializer=new T8({store:this.store}),this.runner=new M8({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(b9($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return vJ(this.store.createHubSchedule($))}getSchedule($){let J=this.store.getHubSchedule($);return J?vJ(J):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((J)=>vJ(J))}updateSchedule($,J){if(J.cronPattern!==void 0)b9(J.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let Z=J.workspaceRoot!==void 0?J.workspaceRoot.trim():Q.workspaceRoot;if((J.enabled??Q.enabled)&&!Z)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...J,scheduleId:$});return j?vJ(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;await this.runner.tick();let Q=this.store.getRun(J.runId)??J;return O7(Q,$)}triggerScheduleNowDetached($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;return this.runner.tick().catch(()=>{return}),O7(J,$)}listScheduleExecutions($){let J=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:J?.specId,limit:$.limit};return this.store.listRuns(Q).map((W)=>{let j=J??this.store.getSpec(W.specId);if(!j||j.source!=="hub-schedule")return;return O7(W,j.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let J=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(J.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,Z=0,W=0,j;for(let f of J){if(f.status==="success"||f.status==="completed")Q+=1;if(!j&&f.status!=="success"&&f.status!=="completed")j=f;if(f.startedAt&&f.endedAt)W+=f.endedAt-f.startedAt,Z+=1}return{totalRuns:J.length,successRate:Q/J.length,avgDurationSeconds:Z>0?W/Z/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let J=this.store.getSpec($.specId);if(!J||J.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:J.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:J.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+J.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let J={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(J).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,Z)=>String(Q.nextRunAt).localeCompare(String(Z.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:Z})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:Z}))}}rJ();import{resolveClineBuildEnv as Tw}from"@cline/shared";function Mw($,J){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${J} (${Q} event before socket open).`:`Failed to connect to hub at ${J}.`)}var qw="cline-hub-auth.";function Pw($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function Nw($,J){let Q=new URL($),Z=new URL(J);return Q.search="",Q.hash="",Z.search="",Z.hash="",Q.toString()===Z.toString()}function mH(){return Tw()==="production"?p1():D1()}async function ww($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=mH(),Z=await A0(Q.discoveryPath);if(Z?.url&&Nw($.toString(),Z.url))return Z.authToken;return}async function Sw($={}){let J=l1($);if(!Pw($)){let Q=mH(),Z=await A0(Q.discoveryPath);if(Z?.url)return Z.url}return F1(J.host,J.port,J.pathname)}async function vH($){return await new Promise((J,Q)=>{(async()=>{let Z=new URL($),W=await ww(Z);Z.hash="";let j=new WebSocket(Z.toString(),W?[`${qw}${W}`]:void 0),f=new Map,X=0;j.addEventListener("open",()=>{J({send(Y){let V=Y.requestId??`hub-client-${++X}`;return new Promise((H,B)=>{f.set(V,{resolve:H,reject:B});let A={kind:"command",envelope:{...Y,requestId:V}};j.send(JSON.stringify(A))})},close(){j.close()}})}),j.addEventListener("message",(Y)=>{let V=JSON.parse(String(Y.data));if(V.kind==="reply"&&V.envelope.requestId){let H=f.get(V.envelope.requestId);if(H)f.delete(V.envelope.requestId),H.resolve(V.envelope)}}),j.addEventListener("close",()=>{for(let Y of f.values())Y.reject(Error("Hub connection closed"));f.clear()}),j.addEventListener("error",(Y)=>{Q(Mw(Y,$))})})().catch(Q)})}async function ip($){try{return(await vH($)).close(),!0}catch{return!1}}async function np($,J){let Q=await Sw($),Z=await vH(Q);try{return await Z.send({version:J.version??"v1",clientId:J.clientId??"hub-client",...J})}finally{Z.close()}}function P7($){return $?JSON.parse(JSON.stringify($)):{}}function iJ($){let J=$?.session&&typeof $.session==="object"?$.session:void 0;if(!J)return;let Q=J.metadata&&typeof J.metadata==="object"?P7(J.metadata):void 0;return{sessionId:typeof J.sessionId==="string"?J.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function cH($,J){return $.error?.message??`hub command failed: ${J}`}function Cw($){let J=P7($);if(typeof J.error==="string"&&J.error.trim())return{...J,error:J.error.trim()};let Q=J.result&&typeof J.result==="object"?J.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...J,error:Q.text.trim()};let Z=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof Z?.message==="string"&&Z.message.trim())return{...J,error:Z.message.trim()};return J}function uH($){let J=$?.sessionId;return typeof J==="string"&&J.trim()?J.trim():void 0}function yw($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))throw Error("hub checkpoint restore returned no checkpoint");let Q=J;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function Ew($){let J=P7($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||uH(J)||"",eventType:"schedule.execution.completed",payload:J};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||uH(J)||"",eventType:"schedule.execution.failed",payload:J};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:J};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:J};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:J};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:J};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:J};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:J};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:J};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:J};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:Cw($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:J};default:return}}class bw{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new U1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let J=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Q=iJ(J.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,J,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:J.prompt,mode:J.config.mode,attachments:J.attachments,delivery:J.delivery,timeoutSeconds:J.config.timeoutSeconds},$,Q)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(O$(Q))return;throw Q}return iJ(J.payload)}async readMessages($){let J=$.trim();if(!J)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw Error(cH(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async restore($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Z=$.config,W=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,sessionConfig:{providerId:Z.provider,modelId:Z.model,apiKey:Z.apiKey,cwd:Z.cwd??Z.workspaceRoot,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Z.mode??"act",rules:Z.rules,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},metadata:{source:Z.source??"cli",provider:Z.provider,model:Z.model,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,prompt:void 0,interactive:Z.interactive!==!1},runtimeOptions:{mode:Z.mode,systemPrompt:Z.systemPrompt,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,autoApproveTools:Z.autoApproveTools,configExtensions:Z.configExtensions},modelSelection:{provider:Z.provider,model:Z.model,apiKey:Z.apiKey},toolPolicies:Z.toolPolicies}:{}},J);if(!W.ok)throw Error(cH(W,"session.restore"));let j=iJ(W.payload);if(Q&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let f=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,X=yw(W.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...f?{messages:f}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let J=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(J.payload?.sessions)?J.payload?.sessions:[]).map((Z)=>iJ({session:Z})).filter((Z)=>Boolean(Z?.sessionId))}async deleteSession($,J=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:J})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,J){let Q=new Set(($.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),Z=this.client.subscribe((W)=>{let j=Ew(W);if(!j)return;if(Q.size>0&&!Q.has(j.sessionId))return;J.onEvent?.(j)});return this.ensureMetadataApplied().catch((W)=>{J.onError?.(W instanceof Error?W:Error(String(W)))}),Z}streamTeamProgress($,J){let Q=this.client.subscribe((Z)=>{if(Z.event!=="team.progress"||!Z.payload)return;J.onProjection?.(Z.payload)});return this.ensureMetadataApplied().catch((Z)=>{J.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list");return Array.isArray(J.payload?.schedules)?J.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,J){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...J})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,J){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:J});return Array.isArray(Q.payload?.executions)?Q.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(J.payload?.upcoming)?J.payload?.upcoming:[]}}class hw{client;constructor($){this.client=new U1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let J=await this.client.command("session.list",{limit:$});return Array.isArray(J.payload?.sessions)?J.payload.sessions:[]}subscribeUI($){return this.client.subscribe((J)=>{switch(J.event){case"ui.notify":$.onNotify?.(J.payload);break;case"ui.show_window":$.onShowWindow?.(J.payload);break;case"hub.client.registered":$.onClientRegistered?.(J.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(J.payload??{});break;case"session.created":$.onSessionCreated?.(J.payload??{});break;case"session.updated":$.onSessionUpdated?.(J.payload??{});break;case"session.detached":$.onSessionDetached?.(J.payload??{});break}})}}import{normalizeProviderId as kw}from"@cline/llms";function Iw($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function xw($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function fr($={}){let J=new Z$({sessionService:new o1(new s1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||z0.CLI,interactive:!1,config:{providerId:kw(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:xw(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content)});if(!W)throw Error("local hub schedule runtime returned no turn result");return{result:Iw(W)}},async abortSession(Q){return await J.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}import{resolveClineBuildEnv as xB}from"@cline/shared";function gw($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Q)=>{if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text.trim();return""}).filter(Boolean).join(`
706
+ `).trim()||void 0}var dH=120,N7="...";function w7($){let J=$.trim();if(!J)return"";if(Buffer.byteLength(J,"utf8")<=dH)return J;let Q=dH-Buffer.byteLength(N7,"utf8");if(Q<=0)return N7;let Z="";for(let W of J){if(Buffer.byteLength(Z+W,"utf8")>Q)break;Z+=W}return`${Z}${N7}`}async function lH($){let J=$?.sessionId?.trim()||"unknown",Q=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,W=[...await d1(Q)].reverse().find((Y)=>Y.role==="assistant"),j=W?gw(W.content):void 0,f=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():f;return{title:`Task completed (${J})`,body:w7(j&&j.length>0?j:X.length>0?X:f),severity:"info"}}import{captureSdkError as oJ,createSessionId as KS}from"@cline/shared";import{createSessionId as uw}from"@cline/shared";import{createSessionId as cw}from"@cline/shared";function mw($){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 vw($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())J.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())J.parentAgentId=$.parentAgentId;if($.agentId?.trim())J.agentId=$.agentId;if($.conversationId?.trim())J.conversationId=$.conversationId;if($.messagesPath?.trim())J.messagesPath=$.messagesPath;if($.prompt?.trim())J.prompt=$.prompt;if($.provider?.trim())J.provider=$.provider;if($.model?.trim())J.model=$.model;if($.source?.trim())J.source=$.source;if(typeof $.pid==="number")J.pid=$.pid;return Object.keys(J).length>0?J:void 0}function nJ($,J,Q,Z){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:J?.createdByClientId??"hub",status:mw($.status),participants:J?[...J.participants.values()]:[],metadata:vw($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Q?{usage:{...Q}}:{},...Z?{aggregateUsage:{...Z}}:{}}}function c($,J){return{version:$.version,requestId:$.requestId,ok:!0,...J!==void 0?{payload:J}:{}}}function x($,J,Q){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:J,message:Q}}}function aJ($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function w0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function u$($,J,Q){return{version:"v1",event:$,eventId:cw("hevt_"),sessionId:Q,timestamp:Date.now(),payload:J}}async function c0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let Z=await $.sessionHost.getAccumulatedUsage?.(J);return nJ(Q,$.sessionState.get(J),Z?.usage,Z?.aggregateUsage)}async function u0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let[Z,W]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(J):[],$.sessionHost.getAccumulatedUsage?.(J)]);return i1({session:Q,messages:Z,usage:W?.usage,aggregateUsage:W?.aggregateUsage})}function sJ($,J,Q,Z,W={}){let j=$.sessionState.get(J);if(j){if(W.interactive!==void 0)j.interactive=W.interactive;if(!j.participants.has(Q))j.participants.set(Q,{clientId:Q,attachedAt:Date.now(),role:Z});return j}let f={createdByClientId:Q,interactive:W.interactive??!0,participants:new Map([[Q,{clientId:Q,attachedAt:Date.now(),role:Z}]])};return $.sessionState.set(J,f),f}async function S7($,J){let Q=uw("approval_"),Z=J.sessionId;if($.sessionState.get(Z)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Q,{sessionId:Z,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Q,sessionId:J.sessionId,agentId:J.agentId,conversationId:J.conversationId,iteration:J.iteration,toolCallId:J.toolCallId,toolName:J.toolName,inputJson:JSON.stringify(J.input??null),policy:J.policy},Z))})}function C7($,J,Q){let Z=$.pendingApprovals.get(J);if(!Z)return;return $.pendingApprovals.delete(J),Z.resolve(Q),{sessionId:Z.sessionId}}function y7($,J,Q){let Z=0;for(let[W,j]of[...$.pendingApprovals.entries()]){if(!J({approvalId:W,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(W),j.resolve({approved:!1,reason:Q}),$.publish($.buildEvent("approval.resolved",{approvalId:W,approved:!1,cancelled:!0,reason:Q},j.sessionId)),Z+=1}return Z}async function pH($,J){let Q=typeof J.payload?.approvalId==="string"?J.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Q))return x(J,"approval_not_found",`Unknown approval: ${Q}`);let W=typeof J.payload?.reason==="string"?J.payload.reason:J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)&&typeof J.payload.payload.reason==="string"?J.payload.payload.reason:void 0,j=J.payload?.approved===!0,f=C7($,Q,{approved:j,reason:W});if(!f)return x(J,"approval_not_found",`Unknown approval: ${Q}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Q,approved:j,reason:W},f.sessionId)),c(J,{approvalId:Q,approved:j})}import{createSessionId as pw}from"@cline/shared";function dw($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var rH={debug:10,info:20,warn:30,error:40,silent:50};function lw(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function g($,J,Q={}){if(rH[$]<rH[lw()])return;let Z=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:J,...Object.fromEntries(Object.entries(Q).map(([W,j])=>[W,dw(j)]).filter(([,W])=>W!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Z}`);return}console.log(`[hub] ${Z}`)}function E7($,J){let Q=J instanceof Error?J.stack||J.message:String(J);g("error",$,{error:Q})}async function iH($,J,Q,Z,W,j){let f=pw("capreq_"),X=performance.now();return g("info","capability.request.start",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W}),await new Promise((Y,V)=>{$.pendingCapabilityRequests.set(f,{sessionId:J,targetClientId:W,capabilityName:Q,onProgress:j,resolve:(H)=>{if(g(H.ok?"info":"warn","capability.request.end",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-X)}),!H.ok){V(Error(H.error||`Capability ${Q} was rejected by ${W}.`));return}Y(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:f,targetClientId:W,capabilityName:Q,payload:Z},J)),g("info","capability.request.published",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W})})}function nH($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return x(J,"capability_not_found",`Unknown capability request: ${Q}`);if((J.clientId?.trim()||"")!==Z.targetClientId)return x(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return x(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{};return Z.onProgress?.(j),c(J,{requestId:Q})}function W$($,J,Q){let Z=0;for(let[W,j]of[...$.pendingCapabilityRequests.entries()]){if(!J({requestId:W,...j}))continue;$.pendingCapabilityRequests.delete(W),g("warn","capability.request.cancelled",{requestId:W,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Q}),j.resolve({ok:!1,error:Q}),$.publish($.buildEvent("capability.resolved",{requestId:W,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Q},j.sessionId)),Z+=1}return Z}async function aH($,J){let Q=typeof J.payload?.sessionId==="string"?J.payload.sessionId.trim():J.sessionId?.trim()||"",Z=typeof J.payload?.capabilityName==="string"?J.payload.capabilityName.trim():"",W=typeof J.payload?.targetClientId==="string"?J.payload.targetClientId.trim():"";if(!Q||!Z||!W)return x(J,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{},f=await $.requestCapability(Q,Z,j,W);return c(J,f)}catch(j){return x(J,"capability_request_failed",j instanceof Error?j.message:String(j))}}function sH($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return x(J,"capability_not_found",`Unknown capability request: ${Q}`);let W=J.clientId?.trim()||"";if(W!==Z.targetClientId)return x(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return x(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);$.pendingCapabilityRequests.delete(Q);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:void 0,f=typeof J.payload?.error==="string"?J.payload.error:void 0,X=J.payload?.ok===!0;return g(X?"info":"warn","capability.respond",{requestId:Q,sessionId:Z.sessionId,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,error:f}),Z.resolve({ok:X,payload:j,error:f}),$.publish($.buildEvent("capability.resolved",{requestId:Q,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,payload:j,error:f},Z.sessionId)),c(J,{requestId:Q,ok:X})}import{createSessionId as rw}from"@cline/shared";function oH($,J){let Q=J.payload,Z=Q?.clientId?.trim()||J.clientId?.trim()||rw("client_");return $.clients.set(Z,{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,actorKind:Q?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Q?.transport??"native",capabilities:Q?.capabilities??[],metadata:Q?.metadata,workspaceContext:Q?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,connectedAt:Date.now()})),c(J,{clientId:Z})}function tH($,J){let Q=J.clientId?.trim(),Z=Q?$.clients.get(Q):void 0;if(!Q||!Z)return x(J,"client_not_found","Client is not registered with this hub.");let W=aJ(J.payload?.metadata);if(Z.lastSeenAt=Date.now(),W)Z.metadata=JSON.parse(JSON.stringify(W));return c(J)}function eH($,J,Q){let Z=J.clientId?.trim();if(Z)$.clients.delete(Z),Q(Z),$.publish($.buildEvent("hub.client.disconnected",{clientId:Z}));return c(J)}function $B($,J){return c(J,{clients:[...$.clients.values()]})}var iw=30000;function nw($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function aw($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function sw($,J,Q){let Z=Q instanceof Error&&Q.message.trim()?Q.message:`Unknown session: ${J}`;return x($,_8,Z)}function ow($){return $?$:void 0}function tw($){let J=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J);let Q=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Q&&Number.isFinite(Q)&&Q>0)return Math.floor(Q*1000);return}async function ew($,J,Q,Z){let W=performance.now(),j=!1,f={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q.sessionId,timeoutMs:Z},X=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-W);g("warn","run.heartbeat",{...f,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:J.requestId,elapsedMs:H,...Z?{timeoutMs:Z}:{}},Q.sessionId))},iw),Y=$.sessionHost.runTurn(Q);Y.then((H)=>{if(!j)return;g("warn","run.late_end",{...f,elapsedMs:Math.round(performance.now()-W),finishReason:H?.finishReason})},(H)=>{if(!j)return;g("error","run.late_error",{...f,elapsedMs:Math.round(performance.now()-W),error:H})});let V;try{if(!Z)return await Y;return await Promise.race([Y,new Promise((H,B)=>{V=setTimeout(()=>{let A=`Hub run ${J.command} timed out after ${Z}ms.`;j=!0,clearInterval(X),B(Error(A)),g("error","run.timeout",{...f,elapsedMs:Math.round(performance.now()-W)}),y7($,(K)=>K.sessionId===Q.sessionId,A),W$($,(K)=>K.sessionId===Q.sessionId,A),$.sessionHost.abort(Q.sessionId,A).catch((K)=>{g("error","run.timeout_abort_failed",{...f,error:K})})},Z)})])}finally{if(j=!0,clearInterval(X),V)clearTimeout(V)}}async function JB($,J){let Q=w0(J),Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.prompt==="string"?Z.prompt:typeof Z.input==="string"?Z.input:"";if(!W.trim())return x(J,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Q));let j=Z.attachments&&typeof Z.attachments==="object"&&!Array.isArray(Z.attachments)?Z.attachments:void 0,f=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,X=tw(Z);$.suppressNextTerminalEventBySession.set(Q,"run.start.reply");let Y;try{Y=await ew($,J,{sessionId:Q,prompt:W,mode:ow(Z.mode),delivery:Z.delivery==="queue"||Z.delivery==="steer"?Z.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:f,timeoutMs:X},X)}catch(H){if($.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q);if(O$(H))return sw(J,Q,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Q)),H}if(Y){let H=await u0($,Q),B=aw(Y);if($.publish($.buildEvent(nw(Y.finishReason),{reason:Y.finishReason,...B?{error:B}:{},result:Y,...H?{snapshot:H}:{}},Q)),$.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q)}else $.suppressNextTerminalEventBySession.delete(Q);let V=await u0($,Q);return c(J,Y||V?{...Y?{result:Y}:{},...V?{snapshot:V}:{}}:void 0)}async function QB($,J){let Q=w0(J),Z=typeof J.payload?.reason==="string"?J.payload.reason:"Run was aborted before pending approval or capability request was resolved.";y7($,(W)=>W.sessionId===Q,Z);try{await $.sessionHost.abort(Q,J.payload?.reason)}catch(W){g("warn","run.abort_failed",{command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q,error:W})}finally{W$($,(W)=>W.sessionId===Q,Z)}return c(J,{applied:!0})}async function ZB($,J){let Q=xJ(J.payload?.payload);if(!Q)return x(J,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Q),c(J,{applied:!0})}async function WB($,J){switch(J.type){case"chunk":return;case"agent_event":await $S($,J);return;case"hook":if(J.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:J.payload.toolName},J.payload.sessionId));else if(J.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:J.payload.toolName},J.payload.sessionId));return;case"team_progress":{let Q={type:"team_progress_projection",version:1,sessionId:J.payload.sessionId,summary:J.payload.summary,lastEvent:J.payload.lifecycle};$.publish($.buildEvent("team.progress",Q,J.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:J.payload.sessionId,prompts:J.payload.prompts},J.payload.sessionId));return;case"pending_prompt_submitted":{let Q={id:J.payload.id,prompt:J.payload.prompt,delivery:J.payload.delivery,attachmentCount:J.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:J.payload.sessionId,prompt:Q},J.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:J.payload.sessionId,snapshot:J.payload.snapshot},J.payload.sessionId));return;case"status":{let[Q,Z]=await Promise.all([c0($,J.payload.sessionId),u0($,J.payload.sessionId)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J.payload.sessionId));return}case"ended":await JS($,J);return;default:return}}async function $S($,J){let{sessionId:Q,event:Z}=J.payload;if(Z.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Z.iteration},Q));return}if(Z.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Z.iteration,hadToolCalls:Z.hadToolCalls,toolCallCount:Z.toolCallCount},Q));return}if(Z.type==="content_start"){if(Z.contentType==="text"&&typeof Z.text==="string"&&Z.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Z.text},Q));return}if(Z.contentType==="reasoning"){if(Z.redacted&&!Z.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Q));return}if(typeof Z.reasoning==="string"&&Z.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Z.reasoning,redacted:Z.redacted===!0},Q));return}if(Z.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Z.toolCallId,toolName:Z.toolName,input:Z.input},Q));return}}if(Z.type==="content_end"){switch(Z.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Z.text},Q));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Z.reasoning},Q));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Z.toolCallId,toolName:Z.toolName,output:Z.output,error:Z.error},Q));break}return}if(Z.type==="usage"){let W;try{W=await $.sessionHost.getAccumulatedUsage?.(Q)}catch{W=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Q,delta:{inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadTokens:Z.cacheReadTokens??0,cacheWriteTokens:Z.cacheWriteTokens??0,totalCost:Z.cost??0},totals:{inputTokens:Z.totalInputTokens,outputTokens:Z.totalOutputTokens,cacheReadTokens:Z.totalCacheReadTokens??0,cacheWriteTokens:Z.totalCacheWriteTokens??0,totalCost:Z.totalCost??0},usage:W?.usage,aggregateUsage:W?.aggregateUsage,agent:{kind:J.payload.teamRole==="teammate"?"teammate":Z.parentAgentId?"subagent":"lead",agentId:Z.agentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamAgentId:J.payload.teamAgentId,teamRole:J.payload.teamRole}},Q));return}if(Z.type==="done")$.publish($.buildEvent("agent.done",{reason:Z.reason,text:Z.text,iterations:Z.iterations,usage:Z.usage},Q))}async function JS($,J){let Q=$.suppressNextTerminalEventBySession.get(J.payload.sessionId),Z=Q===J.payload.reason||Q==="run.start.reply";if(Z)$.suppressNextTerminalEventBySession.delete(J.payload.sessionId);let[W,j]=await Promise.all([c0($,J.payload.sessionId),u0($,J.payload.sessionId)]);if(J.payload.reason==="completed"){let f=await lH(W);$.publish($.buildEvent("ui.notify",f,J.payload.sessionId))}if(Z)return;$.publish($.buildEvent(J.payload.reason==="aborted"?"run.aborted":J.payload.reason==="error"||J.payload.reason==="failed"?"run.failed":"run.completed",{reason:J.payload.reason,...j?{snapshot:j}:{}},J.payload.sessionId))}import{createSessionId as XB,parseRuntimeConfigExtensions as YB}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as xr,HUB_COMPACTION_CAPABILITY as gr,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as mr,HUB_HOOK_CAPABILITY_PREFIX as vr,HUB_MISTAKE_LIMIT_CAPABILITY as cr,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ur,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as dr,isHubToolExecutorName as QS}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as nr,HUB_COMPACTION_CAPABILITY as ar,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as sr,HUB_HOOK_CAPABILITY_PREFIX as or,HUB_MISTAKE_LIMIT_CAPABILITY as tr,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as er,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as $i}from"@cline/shared";var ZS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function d$($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function WS($,J){let Q=typeof $.name==="string"?$.name.trim():"",Z=typeof $.description==="string"?$.description:"",W=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=d$($.inputSchema);if(!Q||!Z||!j||!W||J.has(W))return;return J.add(W),{kind:"tool",capabilityName:W,name:Q,description:Z,inputSchema:j,...d$($.lifecycle)?{lifecycle:d$($.lifecycle)}:{}}}function h7($){if(!Array.isArray($))return[];let J=[],Q=new Set;for(let Z of $){if(!Z||typeof Z!=="object"||Array.isArray(Z))continue;let W=Z,j=W.kind,f=typeof W.capabilityName==="string"?W.capabilityName.trim():"";if(!f||Q.has(f))continue;if(j==="tool"){let X=WS(W,Q);if(X)J.push(X);continue}if(j==="toolExecutor"){let X=W.executor;if(!QS(X))continue;Q.add(f),J.push({kind:"toolExecutor",capabilityName:f,executor:X});continue}if(j==="hook"){let X=typeof W.name==="string"?W.name.trim():"";if(!X)continue;Q.add(f),J.push({kind:"hook",capabilityName:f,name:X});continue}if(j==="compaction"){Q.add(f),J.push({kind:"compaction",capabilityName:f,...d$(W.config)?{config:d$(W.config)}:{}});continue}if(j==="checkpoint"){Q.add(f),J.push({kind:"checkpoint",capabilityName:f,...d$(W.config)?{config:d$(W.config)}:{}});continue}if(j==="mistakeLimit"){Q.add(f),J.push({kind:"mistakeLimit",capabilityName:f});continue}if(j==="userInstructionService")Q.add(f),J.push({kind:"userInstructionService",capabilityName:f})}return J}function fB($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function jS($){return Object.hasOwn($,"update")?$.update:$}function H4($){return $.trim().replace(/^\/+/,"").toLowerCase()}function fS($){let J=($??[]).map(H4).filter(Boolean);return J.length>0?new Set(J):void 0}function XS($,J,Q){if(!Q)return!0;let Z=H4($),W=H4(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function b7($,J){let Q=fS(J);return $.records.skill.map((Z)=>({id:Z.id,name:Z.item.name,description:"description"in Z.item&&typeof Z.item.description==="string"?Z.item.description:void 0,disabled:Z.item.disabled===!0,skill:Z.item})).filter((Z)=>XS(Z.id,Z.name,Q))}function jB($,J){let Q=async(Z,W)=>{let j=H4(Z),X=b7($,J).filter((A)=>A.id===j||H4(A.name)===j||A.id.endsWith(`:${j}`)).filter((A)=>!A.disabled);if(X.length!==1)return X.length>1?`Skill "${Z}" is ambiguous. Use one of: ${X.map((A)=>A.id).join(", ")}`:`Skill "${Z}" not found.`;let Y=X[0].skill,V=W?.trim(),H=V?`
707
707
  <command-args>${V}</command-args>`:"",B=Y.description?.trim()?`Description: ${Y.description.trim()}
708
708
 
709
709
  `:"";return`<command-name>${Y.name}</command-name>${H}
710
710
  <command-instructions>
711
711
  ${B}${Y.instructions}
712
- </command-instructions>`};return Object.defineProperty(Q,"configuredSkills",{get:()=>b7($,J).map(({skill:Z,...W})=>W),enumerable:!0}),Q}function XS($,J,Q,Z){let W={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let f=await Z($,Q.capabilityName,{},J);if(f?.snapshot)W=f.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(f)=>[...W.records[f]],listRuntimeCommands:()=>[...W.runtimeCommands],resolveRuntimeSlashCommand:(f)=>{if(!f.startsWith("/")||f.length<2)return f;let Y=f.match(/^\/(\S+)/)?.[1];if(!Y)return f;let V=W.runtimeCommands.find((H)=>H.name===Y);return V?`${V.instructions}${f.slice(Y.length+1)}`:f},hasConfiguredSkills:(f)=>b7(W,f).some((X)=>!X.disabled),createSkillsExecutor:(f)=>ZB(W,f),createExtension:(f)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(f.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>$6(W.records.rule.map((Y)=>Y.item).filter((Y)=>Y.disabled!==!0))});if(f.registerSkillsTool)X.registerTool(H2(ZB(W,f.allowedSkillNames)));for(let Y of W.runtimeCommands.filter((V)=>V.kind==="skill"&&f.includeSkills||V.kind==="workflow"&&f.includeWorkflows))X.registerCommand({name:Y.name,description:Y.description,handler:(V)=>{let H=V.trim();return H?`${Y.instructions}
712
+ </command-instructions>`};return Object.defineProperty(Q,"configuredSkills",{get:()=>b7($,J).map(({skill:Z,...W})=>W),enumerable:!0}),Q}function YS($,J,Q,Z){let W={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let f=await Z($,Q.capabilityName,{},J);if(f?.snapshot)W=f.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(f)=>[...W.records[f]],listRuntimeCommands:()=>[...W.runtimeCommands],resolveRuntimeSlashCommand:(f)=>{if(!f.startsWith("/")||f.length<2)return f;let Y=f.match(/^\/(\S+)/)?.[1];if(!Y)return f;let V=W.runtimeCommands.find((H)=>H.name===Y);return V?`${V.instructions}${f.slice(Y.length+1)}`:f},hasConfiguredSkills:(f)=>b7(W,f).some((X)=>!X.disabled),createSkillsExecutor:(f)=>jB(W,f),createExtension:(f)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(f.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>$6(W.records.rule.map((Y)=>Y.item).filter((Y)=>Y.disabled!==!0))});if(f.registerSkillsTool)X.registerTool(H2(jB(W,f.allowedSkillNames)));for(let Y of W.runtimeCommands.filter((V)=>V.kind==="skill"&&f.includeSkills||V.kind==="workflow"&&f.includeWorkflows))X.registerCommand({name:Y.name,description:Y.description,handler:(V)=>{let H=V.trim();return H?`${Y.instructions}
713
713
 
714
- ${H}`:Y.instructions}})}})}}function YS($,J,Q,Z){let W=Q.map((j)=>[j.executor,async(...f)=>{let X=f.at(-1),Y=f.slice(0,-1);return(await Z($,j.capabilityName,{executor:j.executor,args:Y,context:WB(X)},J))?.result}]);return W.length>0?Object.fromEntries(W):void 0}function VS($,J,Q,Z){if(Q.length===0)return;return Q.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema,lifecycle:W.lifecycle,async execute(j,f){return(await Z($,W.capabilityName,{toolName:W.name,input:j,context:WB(f)},J,f.emitUpdate?(Y)=>{f.emitUpdate?.(WS(Y))}:void 0))?.result}}))}function HS($,J,Q,Z){let W=new Map(Q.map((f)=>[f.name,f])),j={};for(let f of QS){let X=W.get(f);if(!X)continue;j[f]=async(Y)=>{return(await Z($,X.capabilityName,{context:Y},J))?.control}}return Object.keys(j).length>0?j:void 0}function k7($){let J=$.contributions.filter((Y)=>Y.kind==="toolExecutor"),Q=$.contributions.filter((Y)=>Y.kind==="tool"),Z=$.contributions.filter((Y)=>Y.kind==="hook"),W=$.contributions.find((Y)=>Y.kind==="compaction"),j=$.contributions.find((Y)=>Y.kind==="checkpoint"),f=$.contributions.find((Y)=>Y.kind==="mistakeLimit"),X=$.contributions.find((Y)=>Y.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:YS($.sessionId,$.targetClientId,J,$.requestCapability),localRuntime:{...Z.length>0?{hooks:HS($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...Q.length>0?{extraTools:VS($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...W?{compaction:{...$.sessionConfig?.compaction??{},...W.config,compact:async(Y)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(Y)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...f?{onConsecutiveMistakeLimitReached:async(Y)=>{return(await $.requestCapability($.sessionId,f.capabilityName,{context:Y},$.targetClientId))?.result}}:{},...X?{userInstructionService:XS($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var XB="hubCapabilityOwnerClientId";function YB($,J){$[XB]=J}function BS($){let J=$?.[XB];return typeof J==="string"&&J.trim()?J.trim():void 0}async function VB($,J,Q){let Z=performance.now(),W={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:J.sessionId};g("info","session.create.begin",W);let j=J.payload&&typeof J.payload==="object"?J.payload:{},f=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},X=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,Y=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{};if(typeof X?.mode==="string")f.mode=X.mode;else if(typeof Y.mode==="string")f.mode=Y.mode;if(typeof X?.systemPrompt==="string")f.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")f.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)f.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)f.checkpointEnabled=!0;let V=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},H=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!H)return g("warn","session.create.invalid",{...W,reason:"missing_workspace_root"}),x(J,"invalid_session_create","session.create requires workspaceRoot or cwd");let B=J.clientId?.trim()||"hub-client",A=h7(Y.clientContributions);if(g("info","session.create.contributions_parsed",{...W,clientId:B,workspaceRoot:H,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:A.length}),A.length>0)YB(f,B);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||jB(),R=fB(Y.configExtensions);g("info","session.create.runtime_build.begin",{...W,sessionId:G,configExtensionCount:R?.length??0});let D=k7({sessionId:G,targetClientId:B,contributions:A,sessionConfig:X,requestCapability:$.requestCapability});g("info","session.create.start_session.begin",{...W,sessionId:G,provider:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),model:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub")});let U=await $.sessionHost.startSession({source:typeof f.source==="string"?f.source:void 0,interactive:f.interactive!==!1,sessionMetadata:Object.keys(f).length>0?f:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Q},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),modelId:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub"),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:void 0),cwd:X?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():H),workspaceRoot:X?.workspaceRoot??H,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof f.teamName==="string"?f.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});g("info","session.create.start_session.end",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z),hasImmediateResult:!!U.result}),sJ($,U.sessionId,B,"creator",{interactive:f.interactive!==!1}),g("info","session.create.read_records.begin",{...W,sessionId:U.sessionId});let[F,O]=await Promise.all([c0($,U.sessionId),u0($,U.sessionId)]);if(g("info","session.create.read_records.end",{...W,sessionId:U.sessionId,hasSession:!!F,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Z)}),F)$.publish($.buildEvent("session.created",{session:F,...O?{snapshot:O}:{}},U.sessionId));return g("info","session.create.reply",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z)}),c(J,{session:F,...O?{snapshot:O}:{}})}async function HB($,J,Q){let Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.sessionId==="string"?Z.sessionId.trim():J.sessionId?.trim()||"",j=Z.checkpointRunCount;if(!W)return x(J,"invalid_restore","session.restore requires a session id");let f=Z.restore&&typeof Z.restore==="object"?Z.restore:{},X=f.messages!==!1;if(typeof j!=="number")return x(J,"invalid_restore","checkpointRunCount must be a positive integer");try{let Y=Z.sessionConfig&&typeof Z.sessionConfig==="object"?JSON.parse(JSON.stringify(Z.sessionConfig)):void 0;if(X&&!Y)return x(J,"invalid_restore","sessionConfig is required when restore.messages is true");let V=Z.runtimeOptions&&typeof Z.runtimeOptions==="object"?Z.runtimeOptions:{},H=Z.metadata&&typeof Z.metadata==="object"?JSON.parse(JSON.stringify(Z.metadata)):{};if(typeof Y?.mode==="string")H.mode=Y.mode;else if(typeof V.mode==="string")H.mode=V.mode;if(typeof Y?.systemPrompt==="string")H.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")H.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)H.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)H.checkpointEnabled=!0;let B=Z.modelSelection&&typeof Z.modelSelection==="object"?Z.modelSelection:{},A=J.clientId?.trim()||"hub-client",K=h7(V.clientContributions);if(K.length>0)YB(H,A);let R=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||jB(),D=fB(V.configExtensions),U=k7({sessionId:R,targetClientId:A,contributions:K,sessionConfig:Y,requestCapability:$.requestCapability}),O=await new E2().restoreCheckpoint({sessionId:W,checkpointRunCount:j,restore:{messages:f.messages,workspace:f.workspace,omitCheckpointMessageFromSession:f.omitCheckpointMessageFromSession===!0},start:Y,cwd:typeof Y?.cwd==="string"&&Y.cwd.trim()||typeof Y?.workspaceRoot==="string"&&Y.workspaceRoot.trim()||void 0,getSession:(M)=>$.sessionHost.getSession(M),readMessages:(M)=>$.sessionHost.readSessionMessages(M),buildStartInput:(M)=>{if(M.restoredCheckpointMetadata)H.checkpoint=M.restoredCheckpointMetadata;let P=typeof Z.workspaceRoot==="string"&&Z.workspaceRoot.trim()?Z.workspaceRoot.trim():typeof Z.cwd==="string"&&Z.cwd.trim()?Z.cwd.trim():M.sourceSession.workspaceRoot||M.sourceSession.cwd;return{source:typeof H.source==="string"?H.source:void 0,interactive:H.interactive!==!1,sessionMetadata:{...H,restoredFromSessionId:W,restoredCheckpointRunCount:j},initialMessages:M.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:D,...U.localRuntime},capabilities:{toolExecutors:U.toolExecutors,requestToolApproval:Q},config:{...Y??{},sessionId:R,providerId:Y?.providerId??(typeof B.provider==="string"?B.provider:M.sourceSession.provider),modelId:Y?.modelId??(typeof B.model==="string"?B.model:M.sourceSession.model),apiKey:Y?.apiKey??(typeof B.apiKey==="string"?B.apiKey:""),cwd:Y?.cwd??M.plan.cwd,workspaceRoot:Y?.workspaceRoot??P,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof H.teamName==="string"?H.teamName:void 0)},toolPolicies:Z.toolPolicies&&typeof Z.toolPolicies==="object"&&!Array.isArray(Z.toolPolicies)?JSON.parse(JSON.stringify(Z.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(M)=>$.sessionHost.startSession(M),getStartedSessionId:(M)=>M.sessionId,readRestoredSession:(M)=>$.sessionHost.getSession(M)});if(!X)return c(J,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return x(J,"restore_failed","Checkpoint restore did not start a session");sJ($,T.sessionId,A,"creator",{interactive:H.interactive!==!1});let[L,z]=await Promise.all([c0($,T.sessionId),u0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...z?{snapshot:z}:{}},T.sessionId));return c(J,{session:L,...z?{snapshot:z}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(Y){if(Y instanceof a0)return x(J,Y.code,Y.code==="session_not_found"?`Unknown session: ${W}`:Y.message);return x(J,"restore_failed",Y instanceof Error?Y.message:String(Y))}}async function BB($,J){let Q=w0(J);if(!Q)return x(J,"invalid_session_attach","session.attach requires a session id");sJ($,Q,J.clientId?.trim()||"hub-client","participant");let Z=await c0($,Q);if(Z)$.publish($.buildEvent("session.attached",{session:Z},Q));return Z?c(J,{session:Z}):x(J,"session_not_found",`Unknown session: ${Q}`)}async function AB($,J){let Q=w0(J);if(!Q)return x(J,"invalid_session_detach","session.detach requires a session id");let Z=J.clientId?.trim()||"hub-client",[W]=await Promise.all([c0($,Q)]),j=BS(W?.metadata)??Z,f=$.sessionState.get(Q);if(f){if(f.participants.delete(Z),f.createdByClientId===Z)f.createdByClientId=j;if(f.participants.size===0)$.sessionState.delete(Q)}W$($,(V)=>V.sessionId===Q&&V.targetClientId===Z,`Capability owner client ${Z} detached before request was resolved.`);let[X,Y]=await Promise.all([c0($,Q),u0($,Q)]);return $.publish($.buildEvent("session.detached",X?{session:X,...Y?{snapshot:Y}:{},clientId:Z}:{clientId:Z},Q)),c(J)}async function KB($,J){let Q=w0(J),Z=J.payload?.includeSnapshot===!0,[W,j]=await Promise.all([c0($,Q),Z?u0($,Q):Promise.resolve(void 0)]);return W?c(J,{session:W,...j?{snapshot:j}:{}}):x(J,"session_not_found",`Unknown session: ${Q}`)}async function GB($,J){let Q=w0(J);if(!Q)return x(J,"invalid_session_id","session.messages requires a session id");if(!await c0($,Q))return x(J,"session_not_found",`Unknown session: ${Q}`);let W=await $.sessionHost.readSessionMessages(Q);return c(J,{sessionId:Q,messages:W})}async function FB($,J){let Q=typeof J.payload?.limit==="number"?J.payload.limit:200,W=(await $.sessionHost.listSessions(Q)).map((j)=>nJ(j,$.sessionState.get(j.sessionId)));return c(J,{sessions:W})}async function DB($,J){let Q=w0(J),Z=aJ(J.payload?.metadata),W=await $.sessionHost.updateSession(Q,{metadata:Z}),[j,f]=await Promise.all([c0($,Q),u0($,Q)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...f?{snapshot:f}:{}},Q));return{version:J.version,requestId:J.requestId,ok:W.updated,payload:{updated:W.updated,session:j,...f?{snapshot:f}:{}}}}async function UB($,J){let Q=w0(J),Z=await $.sessionHost.deleteSession(Q);return $.sessionState.delete(Q),c(J,{deleted:Z})}async function RB($,J){let Q=w0(J),Z=$.sessionHost.pendingPrompts;if(!Z)return x(J,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.list({sessionId:Q});return c(J,{sessionId:Q,prompts:W})}async function zB($,J){let Q=w0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=typeof J.payload?.prompt==="string"?J.payload.prompt:void 0,j=J.payload?.delivery==="queue"||J.payload?.delivery==="steer"?J.payload.delivery:void 0,f=$.sessionHost.pendingPrompts;if(!f)return x(J,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await f.update({sessionId:Q,promptId:Z,prompt:W,delivery:j});return c(J,X)}async function LB($,J){let Q=w0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=$.sessionHost.pendingPrompts;if(!W)return x(J,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await W.delete({sessionId:Q,promptId:Z});return c(J,j)}function _B($){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 KS=new Set(["skills","workflows","rules","tools","mcp"]);function I7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function B4($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="string")throw Error(`settings payload '${J}' must be a string.`);return Q}function GS($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="boolean")throw Error(`settings payload '${J}' must be a boolean.`);return Q}function OB($){if($===void 0)return{};if(!I7($))throw Error("settings.list payload must be an object.");return{cwd:B4($,"cwd"),workspaceRoot:B4($,"workspaceRoot"),availabilityContext:I7($.availabilityContext)?$.availabilityContext:void 0}}function FS($){if(!I7($))throw Error("settings.toggle payload must be an object.");let{type:J}=$;if(typeof J!=="string"||!KS.has(J))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...OB($),type:J,id:B4($,"id"),path:B4($,"path"),name:B4($,"name"),enabled:GS($,"enabled")}}class tJ{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=AS("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new Z$({sessionService:new o1(new s1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(J)=>this.publish(J),buildEvent:u$,requestCapability:(J,Q,Z,W,j)=>pH(this.ctx,J,Q,Z,W,j)},this.schedules=new uJ({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(J,Q)=>{let Z=J==="schedule.execution.completed"?"schedule.execution_completed":J==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Z)return;this.publish(u$(Z,Q&&typeof Q==="object"?Q:void 0))}}),this.scheduleCommands=new mJ(this.schedules),this.settings=$.settingsService??new _2,$.cronOptions)this.cronService=new S8({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((J)=>{QB(this.ctx,J).catch((Q)=>{E7("session event handling failed",Q),oJ(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Q,severity:"error",handled:!0,context:{eventType:J.type,sessionId:J.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())C7(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(W$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let J=await this.dispatchCommand($);return this.captureFailedReply($,J),J}catch(J){throw oJ(this.options.telemetry,{component:"core",operation:"hub.command",error:J,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),J}}async dispatchCommand($){switch($.command){case"client.register":return aH(this.ctx,$);case"client.update":return sH(this.ctx,$);case"client.unregister":return oH(this.ctx,$,(J)=>{this.listeners.delete(J),this.detachClientFromSessions(J)});case"client.list":return tH(this.ctx,$);case"session.create":return await VB(this.ctx,$,(J)=>S7(this.ctx,J));case"session.restore":return await HB(this.ctx,$,(J)=>S7(this.ctx,J));case"session.attach":return await BB(this.ctx,$);case"session.detach":return await AB(this.ctx,$);case"session.get":return await KB(this.ctx,$);case"session.messages":return await GB(this.ctx,$);case"session.list":return await FB(this.ctx,$);case"session.update":return await DB(this.ctx,$);case"session.pending_prompts":return await RB(this.ctx,$);case"session.update_pending_prompt":return await zB(this.ctx,$);case"session.remove_pending_prompt":return await LB(this.ctx,$);case"session.delete":return await UB(this.ctx,$);case"session.hook":return await JB(this.ctx,$);case"run.start":case"session.send_input":return await eH(this.ctx,$);case"run.abort":return await $B(this.ctx,$);case"capability.request":return await iH(this.ctx,$);case"approval.respond":return await dH(this.ctx,$);case"capability.respond":return nH(this.ctx,$);case"capability.progress":return rH(this.ctx,$);case"ui.notify":return this.publish(u$("ui.notify",$.payload??{})),c($);case"ui.show_window":return this.publish(u$("ui.show_window",$.payload??{})),c($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let J=await this.scheduleCommands.handleCommand($);if(J.ok){let Q=_B($.command);if(Q)this.publish(u$(Q,J.payload))}return J}}}captureFailedReply($,J){if(J.ok||!J.error||!DS(J.error.code))return;oJ(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(J.error.message),severity:J.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:J.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let J=await this.settings.list(OB($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:J instanceof Error?J.message:String(J)}}}}async handleSettingsToggle($){try{let J=await this.settings.toggle(FS($.payload));return this.publish(u$("settings.changed",{types:J.changedTypes,snapshot:J.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J.snapshot,changedTypes:J.changedTypes}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:J instanceof Error?J.message:String(J)}}}}subscribe($,J,Q){let Z=this.listeners.get($)??new Set,W={sessionId:Q?.sessionId,listener:J};return Z.add(W),this.listeners.set($,Z),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(W),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[J,Q]of this.sessionState.entries())if(Q.participants.delete($),Q.participants.size===0)this.sessionState.delete(J);W$(this.ctx,(J)=>J.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let J of this.listeners.values())for(let Q of J){if(Q.sessionId&&Q.sessionId!==$.sessionId)continue;try{Q.listener($)}catch(Z){E7(`listener threw while publishing ${$.event}`,Z),oJ(this.options.telemetry,{component:"core",operation:"hub.publish",error:Z,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function DS($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as LS}from"node:crypto";import _S from"node:http";import OS from"node:net";import{URL as qB}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as PB,HUB_CAPABILITIES as TS,isHubProtocolCompatible as MS,MAX_CLIENT_HUB_PROTOCOL_VERSION as NB,MIN_CLIENT_HUB_PROTOCOL_VERSION as wB}from"@cline/shared";import{WebSocketServer as qS}from"ws";import{captureSdkError as TB,HUB_COMMAND_SLOW_LOG_MS as US,resolveHubCommandTimeoutMs as RS,safeJsonParse as zS}from"@cline/shared";function x7($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function MB($,J,Q){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:J,message:Q}}}class g7{transport;telemetry;constructor($,J){this.transport=$;this.telemetry=J}attach($){let J=new Map,Q=new Set,Z=!1,W=(Y)=>{try{$.send(JSON.stringify(Y))}catch(V){console.error(`[hub] failed to send websocket frame: ${V instanceof Error?V.stack||V.message:String(V)}`)}},j=(Y)=>{W({kind:"event",envelope:Y})},f=async(Y)=>{try{let V=JSON.parse(Y.data);switch(V.kind){case"command":{let H=performance.now(),B=!1,A=x7(V);g("info","command.start",A);let K=setTimeout(()=>{if(B)return;g("warn","command.slow",{...A,elapsedMs:Math.round(performance.now()-H)})},US),G=this.transport.command(V.envelope);G.then((T)=>{if(!B)return;g(T.ok?"warn":"error","command.late_end",{...A,elapsedMs:Math.round(performance.now()-H),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!B)return;g("error","command.late_error",{...A,elapsedMs:Math.round(performance.now()-H),error:T})});let R=!1,D,U,F=RS(V.envelope.command,V.envelope.timeoutMs);try{U=F===null?await G:await Promise.race([G,new Promise((T)=>{D=setTimeout(()=>{R=!0,TB(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${V.envelope.command} did not complete within ${F}ms.`),severity:"error",handled:!0,context:{...A,timeoutMs:F}}),T(MB(V,"hub_command_timeout",`Hub command ${V.envelope.command} did not complete within ${F}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${V.envelope.requestId}.`))},F)})])}catch(T){if(clearTimeout(K),D)clearTimeout(D);throw T}if(B=R,clearTimeout(K),D)clearTimeout(D);let O=Math.round(performance.now()-H);if(R)g("error","command.timeout",{...A,durationMs:O,timeoutMs:F});else g(U.ok?"info":"warn","command.end",{...A,durationMs:O,ok:U.ok,errorCode:U.error?.code,errorMessage:U.error?.message});if(V.envelope.command==="client.register"&&U.ok){let L=(V.envelope.payload??{}).clientId?.trim()||V.envelope.clientId?.trim();if(L)Q.add(L)}else if(V.envelope.command==="client.unregister"&&U.ok){let T=V.envelope.clientId?.trim();if(T)Q.delete(T)}W({kind:"reply",envelope:U});break}case"stream.subscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;if(J.has(H))break;let B=await this.transport.subscribe(V.clientId,j,{sessionId:V.sessionId});J.set(H,B);break}case"stream.unsubscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;J.get(H)?.(),J.delete(H);break}case"reply":case"event":break}}catch(V){let H=typeof Y.data==="string"?zS(Y.data):void 0;if(!H||H.kind!=="command"){g("error","rejected malformed websocket frame",{error:V});return}g("error","command.error",{...x7(H),error:V}),TB(this.telemetry,{component:"core",operation:"hub.websocket_command",error:V,severity:"error",handled:!0,context:x7(H)}),W({kind:"reply",envelope:MB(H,"command_failed",V instanceof Error?V.message:"Unknown hub error")})}},X=()=>{if(Z)return;Z=!0;for(let Y of J.values())Y();J.clear();for(let Y of Q)this.transport.command({version:"v1",command:"client.unregister",clientId:Y});Q.clear(),$.removeEventListener("message",f),$.removeEventListener("close",X)};return $.addEventListener("message",f),$.addEventListener("close",X),X}}class m7{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,J,Q){return this.transport.subscribe($,J,Q)}}function PS($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();return String($)}function NS($){return{send(J){$.send(J)},addEventListener(J,Q){if(J==="message"){$.on("message",(Z)=>{Q({data:PS(Z)})});return}$.on("close",Q)},removeEventListener(){}}}function wS($){try{$.write(`HTTP/1.1 400 Bad Request\r
714
+ ${H}`:Y.instructions}})}})}}function VS($,J,Q,Z){let W=Q.map((j)=>[j.executor,async(...f)=>{let X=f.at(-1),Y=f.slice(0,-1);return(await Z($,j.capabilityName,{executor:j.executor,args:Y,context:fB(X)},J))?.result}]);return W.length>0?Object.fromEntries(W):void 0}function HS($,J,Q,Z){if(Q.length===0)return;return Q.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema,lifecycle:W.lifecycle,async execute(j,f){return(await Z($,W.capabilityName,{toolName:W.name,input:j,context:fB(f)},J,f.emitUpdate?(Y)=>{f.emitUpdate?.(jS(Y))}:void 0))?.result}}))}function BS($,J,Q,Z){let W=new Map(Q.map((f)=>[f.name,f])),j={};for(let f of ZS){let X=W.get(f);if(!X)continue;j[f]=async(Y)=>{return(await Z($,X.capabilityName,{context:Y},J))?.control}}return Object.keys(j).length>0?j:void 0}function k7($){let J=$.contributions.filter((Y)=>Y.kind==="toolExecutor"),Q=$.contributions.filter((Y)=>Y.kind==="tool"),Z=$.contributions.filter((Y)=>Y.kind==="hook"),W=$.contributions.find((Y)=>Y.kind==="compaction"),j=$.contributions.find((Y)=>Y.kind==="checkpoint"),f=$.contributions.find((Y)=>Y.kind==="mistakeLimit"),X=$.contributions.find((Y)=>Y.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:VS($.sessionId,$.targetClientId,J,$.requestCapability),localRuntime:{...Z.length>0?{hooks:BS($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...Q.length>0?{extraTools:HS($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...W?{compaction:{...$.sessionConfig?.compaction??{},...W.config,compact:async(Y)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(Y)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...f?{onConsecutiveMistakeLimitReached:async(Y)=>{return(await $.requestCapability($.sessionId,f.capabilityName,{context:Y},$.targetClientId))?.result}}:{},...X?{userInstructionService:YS($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var VB="hubCapabilityOwnerClientId";function HB($,J){$[VB]=J}function AS($){let J=$?.[VB];return typeof J==="string"&&J.trim()?J.trim():void 0}async function BB($,J,Q){let Z=performance.now(),W={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:J.sessionId};g("info","session.create.begin",W);let j=J.payload&&typeof J.payload==="object"?J.payload:{},f=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},X=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,Y=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{};if(typeof X?.mode==="string")f.mode=X.mode;else if(typeof Y.mode==="string")f.mode=Y.mode;if(typeof X?.systemPrompt==="string")f.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")f.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)f.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)f.checkpointEnabled=!0;let V=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},H=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!H)return g("warn","session.create.invalid",{...W,reason:"missing_workspace_root"}),x(J,"invalid_session_create","session.create requires workspaceRoot or cwd");let B=J.clientId?.trim()||"hub-client",A=h7(Y.clientContributions);if(g("info","session.create.contributions_parsed",{...W,clientId:B,workspaceRoot:H,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:A.length}),A.length>0)HB(f,B);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||XB(),R=YB(Y.configExtensions);g("info","session.create.runtime_build.begin",{...W,sessionId:G,configExtensionCount:R?.length??0});let D=k7({sessionId:G,targetClientId:B,contributions:A,sessionConfig:X,requestCapability:$.requestCapability});g("info","session.create.start_session.begin",{...W,sessionId:G,provider:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),model:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub")});let U=await $.sessionHost.startSession({source:typeof f.source==="string"?f.source:void 0,interactive:f.interactive!==!1,sessionMetadata:Object.keys(f).length>0?f:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Q},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),modelId:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub"),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:void 0),cwd:X?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():H),workspaceRoot:X?.workspaceRoot??H,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof f.teamName==="string"?f.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});g("info","session.create.start_session.end",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z),hasImmediateResult:!!U.result}),sJ($,U.sessionId,B,"creator",{interactive:f.interactive!==!1}),g("info","session.create.read_records.begin",{...W,sessionId:U.sessionId});let[F,O]=await Promise.all([c0($,U.sessionId),u0($,U.sessionId)]);if(g("info","session.create.read_records.end",{...W,sessionId:U.sessionId,hasSession:!!F,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Z)}),F)$.publish($.buildEvent("session.created",{session:F,...O?{snapshot:O}:{}},U.sessionId));return g("info","session.create.reply",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z)}),c(J,{session:F,...O?{snapshot:O}:{}})}async function AB($,J,Q){let Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.sessionId==="string"?Z.sessionId.trim():J.sessionId?.trim()||"",j=Z.checkpointRunCount;if(!W)return x(J,"invalid_restore","session.restore requires a session id");let f=Z.restore&&typeof Z.restore==="object"?Z.restore:{},X=f.messages!==!1;if(typeof j!=="number")return x(J,"invalid_restore","checkpointRunCount must be a positive integer");try{let Y=Z.sessionConfig&&typeof Z.sessionConfig==="object"?JSON.parse(JSON.stringify(Z.sessionConfig)):void 0;if(X&&!Y)return x(J,"invalid_restore","sessionConfig is required when restore.messages is true");let V=Z.runtimeOptions&&typeof Z.runtimeOptions==="object"?Z.runtimeOptions:{},H=Z.metadata&&typeof Z.metadata==="object"?JSON.parse(JSON.stringify(Z.metadata)):{};if(typeof Y?.mode==="string")H.mode=Y.mode;else if(typeof V.mode==="string")H.mode=V.mode;if(typeof Y?.systemPrompt==="string")H.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")H.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)H.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)H.checkpointEnabled=!0;let B=Z.modelSelection&&typeof Z.modelSelection==="object"?Z.modelSelection:{},A=J.clientId?.trim()||"hub-client",K=h7(V.clientContributions);if(K.length>0)HB(H,A);let R=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||XB(),D=YB(V.configExtensions),U=k7({sessionId:R,targetClientId:A,contributions:K,sessionConfig:Y,requestCapability:$.requestCapability}),O=await new E2().restoreCheckpoint({sessionId:W,checkpointRunCount:j,restore:{messages:f.messages,workspace:f.workspace,omitCheckpointMessageFromSession:f.omitCheckpointMessageFromSession===!0},start:Y,cwd:typeof Y?.cwd==="string"&&Y.cwd.trim()||typeof Y?.workspaceRoot==="string"&&Y.workspaceRoot.trim()||void 0,getSession:(M)=>$.sessionHost.getSession(M),readMessages:(M)=>$.sessionHost.readSessionMessages(M),buildStartInput:(M)=>{if(M.restoredCheckpointMetadata)H.checkpoint=M.restoredCheckpointMetadata;let P=typeof Z.workspaceRoot==="string"&&Z.workspaceRoot.trim()?Z.workspaceRoot.trim():typeof Z.cwd==="string"&&Z.cwd.trim()?Z.cwd.trim():M.sourceSession.workspaceRoot||M.sourceSession.cwd;return{source:typeof H.source==="string"?H.source:void 0,interactive:H.interactive!==!1,sessionMetadata:{...H,restoredFromSessionId:W,restoredCheckpointRunCount:j},initialMessages:M.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:D,...U.localRuntime},capabilities:{toolExecutors:U.toolExecutors,requestToolApproval:Q},config:{...Y??{},sessionId:R,providerId:Y?.providerId??(typeof B.provider==="string"?B.provider:M.sourceSession.provider),modelId:Y?.modelId??(typeof B.model==="string"?B.model:M.sourceSession.model),apiKey:Y?.apiKey??(typeof B.apiKey==="string"?B.apiKey:""),cwd:Y?.cwd??M.plan.cwd,workspaceRoot:Y?.workspaceRoot??P,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof H.teamName==="string"?H.teamName:void 0)},toolPolicies:Z.toolPolicies&&typeof Z.toolPolicies==="object"&&!Array.isArray(Z.toolPolicies)?JSON.parse(JSON.stringify(Z.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(M)=>$.sessionHost.startSession(M),getStartedSessionId:(M)=>M.sessionId,readRestoredSession:(M)=>$.sessionHost.getSession(M)});if(!X)return c(J,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return x(J,"restore_failed","Checkpoint restore did not start a session");sJ($,T.sessionId,A,"creator",{interactive:H.interactive!==!1});let[L,z]=await Promise.all([c0($,T.sessionId),u0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...z?{snapshot:z}:{}},T.sessionId));return c(J,{session:L,...z?{snapshot:z}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(Y){if(Y instanceof a0)return x(J,Y.code,Y.code==="session_not_found"?`Unknown session: ${W}`:Y.message);return x(J,"restore_failed",Y instanceof Error?Y.message:String(Y))}}async function KB($,J){let Q=w0(J);if(!Q)return x(J,"invalid_session_attach","session.attach requires a session id");sJ($,Q,J.clientId?.trim()||"hub-client","participant");let Z=await c0($,Q);if(Z)$.publish($.buildEvent("session.attached",{session:Z},Q));return Z?c(J,{session:Z}):x(J,"session_not_found",`Unknown session: ${Q}`)}async function GB($,J){let Q=w0(J);if(!Q)return x(J,"invalid_session_detach","session.detach requires a session id");let Z=J.clientId?.trim()||"hub-client",[W]=await Promise.all([c0($,Q)]),j=AS(W?.metadata)??Z,f=$.sessionState.get(Q);if(f){if(f.participants.delete(Z),f.createdByClientId===Z)f.createdByClientId=j;if(f.participants.size===0)$.sessionState.delete(Q)}W$($,(V)=>V.sessionId===Q&&V.targetClientId===Z,`Capability owner client ${Z} detached before request was resolved.`);let[X,Y]=await Promise.all([c0($,Q),u0($,Q)]);return $.publish($.buildEvent("session.detached",X?{session:X,...Y?{snapshot:Y}:{},clientId:Z}:{clientId:Z},Q)),c(J)}async function FB($,J){let Q=w0(J),Z=J.payload?.includeSnapshot===!0,[W,j]=await Promise.all([c0($,Q),Z?u0($,Q):Promise.resolve(void 0)]);return W?c(J,{session:W,...j?{snapshot:j}:{}}):x(J,"session_not_found",`Unknown session: ${Q}`)}async function DB($,J){let Q=w0(J);if(!Q)return x(J,"invalid_session_id","session.messages requires a session id");if(!await c0($,Q))return x(J,"session_not_found",`Unknown session: ${Q}`);let W=await $.sessionHost.readSessionMessages(Q);return c(J,{sessionId:Q,messages:W})}async function UB($,J){let Q=typeof J.payload?.limit==="number"?J.payload.limit:200,W=(await $.sessionHost.listSessions(Q)).map((j)=>nJ(j,$.sessionState.get(j.sessionId)));return c(J,{sessions:W})}async function RB($,J){let Q=w0(J),Z=aJ(J.payload?.metadata),W=await $.sessionHost.updateSession(Q,{metadata:Z}),[j,f]=await Promise.all([c0($,Q),u0($,Q)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...f?{snapshot:f}:{}},Q));return{version:J.version,requestId:J.requestId,ok:W.updated,payload:{updated:W.updated,session:j,...f?{snapshot:f}:{}}}}async function zB($,J){let Q=w0(J),Z=await $.sessionHost.deleteSession(Q);return $.sessionState.delete(Q),c(J,{deleted:Z})}async function LB($,J){let Q=w0(J),Z=$.sessionHost.pendingPrompts;if(!Z)return x(J,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.list({sessionId:Q});return c(J,{sessionId:Q,prompts:W})}async function _B($,J){let Q=w0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=typeof J.payload?.prompt==="string"?J.payload.prompt:void 0,j=J.payload?.delivery==="queue"||J.payload?.delivery==="steer"?J.payload.delivery:void 0,f=$.sessionHost.pendingPrompts;if(!f)return x(J,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await f.update({sessionId:Q,promptId:Z,prompt:W,delivery:j});return c(J,X)}async function OB($,J){let Q=w0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=$.sessionHost.pendingPrompts;if(!W)return x(J,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await W.delete({sessionId:Q,promptId:Z});return c(J,j)}function TB($){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 GS=new Set(["skills","workflows","rules","tools","mcp"]);function I7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function B4($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="string")throw Error(`settings payload '${J}' must be a string.`);return Q}function FS($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="boolean")throw Error(`settings payload '${J}' must be a boolean.`);return Q}function MB($){if($===void 0)return{};if(!I7($))throw Error("settings.list payload must be an object.");return{cwd:B4($,"cwd"),workspaceRoot:B4($,"workspaceRoot"),availabilityContext:I7($.availabilityContext)?$.availabilityContext:void 0}}function DS($){if(!I7($))throw Error("settings.toggle payload must be an object.");let{type:J}=$;if(typeof J!=="string"||!GS.has(J))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...MB($),type:J,id:B4($,"id"),path:B4($,"path"),name:B4($,"name"),enabled:FS($,"enabled")}}class tJ{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=KS("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new Z$({sessionService:new o1(new s1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(J)=>this.publish(J),buildEvent:u$,requestCapability:(J,Q,Z,W,j)=>iH(this.ctx,J,Q,Z,W,j)},this.schedules=new uJ({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(J,Q)=>{let Z=J==="schedule.execution.completed"?"schedule.execution_completed":J==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Z)return;this.publish(u$(Z,Q&&typeof Q==="object"?Q:void 0))}}),this.scheduleCommands=new mJ(this.schedules),this.settings=$.settingsService??new _2,$.cronOptions)this.cronService=new S8({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((J)=>{WB(this.ctx,J).catch((Q)=>{E7("session event handling failed",Q),oJ(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Q,severity:"error",handled:!0,context:{eventType:J.type,sessionId:J.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())C7(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(W$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let J=await this.dispatchCommand($);return this.captureFailedReply($,J),J}catch(J){throw oJ(this.options.telemetry,{component:"core",operation:"hub.command",error:J,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),J}}async dispatchCommand($){switch($.command){case"client.register":return oH(this.ctx,$);case"client.update":return tH(this.ctx,$);case"client.unregister":return eH(this.ctx,$,(J)=>{this.listeners.delete(J),this.detachClientFromSessions(J)});case"client.list":return $B(this.ctx,$);case"session.create":return await BB(this.ctx,$,(J)=>S7(this.ctx,J));case"session.restore":return await AB(this.ctx,$,(J)=>S7(this.ctx,J));case"session.attach":return await KB(this.ctx,$);case"session.detach":return await GB(this.ctx,$);case"session.get":return await FB(this.ctx,$);case"session.messages":return await DB(this.ctx,$);case"session.list":return await UB(this.ctx,$);case"session.update":return await RB(this.ctx,$);case"session.pending_prompts":return await LB(this.ctx,$);case"session.update_pending_prompt":return await _B(this.ctx,$);case"session.remove_pending_prompt":return await OB(this.ctx,$);case"session.delete":return await zB(this.ctx,$);case"session.hook":return await ZB(this.ctx,$);case"run.start":case"session.send_input":return await JB(this.ctx,$);case"run.abort":return await QB(this.ctx,$);case"capability.request":return await aH(this.ctx,$);case"approval.respond":return await pH(this.ctx,$);case"capability.respond":return sH(this.ctx,$);case"capability.progress":return nH(this.ctx,$);case"ui.notify":return this.publish(u$("ui.notify",$.payload??{})),c($);case"ui.show_window":return this.publish(u$("ui.show_window",$.payload??{})),c($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let J=await this.scheduleCommands.handleCommand($);if(J.ok){let Q=TB($.command);if(Q)this.publish(u$(Q,J.payload))}return J}}}captureFailedReply($,J){if(J.ok||!J.error||!US(J.error.code))return;oJ(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(J.error.message),severity:J.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:J.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let J=await this.settings.list(MB($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:J instanceof Error?J.message:String(J)}}}}async handleSettingsToggle($){try{let J=await this.settings.toggle(DS($.payload));return this.publish(u$("settings.changed",{types:J.changedTypes,snapshot:J.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J.snapshot,changedTypes:J.changedTypes}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:J instanceof Error?J.message:String(J)}}}}subscribe($,J,Q){let Z=this.listeners.get($)??new Set,W={sessionId:Q?.sessionId,listener:J};return Z.add(W),this.listeners.set($,Z),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(W),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[J,Q]of this.sessionState.entries())if(Q.participants.delete($),Q.participants.size===0)this.sessionState.delete(J);W$(this.ctx,(J)=>J.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let J of this.listeners.values())for(let Q of J){if(Q.sessionId&&Q.sessionId!==$.sessionId)continue;try{Q.listener($)}catch(Z){E7(`listener threw while publishing ${$.event}`,Z),oJ(this.options.telemetry,{component:"core",operation:"hub.publish",error:Z,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function US($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as _S}from"node:crypto";import OS from"node:http";import TS from"node:net";import{URL as NB}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as wB,HUB_CAPABILITIES as MS,isHubProtocolCompatible as qS,MAX_CLIENT_HUB_PROTOCOL_VERSION as SB,MIN_CLIENT_HUB_PROTOCOL_VERSION as CB}from"@cline/shared";import{WebSocketServer as PS}from"ws";import{captureSdkError as qB,HUB_COMMAND_SLOW_LOG_MS as RS,resolveHubCommandTimeoutMs as zS,safeJsonParse as LS}from"@cline/shared";function x7($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function PB($,J,Q){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:J,message:Q}}}class g7{transport;telemetry;constructor($,J){this.transport=$;this.telemetry=J}attach($){let J=new Map,Q=new Set,Z=!1,W=(Y)=>{try{$.send(JSON.stringify(Y))}catch(V){console.error(`[hub] failed to send websocket frame: ${V instanceof Error?V.stack||V.message:String(V)}`)}},j=(Y)=>{W({kind:"event",envelope:Y})},f=async(Y)=>{try{let V=JSON.parse(Y.data);switch(V.kind){case"command":{let H=performance.now(),B=!1,A=x7(V);g("info","command.start",A);let K=setTimeout(()=>{if(B)return;g("warn","command.slow",{...A,elapsedMs:Math.round(performance.now()-H)})},RS),G=this.transport.command(V.envelope);G.then((T)=>{if(!B)return;g(T.ok?"warn":"error","command.late_end",{...A,elapsedMs:Math.round(performance.now()-H),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!B)return;g("error","command.late_error",{...A,elapsedMs:Math.round(performance.now()-H),error:T})});let R=!1,D,U,F=zS(V.envelope.command,V.envelope.timeoutMs);try{U=F===null?await G:await Promise.race([G,new Promise((T)=>{D=setTimeout(()=>{R=!0,qB(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${V.envelope.command} did not complete within ${F}ms.`),severity:"error",handled:!0,context:{...A,timeoutMs:F}}),T(PB(V,"hub_command_timeout",`Hub command ${V.envelope.command} did not complete within ${F}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${V.envelope.requestId}.`))},F)})])}catch(T){if(clearTimeout(K),D)clearTimeout(D);throw T}if(B=R,clearTimeout(K),D)clearTimeout(D);let O=Math.round(performance.now()-H);if(R)g("error","command.timeout",{...A,durationMs:O,timeoutMs:F});else g(U.ok?"info":"warn","command.end",{...A,durationMs:O,ok:U.ok,errorCode:U.error?.code,errorMessage:U.error?.message});if(V.envelope.command==="client.register"&&U.ok){let L=(V.envelope.payload??{}).clientId?.trim()||V.envelope.clientId?.trim();if(L)Q.add(L)}else if(V.envelope.command==="client.unregister"&&U.ok){let T=V.envelope.clientId?.trim();if(T)Q.delete(T)}W({kind:"reply",envelope:U});break}case"stream.subscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;if(J.has(H))break;let B=await this.transport.subscribe(V.clientId,j,{sessionId:V.sessionId});J.set(H,B);break}case"stream.unsubscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;J.get(H)?.(),J.delete(H);break}case"reply":case"event":break}}catch(V){let H=typeof Y.data==="string"?LS(Y.data):void 0;if(!H||H.kind!=="command"){g("error","rejected malformed websocket frame",{error:V});return}g("error","command.error",{...x7(H),error:V}),qB(this.telemetry,{component:"core",operation:"hub.websocket_command",error:V,severity:"error",handled:!0,context:x7(H)}),W({kind:"reply",envelope:PB(H,"command_failed",V instanceof Error?V.message:"Unknown hub error")})}},X=()=>{if(Z)return;Z=!0;for(let Y of J.values())Y();J.clear();for(let Y of Q)this.transport.command({version:"v1",command:"client.unregister",clientId:Y});Q.clear(),$.removeEventListener("message",f),$.removeEventListener("close",X)};return $.addEventListener("message",f),$.addEventListener("close",X),X}}class m7{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,J,Q){return this.transport.subscribe($,J,Q)}}function NS($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();return String($)}function wS($){return{send(J){$.send(J)},addEventListener(J,Q){if(J==="message"){$.on("message",(Z)=>{Q({data:NS(Z)})});return}$.on("close",Q)},removeEventListener(){}}}function SS($){try{$.write(`HTTP/1.1 400 Bad Request\r
715
715
  Connection: close\r
716
716
  Content-Length: 0\r
717
717
  \r
718
- `),$.end()}catch{$.destroy()}}function SS($){try{$.write(`HTTP/1.1 401 Unauthorized\r
718
+ `),$.end()}catch{$.destroy()}}function CS($){try{$.write(`HTTP/1.1 401 Unauthorized\r
719
719
  Connection: close\r
720
720
  Content-Length: 0\r
721
721
  \r
722
- `),$.end()}catch{$.destroy()}}function v7($,J){if(!$||!J)return!1;let Q=Buffer.from($,"utf8"),Z=Buffer.from(J,"utf8");return Q.length===Z.length&&LS(Q,Z)}function SB($,J){let Q=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Z=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",W=`Failed to start hub server on ${J.host}:${J.port}${J.pathname}: ${Z}`,j=Error(Q?`${W} (${Q})`:W);if(Q)$.code=Q,j.code=Q;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
723
- Caused by: ${$.stack}`;return j}async function CS($){return await new Promise((J,Q)=>{let Z=OS.createServer();Z.once("error",Q),Z.listen(0,$,()=>{let W=Z.address();if(!W||typeof W==="string"){Z.close(()=>Q(Error("Failed to resolve free port")));return}let j=W.port;Z.close((f)=>{if(f){Q(f);return}J(j)})})})}function yS($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var c7=new Map,CB="cline-hub-auth.",ES=30000;function bB($){return Array.isArray($)?$.join(","):$??""}function yB($){return $===32||$===9}function EB($){let J=bB($).trim(),Q="bearer";if(J.length<=6||J.slice(0,6).toLowerCase()!=="bearer"||!yB(J.charCodeAt(6)))return null;let Z=7;while(Z<J.length&&yB(J.charCodeAt(Z)))Z+=1;return J.slice(Z).trim()||null}function bS($){for(let J of bB($).split(",")){let Q=J.trim();if(Q.startsWith(CB))return Q.slice(CB.length).trim()||null}return null}async function u7($){let J=$.owner??w$(),Q=$.host??"127.0.0.1",Z=$.pathname??"/hub",W=$.port??n6(),j=W===0?await CS(Q):W,f=j,X=F1(Q,j,Z),Y=eX(),V=tX(),H=new tJ($);await H.start();let B=new g7(new m7(H),$.telemetry),A=new Set,K=new Date().toISOString(),G={protocolVersion:PB,minClientProtocolVersion:wB,maxClientProtocolVersion:NB,capabilities:TS,coreVersion:I8.version,buildId:Y,pid:process.pid,startedAt:K},R=new Set,D,U,F=async()=>{if(U)return U;return U=(async()=>{if(D)clearInterval(D),D=void 0;for(let z of R)z.terminate?.();R.clear();for(let z of A)z();if(A.clear(),await new Promise((z,M)=>{T.close((P)=>{if(P){M(P);return}z()})}),await new Promise((z,M)=>{O.close((P)=>{if(P){M(P);return}z()})}),await H.stop(),(await A0(J.discoveryPath))?.url===X)await n0(J.discoveryPath)})(),U},O=_S.createServer((L,z)=>{if((L.url??"/")==="/health"){let P=JSON.stringify({ok:!0,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,coreVersion:G.coreVersion,host:Q,port:f,url:X});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(P);return}if((L.url??"/")==="/status"){if(!v7(EB(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}let P=JSON.stringify({hubId:H.getHubId(),...G,authToken:V,host:Q,port:f,url:X,updatedAt:new Date().toISOString()});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(P);return}if((L.url??"/")==="/version"){z.statusCode=200,z.setHeader("content-type","application/json"),z.end(JSON.stringify(G));return}if(new qB(L.url??"/",`http://${Q}:${f}`).pathname==="/shutdown"&&L.method==="POST"){if(!v7(EB(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}z.statusCode=202,z.setHeader("content-type","application/json"),z.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{F()});return}z.statusCode=404,z.end("Not found")}),T=new qS({noServer:!0});D=setInterval(()=>{for(let L of R){if(L.isAlive===!1){try{L.terminate?.()}catch{}R.delete(L);continue}L.isAlive=!1;try{L.ping?.()}catch{try{L.terminate?.()}catch{}R.delete(L)}}},ES),O.on("upgrade",(L,z,M)=>{if(new qB(L.url??"/",`http://${Q}:${f}`).pathname!==Z){z.destroy();return}if(!v7(bS(L.headers["sec-websocket-protocol"]),V)){SS(z);return}try{T.handleUpgrade(L,z,M,(C)=>{let m=C;m.isAlive=!0,m.on("pong",()=>{m.isAlive=!0}),R.add(m);let n=B.attach(NS(C));A.add(n),C.once("close",()=>{R.delete(m),n(),A.delete(n)})})}catch{wS(z)}});try{await new Promise((L,z)=>{O.once("error",(M)=>{z(SB(M,{host:Q,port:j,pathname:Z}))}),O.listen(j,Q,()=>{let M=O.address();if(!M||typeof M==="string"){z(SB(Error("Failed to resolve hub port"),{host:Q,port:j,pathname:Z}));return}f=M.port,X=F1(Q,f,Z),L()})})}catch(L){if(D)clearInterval(D),D=void 0;throw await H.stop().catch(()=>{return}),L}return await $Y(J.discoveryPath,{hubId:H.getHubId(),protocolVersion:PB,minClientProtocolVersion:wB,maxClientProtocolVersion:NB,capabilities:[...G.capabilities],coreVersion:I8.version,buildId:Y,authToken:V,host:Q,port:f,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:Q,port:f,url:X,authToken:V,close:F}}async function hB($){let J=$.owner??w$(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.host??"127.0.0.1",W=$.port??n6(),j=$.pathname??"/hub",f=F1(Z,W,j),X=J.discoveryPath,Y=(H)=>{if(!Q)O2(H.url,H.authToken);return H},V=c7.get(X);if(V){let H=await V;if(H.url===f)return Y({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await JY(J.discoveryPath,async()=>{let H=await A0(J.discoveryPath);if(H?.url&&(H.url===f||$.allowPortFallback===!0)){let K=await S$(H.url,{authToken:H.authToken});if(K?.url&&MS(K).compatible&&await r1(K.url,{authToken:H.authToken}))return Y({url:K.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await n0(J.discoveryPath);let A=async(K)=>{let G=u7({...K,owner:J});c7.set(X,G);try{let R=await G;return Y({server:R,url:R.url,authToken:R.authToken,action:"started"})}catch(R){throw c7.delete(X),R}};try{return await A($)}catch(K){if(!$.allowPortFallback||!yS(K))throw K;return await A({...$,port:0})}})}function IB(){return kB()==="production"?p1():D1()}function hS($){return kB()!=="production"&&!$}async function Qn($){let J=l1({host:$.host,port:$.port,pathname:$.pathname});return await u7({...$,...J,owner:IB()})}async function Zn($){let J=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=l1({host:$.host,port:$.port,pathname:$.pathname});return await hB({...$,...Q,allowPortFallback:$.allowPortFallback??hS(J),owner:IB()})}eJ();import{buildRemoteConfigSessionBlobUploadMetadata as gB,clearRemoteConfigSessionBlobUpload as kS,createClineTelemetryServiceConfig as IS,createSessionId as xS,createRemoteConfigSessionMessagesArtifactUploader as gS,prepareRemoteConfigRuntime as mS,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as mB,readRemoteConfigSessionBlobUploadMetadata as vS,registerRemoteConfigSessionBlobUpload as vB}from"@cline/shared";function cS($,J){let Q=$.telemetry||J.telemetryService?{...J.telemetryService??{},...$.telemetry??{}}:void 0;if(!Q)return;return c$(IS(Q)).telemetry}function uS(){let $=gS();return{async uploadMessagesFile(J){await $.uploadMessagesFile(J)}}}async function dS($){let J=await mS($),Q=cS(J,$),Z=[J.pluginDefinition],W=J.claims?.subject,j=gB(J.bundle?.remoteConfig,W),f;return{prepared:J,extensions:Z,telemetry:Q,applyToStartSessionInput(X){let Y=X.config.extensions??[],V=X.config.telemetry,H=j?X.config.sessionId?.trim()||xS():X.config.sessionId;if(H&&j)f=H;let B=H&&j?vB(H,J.bundle?.remoteConfig,W):void 0,A=B?{...X.sessionMetadata??{},[mB]:B}:X.sessionMetadata;return{...X,...A?{sessionMetadata:A}:{},config:{...X.config,...H?{sessionId:H}:{},extensions:[...Y,...Z],telemetry:Q??V}}},async dispose(){if(f)kS(f)}}}import{mkdir as lS,readFile as pS,unlink as rS,writeFile as iS}from"node:fs/promises";import{join as cB}from"node:path";function nS($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function aS($){return new Promise((J)=>setTimeout(J,$))}async function d7($){try{await rS($)}catch{}}async function sS($,J={}){let Q=J.approvalDir?.trim(),Z=J.sessionId?.trim();if(!Q||!Z)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await lS(Q,{recursive:!0});let W=nS(`${$.toolCallId}`),j=cB(Q,`${Z}.request.${W}.json`),f=cB(Q,`${Z}.decision.${W}.json`),X=J.nowIso??(()=>new Date().toISOString());await iS(j,`${JSON.stringify({requestId:W,sessionId:Z,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
724
- `,"utf8");let Y=J.timeoutMs??300000,V=J.pollIntervalMs??200,H=Date.now();while(Date.now()-H<Y){try{let B=await pS(f,"utf8"),A=JSON.parse(B),K={approved:A.approved===!0,reason:typeof A.reason==="string"?A.reason:void 0};return await Promise.all([d7(f),d7(j)]),K}catch{}await aS(V)}return await d7(j),{approved:!1,reason:"Tool approval request timed out"}}p0();import{existsSync as oS,mkdirSync as tS,readFileSync as eS,writeFileSync as $C}from"node:fs";import{dirname as dB,isAbsolute as JC,relative as QC,resolve as uB}from"node:path";function l$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $5($,J){let Q=QC(uB($),uB(J));return Q===""||!Q.startsWith("..")&&!JC(Q)}function l7($){if(!oS($))return{mcpServers:{}};try{let J=JSON.parse(eS($,"utf8"));if(l$(J))return J}catch(J){throw Error(`Invalid MCP settings at "${$}": ${J instanceof Error?J.message:String(J)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function p7($){if(l$($.mcpServers))return{...$.mcpServers};return{}}function r7($,J,Q){tS(dB($),{recursive:!0}),$C($,`${JSON.stringify({...J,mcpServers:Q},null,2)}
725
- `,"utf8")}function lB($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((J)=>J.trim()).filter((J)=>J.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((J)=>J.trim()).filter((J)=>J.length>0))]}}function Q5($){if(!l$($))return;let J=$.metadata;return l$(J)?J:void 0}function J5($,J){let Q=Q5($);if(!Q||Q.source!=="plugin")return!1;let Z=typeof Q.pluginName==="string"?Q.pluginName:typeof Q.plugin==="string"?Q.plugin:void 0,W=typeof Q.pluginPath==="string"?Q.pluginPath:void 0;if(J.pluginName&&Z===J.pluginName){if(!J.pluginPath||W===J.pluginPath)return!0}if(W&&J.pluginPath&&(W===J.pluginPath||$5(J.pluginPath,W)||$5(W,J.pluginPath)))return!0;if(Z&&J.pluginNames?.some((j)=>j===Z))return!0;if(W&&J.pluginPaths?.some((j)=>W===j||$5(j,W)||$5(W,j)))return!0;return!1}function ZC($){let J=l$($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:dB($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...J,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function WC($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let J=await W2({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Q=[],Z=[],W=(J.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of J.extensions??[]){let f=j.__clinePluginPath;if(!f)continue;if(!j.setup){Q.push({pluginName:j.name,pluginPath:f});continue}let X=[],Y={registerTool:(V)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(V)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');X.push(V)}};try{await j.setup(Y,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(V){W.push({pluginPath:f,pluginName:j.name,message:V instanceof Error?V.message:String(V)});continue}Q.push({pluginName:j.name,pluginPath:f});for(let V of X)Z.push({pluginName:j.name,pluginPath:f,server:{...V,metadata:{...V.metadata??{},source:"plugin",pluginName:j.name,pluginPath:f}}})}return{plugins:Q,servers:Z,failures:W}}finally{await J.shutdown().catch(()=>{})}}async function jC($){let J=$.settingsPath??H0(),Q={mutations:[],failures:[]},Z;try{Z=await WC($)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}Q.failures.push(...Z.failures);let W;try{W=l7(J)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}let j=p7(W),f=new Map,X=new Map;for(let V of Z.plugins)f.set(V.pluginPath,new Set),X.set(V.pluginPath,V.pluginName);let Y=R9(Z.servers.map((V)=>({server:V.server,owner:V,ownerLabel:V.pluginName})));for(let V of Y){let H=V.owner;if(!f.has(H.pluginPath))f.set(H.pluginPath,new Set);if(V.name)f.get(H.pluginPath)?.add(V.name);if(!V.registration){Q.mutations.push({name:V.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:V.loadError??"invalid MCP server registration"});continue}let B=j[V.registration.name];if(B!==void 0){if(!J5(B,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[V.registration.name]=ZC({registration:V.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:l$(B)?B:void 0}),Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:B===void 0?"created":"updated"})}for(let[V,H]of Object.entries(j)){let B=Q5(H),A=typeof B?.pluginPath==="string"?B.pluginPath:"",K=f.get(A);if(K&&J5(H,{pluginPath:A})&&!K.has(V))delete j[V],Q.mutations.push({name:V,pluginName:typeof B?.pluginName==="string"?B.pluginName:X.get(A)??"plugin",pluginPath:A,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Q.mutations.some((V)=>V.action!=="skipped"))try{r7(J,W,j)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)})}return Q}function fC($){let J=$.settingsPath??H0(),Q;try{Q=l7(J)}catch{return[]}let Z=p7(Q),W=lB($),j=[];for(let[f,X]of Object.entries(Z)){if(!l$(X)||!J5(X,W))continue;let Y=Q5(X);Z[f]={...X,disabled:!0},j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"disabled"})}if(j.length>0)r7(J,Q,Z);return j}function i7($){let J=$.settingsPath??H0(),Q;try{Q=l7(J)}catch{return[]}let Z=p7(Q),W=lB($),j=[];for(let[f,X]of Object.entries(Z)){if(!J5(X,W))continue;let Y=Q5(X);delete Z[f],j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"removed"})}if(j.length>0)r7(J,Q,Z);return j}p0();import{existsSync as I2,readdirSync as XC,readFileSync as YC,rmdirSync as VC,rmSync as HC,statSync as BC}from"node:fs";import{basename as d0,dirname as j$,extname as AC,isAbsolute as KC,join as O1,relative as GC,resolve as k2,sep as n7}from"node:path";import{discoverPluginModulePaths as FC,resolvePluginConfigSearchPaths as DC}from"@cline/shared/storage";var e7="_installed",UC="package",RC=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function a7($){return $.trim().toLowerCase()}function s0($,J){let Q=J?.trim();if(!Q)return;$.add(Q)}function zC($){return $.replace(/-[0-9a-f]{12}$/i,"")}function s7($){let J=AC($);return J?$.slice(0,-J.length):$}function o7($){if(!I2($))return;try{let J=JSON.parse(YC($,"utf8"));return typeof J.name==="string"?J.name.trim():void 0}catch{return}}function $W($,J){let Q=GC(J,$);return Q===""||!Q.startsWith("..")&&!KC(Q)}function pB($){let Q=k2($).split(n7),Z=Q.lastIndexOf(e7);if(Z<0)return;let W=Q[Z+1];if(!W)return;let j=RC.get(W)??1,f=Z+2+j;if(Q.length<f)return;let X=Q.slice(0,f).join(n7)||n7;return I2(X)?X:void 0}function Z5($){try{return XC($,{withFileTypes:!0})}catch{return[]}}function LC($){let J=O1($,e7);if(!I2(J))return[];let Q=[];for(let Z of Z5(J)){if(!Z.isDirectory())continue;let W=O1(J,Z.name);if(Z.name==="git"){for(let j of Z5(W)){if(!j.isDirectory())continue;let f=O1(W,j.name);for(let X of Z5(f))if(X.isDirectory())Q.push(O1(f,X.name))}continue}for(let j of Z5(W))if(j.isDirectory())Q.push(O1(W,j.name))}return Q.sort((Z,W)=>Z.localeCompare(W))}function rB($){try{return FC($)}catch{return[]}}function t7($){let J=rB($),Q=new Set;s0(Q,d0($)),s0(Q,zC(d0($))),s0(Q,o7(O1($,"package.json"))),s0(Q,o7(O1($,UC,"package.json")));for(let Z of J)s0(Q,d0(Z)),s0(Q,s7(d0(Z)));return{installPath:$,entryPaths:J,names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!0}}function _C($,J){let Q=k2($),Z=J.find((f)=>$W(Q,f));if(!Z)return;let W=j$(Q);while(W!==Z&&W!==j$(W)){if(I2(O1(W,"package.json")))return W;W=j$(W)}let j=d0(Q);if((j==="index.ts"||j==="index.js")&&j$(Q)!==Z)return j$(Q);return Q}function iB($,J){let Q=_C($,J);if(!Q)return;let Z=new Set;return s0(Z,d0($)),s0(Z,s7(d0($))),s0(Z,d0(Q)),s0(Z,s7(d0(Q))),s0(Z,o7(O1(Q,"package.json"))),{installPath:Q,entryPaths:[$],names:[...Z].sort((W,j)=>W.localeCompare(j)),installed:!1}}function OC($){let J=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return DC(J).filter((Q)=>I2(Q))}function TC($){let J=new Map;for(let Q of $){for(let Z of LC(Q))J.set(Z,t7(Z));for(let Z of rB(Q)){let W=pB(Z);if(W){if(!J.has(W))J.set(W,t7(W));continue}let j=iB(Z,$);if(j)J.set(j.installPath,j)}}return[...J.values()].sort((Q,Z)=>Q.installPath.localeCompare(Z.installPath))}function MC($,J){let Q=a7(J);if(!Q)return!1;if(a7($.installPath)===Q)return!0;return $.names.some((Z)=>a7(Z)===Q)}function qC($,J,Q){let Z=k2($);for(let j of J){if($W(Z,j.installPath))return j;if(j.entryPaths.some((f)=>k2(f)===Z))return j}let W=pB(Z);if(W)return t7(W);if(I2(Z))return iB(Z,Q);return}function PC($){let J=M0(),Q=J.disabledPlugins;if(!Q?.length)return;let Z=Q.filter((W)=>{let j=k2(W);if($W(j,$.installPath))return!1;return!$.entryPaths.some((f)=>k2(f)===j)});if(Z.length===Q.length)return;C1({...J,disabledPlugins:Z})}function NC($){let J=j$($);while(J!==j$(J)&&d0(J)!==e7){try{VC(J)}catch{return}J=j$(J)}}function wC($){return`${$.names[0]??d0($.installPath)} at ${$.installPath}`}async function SC($){let J=OC($),Q=TC(J),Z=$.path?.trim(),W=$.name?.trim(),j;if(Z){if(j=qC(Z,Q,J),!j)throw Error(`No plugin found at ${Z}`)}else{if(!W)throw Error("plugin uninstall requires a plugin name");let X=Q.filter((Y)=>MC(Y,W));if(X.length===0)throw Error(`No plugin found matching "${W}"`);if(X.length>1)throw Error(`Multiple plugins match "${W}": ${X.map(wC).join(", ")}`);j=X[0]}let f=BC(j.installPath,{throwIfNoEntry:!1});if(!f)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(i7({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),HC(j.installPath,{recursive:f.isDirectory(),force:!0}),PC(j),j.installed)NC(j.installPath);return{name:W||j.names[0]||d0(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}import*as O0 from"@cline/llms";var CC="cline-pass";function yC($){return $.apiKey??$.auth?.apiKey}function EC($){return($.auth?.accessToken?.trim()??"").length>0}function aB($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function bC($){let J=$.split(/\s+/).filter(Boolean);if(J.length===0)return"?";if(J.length===1)return J[0].slice(0,2).toUpperCase();return`${J[0][0]}${J[1][0]}`.toUpperCase()}function hC($){let J=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Q=0;for(let Z of $)Q=Q*31+Z.charCodeAt(0)>>>0;return J[Q%J.length]}function sB($){return Object.entries($).sort(([J],[Q])=>J.localeCompare(Q)).map(([J,Q])=>rV(J,Q))}async function kC($,J){let Q=await O0.getModelsForProvider($);if(!J)return Q;let Z=await o5($,{loadPrivateOnAuth:!0,failOnError:!1},J);return Z?.knownModels?{...Q,...Z.knownModels}:Q}function JW($){return[...new Set(($??[]).map((J)=>J.trim()).filter(Boolean))]}function IC($){if(!$?.length)return;return[...new Set($)]}function xC($,J){return IC([...$??[],...J??[]])}function gC($){let J=$?.popularRank;return typeof J==="number"&&Number.isFinite(J)?J:Number.MAX_SAFE_INTEGER}function mC($){if(!$||typeof $!=="object")return!1;let J=$;return typeof J.path==="string"&&J.path.trim().length>0&&typeof J.label==="string"&&J.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(J.type))}function vC($){let J=$?.configFields;if(!Array.isArray(J))return;return J.filter(mC)}var W5={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},nB={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function cC($){if(!$)return[W5];if($.source!=="system")return $.baseUrl?[W5,nB]:[W5];let J=[];if($.env?.length)J.push(W5);if($.baseUrl)J.push(nB);return J}function uC($,J){return J.split(".").reduce((Q,Z)=>{if(!Q||typeof Q!=="object")return;return Q[Z]},$)}function dC($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function lC($,J,Q){if(!$?.length)return;let Z={};for(let W of $){let f=dC(W.path==="baseUrl"&&J?.baseUrl===void 0?Q?.baseUrl:uC(J,W.path))??W.defaultValue;if(f!==void 0)Z[W.path]=f}return Z}function oB($){let J=Object.entries($??{}).filter(([Q])=>Q.trim().length>0);return J.length>0?Object.fromEntries(J):void 0}function QW($,J){let Q=J?.includes("vision")??!1,Z=J?.includes("reasoning")??!1;return Object.fromEntries($.map((W)=>[W,{id:W,name:W,supportsVision:Q,supportsAttachments:Q,supportsReasoning:Z}]))}async function tB($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let J=$.modelsSourceUrl?await N4($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...J])]}function eB($,J){let Q=$.read(),Z=!1;if(Q.providers[J])delete Q.providers[J],Z=!0;if(Q.lastUsedProvider===J)delete Q.lastUsedProvider,Z=!0;if(Z)$.write(Q);O0.unregisterProvider(J)}async function pC($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=J.baseUrl.trim(),W=J.apiKey?.trim()??"";if(!Z&&!W){let G=x$($);if((await C2(G)).providers[Q]){let D=await JA($,{providerId:Q});return{providerId:Q,settingsPath:D.settingsPath,modelsPath:D.modelsPath,modelsCount:0}}return eB($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(O0.hasProvider(Q))throw Error(`provider "${Q}" already exists`);let j=J.name.trim();if(!j)throw Error("name is required");if(!Z)throw Error("baseUrl is required");let f=JW(J.models),X=J.modelsSourceUrl?.trim(),Y=await tB({providerId:Q,explicitModels:f,modelsSourceUrl:X,shouldRecompute:!0});if(Y.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let V=J.defaultModelId?.trim()&&Y.includes(J.defaultModelId.trim())?J.defaultModelId.trim():Y[0],H=J.capabilities?.length?[...new Set(J.capabilities)]:void 0,B=oB(J.headers);$.saveProviderSettings({provider:Q,apiKey:W||void 0,baseUrl:Z,headers:B,timeout:J.timeoutMs,model:V,protocol:J.protocol,client:J.client},{setLastUsed:!1});let A=x$($),K=await C2(A);return K.providers[Q]={provider:{name:j,baseUrl:Z,defaultModelId:V,protocol:J.protocol,client:J.client,capabilities:H,modelsSourceUrl:X},models:QW(Y,H)},await qJ(A,K),$4(Q,K.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:Y.length}}async function $A($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=x$($),W=await C2(Z),j=W.providers[Q];if(!j){let T=$.getProviderSettings(Q);if(!T)throw Error(`provider "${Q}" does not exist`);let L=J.modelsSourceUrl?.trim(),z=JW(J.models)[0]??T.model?.trim();if(!z&&!L)throw Error(`provider "${Q}" cannot be updated because no model is configured`);j={provider:{name:J.name?.trim()||aB(Q),baseUrl:J.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:z,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:z?QW([z],T.capabilities):{}}}if(!j.provider)throw Error(`provider "${Q}" cannot be updated because it is a model overlay (no provider metadata)`);let f=J.name?.trim()??j.provider.name.trim();if(!f)throw Error("name is required");let X=J.baseUrl?.trim()??j.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let Y=J.capabilities===void 0?j.provider.capabilities:J.capabilities===null?void 0:[...new Set(J.capabilities)],V=J.protocol===void 0?j.provider.protocol:J.protocol??void 0,H=J.client===void 0?j.provider.client:J.client??void 0,B=JW(J.models),A=J.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:J.modelsSourceUrl?.trim()||void 0,K=J.models!==void 0||J.modelsSourceUrl!==void 0&&!!A,G=Object.keys(j.models??{}).map((T)=>T.trim()).filter(Boolean),R=await tB({providerId:Q,explicitModels:B,modelsSourceUrl:A,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let D=J.defaultModelId===void 0?j.provider.defaultModelId?.trim():J.defaultModelId?.trim(),U=D&&R.includes(D)?D:R[0],O={...$.getProviderSettings(Q)??{},provider:Q,baseUrl:X,model:U};if(V)O.protocol=V;else delete O.protocol;if(H)O.client=H;else delete O.client;if(J.apiKey!==void 0){let T=J.apiKey?.trim()??"";if(T)O.apiKey=T;else delete O.apiKey}if(J.headers!==void 0){let T=oB(J.headers);if(T)O.headers=T;else delete O.headers}if(J.timeoutMs!==void 0)if(typeof J.timeoutMs==="number")O.timeout=J.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),W.providers[Q]={provider:{name:f,baseUrl:X,defaultModelId:U,protocol:V,client:H,capabilities:Y,modelsSourceUrl:A},models:QW(R,Y)},await qJ(Z,W),$4(Q,W.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z,modelsCount:R.length}}async function JA($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=x$($),W=await C2(Z);if(!W.providers[Q])throw Error(`provider "${Q}" does not exist`);return delete W.providers[Q],await qJ(Z,W),O0.unregisterProvider(Q),eB($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z}}async function rC($,J={}){let Q=$.read(),Z=O0.getProviderIds(),W=await Promise.all(Z.map(async(f)=>{let[X,Y]=await Promise.all([O0.getProvider(f),O0.getModelsForProvider(f)]),V=sB(Y),H=Q.providers[f]?.settings,B=X?.name??aB(f),A=xC(X?.capabilities,H?.capabilities),K=vC(X?.metadata)??cC(X);return{provider:{id:f,name:B,models:V.length,color:hC(f),letter:bC(B),enabled:Boolean(H),apiKey:H?yC(H):void 0,oauthAccessTokenPresent:H?EC(H):void 0,baseUrl:H?.baseUrl??X?.baseUrl,defaultModelId:X?.defaultModelId,protocol:H?.protocol??X?.protocol,client:H?.client??X?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:K,configValues:lC(K,H,X),modelList:V},rank:gC(X?.metadata)}}));W.sort((f,X)=>{if(f.rank!==X.rank)return f.rank-X.rank;return f.provider.name.localeCompare(X.provider.name)||f.provider.id.localeCompare(X.provider.id)});let j=W.map((f)=>f.provider);if(J.isClinePassEnabled!==!0)j=j.filter((f)=>f.id!==CC);return{providers:j,settingsPath:$.getFilePath()}}async function iC($,J){let Q=$.trim(),Z=await kC(Q,J),W=sB(Z);return{providerId:Q,models:W}}function j5($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function QA($,J){if(!j5(J))return j5($)?{...$}:void 0;let Q=j5($)?{...$}:{};for(let[Z,W]of Object.entries(J)){if(W==null||W===""){delete Q[Z];continue}if(j5(W)){let j=QA(Q[Z],W);if(j&&Object.keys(j).length>0)Q[Z]=j;else delete Q[Z];continue}Q[Z]=W}return Object.keys(Q).length>0?Q:void 0}function nC($,J){let Q=J.providerId.trim();if(J.enabled===!1){let j=$.read();if(delete j.providers[Q],j.lastUsedProvider===Q)delete j.lastUsedProvider;return $.write(j),{providerId:Q,enabled:!1,settingsPath:$.getFilePath()}}let W={...$.getProviderSettings(Q)??{},provider:Q};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(J,j)&&typeof J[j]==="string")if(J[j].trim().length===0)delete W[j];else W[j]=J[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(J,j))W[j]=J[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(J,j)&&J[j]!=null){let f=QA(W[j],J[j]);if(f)W[j]=f;else delete W[j]}return $.saveProviderSettings(W,{setLastUsed:!1}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function aC($,J){let Q=J.trim(),Z=$.getProviderSettings(Q),j=O0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Q]?.provider,f=Z?.baseUrl?.trim()||j?.baseUrl?.trim(),X=w4(f,j?.baseUrl,j?.modelsSourceUrl);if(!Z||!j||!f||!X)return{providerId:Q,refreshed:!1};let Y=await $A($,{providerId:Q,name:j.name,baseUrl:f,apiKey:Z.apiKey,headers:Z.headers??null,timeoutMs:Z.timeout??null,modelsSourceUrl:X,protocol:Z.protocol??j.protocol??null,client:Z.client??j.client??null,capabilities:Z.capabilities??null});return{providerId:Q,refreshed:!0,modelsCount:Y.modelsCount}}function sC($){let J=$.trim().toLowerCase(),Q=f0(J);if(Q)return Q.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function oC($,J,Q,Z){let W=f0($);if(!W)throw Error(`provider "${$}" does not support OAuth login`);let j=F4({onPrompt:async(f)=>f.defaultValue??"",openUrl:Q,onOpenUrlError:({error:f})=>{throw f instanceof Error?f:Error(String(f))}});return W.login({settings:J,callbacks:j,telemetry:Z})}function tC($,J,Q,Z,W){return c2({manager:$,providerId:J,settings:Q,credentials:Z,setLastUsed:W?.setLastUsed})}async function eC($,J,Q,Z){let W=F4({onPrompt:async(j)=>j.defaultValue??"",openUrl:Q,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return l5($,J,{callbacks:W,telemetry:Z})}function $y($){let J=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return J&&J.length>0?J:void 0}import*as f5 from"@cline/llms";var Jy=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Qy={"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 Zy($,J){let Q={};for(let Z of Jy){let W=$[Z],j=J[Z];if(W||j)Q[Z]={...W,...j}}return Q}function Wy($){let J=Qy[$.providerId];if(!J)return $;return{...$,description:J.description??$.description,fields:J.mode==="replace"?J.fields:Zy($.fields,J.fields)}}var jy=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function fy($,J){if(!J?.provider.baseUrl)return!1;if(J.provider.source!=="system")return!0;return jy.has($)}function Xy($){let J=f5.normalizeProviderId($);if(v2(J))return{providerId:J,authMethod:"oauth",fields:{}};let Q=f5.MODEL_COLLECTIONS_BY_PROVIDER_ID[J];if(Q?.provider.capabilities?.includes("local-auth"))return{providerId:J,authMethod:"local",fields:{}};let Z=Q?.provider.baseUrl,W={apiKey:{}};if(fy(J,Q))W.baseUrl={defaultValue:Z};return Wy({providerId:J,authMethod:"api-key",fields:W})}eJ();F0();rJ();import{appendFileSync as Yy,existsSync as ZW,mkdirSync as Vy,readFileSync as Hy,renameSync as By,unlinkSync as Ay,writeFileSync as Ky}from"node:fs";import{join as WW}from"node:path";import{resolveTeamDataDir as Gy}from"@cline/shared/storage";function Fy($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class ZA{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let J=Fy($.teamName),Q=$.baseDir?.trim()||Gy();this.dirPath=WW(Q,J),this.statePath=WW(this.dirPath,"state.json"),this.taskHistoryPath=WW(this.dirPath,"task-history.jsonl")}loadState(){if(!ZW(this.statePath))return;try{let $=Hy(this.statePath,"utf8"),J=JSON.parse($);if(J.version!==1||!J.teamState)return;for(let Q of J.teammates??[])this.teammateSpecs.set(Q.agentId,Q);return oY(J.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let J={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Q=`${this.statePath}.tmp`;Ky(Q,`${JSON.stringify(J,null,2)}
726
- `,"utf8"),By(Q,this.statePath)}appendTaskHistory($){let J={};switch($.type){case"team_task_updated":J=$.task;break;case"team_message":J={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":J={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":J={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":J={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":J={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Yy(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:J})}
727
- `,"utf8")}ensureDir(){if(!ZW(this.dirPath))Vy(this.dirPath,{recursive:!0})}hasPersistableState($){let J=$.exportState();if(this.teammateSpecs.size>0)return!0;if(J.members.some((Q)=>Q.role==="teammate"))return!0;return J.tasks.length>0||J.mailbox.length>0||J.missionLog.length>0}clearPersistedState(){if(ZW(this.statePath))Ay(this.statePath)}}import{z as y}from"zod";var WA=y.object({workspaceRoot:y.string().min(1),cwd:y.string().optional(),provider:y.string().min(1),model:y.string().min(1),mode:y.enum(["act","plan"]).default("act"),apiKey:y.string(),systemPrompt:y.string().optional(),rules:y.string().optional(),maxIterations:y.number().int().positive().optional(),enableTools:y.boolean(),enableSpawn:y.boolean().optional(),enableTeams:y.boolean().optional(),autoApproveTools:y.boolean().optional(),missionStepInterval:y.number().int().positive().optional(),missionTimeIntervalMs:y.number().int().positive().optional()}),jA=y.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),fA=y.enum(["user","assistant","tool","system","status","error"]),XA=y.object({id:y.string().min(1),sessionId:y.string().nullable(),role:fA,content:y.string(),createdAt:y.number().int().nonnegative(),meta:y.object({stream:y.enum(["stdout","stderr"]).optional(),toolName:y.string().optional(),iteration:y.number().int().nonnegative().optional(),agentId:y.string().optional(),conversationId:y.string().optional(),hookEventName:y.string().optional(),inputTokens:y.number().int().nonnegative().optional(),outputTokens:y.number().int().nonnegative().optional(),checkpoint:y.object({ref:y.string(),createdAt:y.number().int().nonnegative(),runCount:y.number().int().positive(),kind:y.enum(["stash","commit"]).optional()}).optional()}).optional()}),YA=y.object({toolCalls:y.number().int().nonnegative(),tokensIn:y.number().int().nonnegative(),tokensOut:y.number().int().nonnegative()}),Dy=y.object({sessionId:y.string().nullable(),status:jA,config:WA,messages:y.array(XA),rawTranscript:y.string(),error:y.string().nullable(),summary:YA});var Uy=rX;import{Agent as us,createAgentRuntime as ds}from"@cline/agents";import{getClineEnvironmentConfig as Ry}from"@cline/shared";var zy=5000,HA={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 Ly($){return{recommended:$.recommended.map((J)=>({...J,tags:[...J.tags]})),free:$.free.map((J)=>({...J,tags:[...J.tags]}))}}function VA($){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.id!=="string"||J.id.length===0)return null;return{id:J.id,name:typeof J.name==="string"&&J.name.length>0?J.name:J.id,description:typeof J.description==="string"?J.description:"",tags:Array.isArray(J.tags)?J.tags.filter((Q)=>typeof Q==="string"):[]}}function _y($){if(!$||typeof $!=="object")return null;let J=$,Q=Array.isArray(J.recommended)?J.recommended:[],Z=Array.isArray(J.free)?J.free:[],W=Q.map(VA).filter((f)=>f!==null),j=Z.map(VA).filter((f)=>f!==null);if(W.length===0&&j.length===0)return null;return{recommended:W,free:j}}function Oy($){let J=$.baseUrl?.trim();if(J)return J;let Q=Ry().apiBaseUrl;try{return($.providerSettingsManager??new Q$).getProviderSettings("cline")?.baseUrl?.trim()||Q}catch{return Q}}async function Ty($,J,Q){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await $(J,{signal:Z.signal})}finally{clearTimeout(W)}}async function My($={}){try{let J=Oy($),Q=$.fetchImpl??fetch,Z=await Ty(Q,`${J}/api/v1/ai/cline/recommended-models`,$.timeoutMs??zy);if(!Z.ok)throw Error(`HTTP ${Z.status}`);let W=await Z.json(),j=_y(W);if(j)return j}catch{}return Ly(HA)}import{readFile as qy}from"node:fs/promises";import Py from"node:path";function Ny($){return $}async function wy($){let J=Py.resolve($),Q=await qy(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse JSON config at "${J}": ${j}`)}return Sy(Z,J)}function Sy($,J){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${J}": expected an object.`);let Z=$.providers;if(!Array.isArray(Z))throw Error(`Invalid llms config in "${J}": "providers" must be an array.`);if(!Z.length)throw Error(`Invalid llms config in "${J}": "providers" cannot be empty.`);return $}import{BUILT_IN_PROVIDER_IDS as KA,createHandler as Ey,createHandlerAsync as by,getProviderCollection as hy,hasProvider as GA,registerAsyncHandler as ky,registerHandler as Iy,registerModel as xy,registerProvider as FA}from"@cline/llms";function BA($){return $?{...$}:{}}function Cy($,J){if($)return $;if(!J)return;let Q=globalThis.process;if(!Q?.env)return;return Q.env[J]}function yy($,J){if(!J.length)throw Error(`Provider "${$}" must include at least one model.`)}function AA($){let J=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:J,defaultModel:$.collection.provider.defaultModelId,modelCount:J.length}}class jW{providers=new Map;register($){yy($.id,$.models);let J=$.defaultModel??$.models[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(J))throw Error(`Default model "${J}" is not included in configured models for "${$.id}".`);let Q=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Q?.models??[],...$.models]),defaultModel:J,defaults:{...Q?.defaults??{},...BA($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:Cy($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...BA($.settings)}})}registerModel($,J){let Q=this.providers.get($);if(!Q){this.providers.set($,{id:$,models:new Set([J]),defaultModel:J,defaults:{}});return}Q.models.add(J)}createHandlerConfig($){let J=this.require($.providerId),Q=$.modelId??J.defaultModel;if(!J.models.has(Q))throw Error(`Model "${Q}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Q,...J.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,J){return this.providers.get($)?.models.has(J)??!1}require($){let J=this.providers.get($);if(!J)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return J}}class fW{configuredProviders=new jW;constructor($){this.applyConfig($)}createHandler($){return Ey(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return by(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(FA($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)Iy($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)ky($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let J=$.exposeModels??Object.keys($.models),Q=$.defaultModel??J[0];if(!Q)throw Error(`Provider "${$.id}" must define a default model.`);FA({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Q,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:J,defaultModel:Q,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){xy($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...KA]}async getBuiltInProviders(){return(await Promise.all(KA.map((J)=>hy(J)))).filter((J)=>J!==void 0).map((J)=>AA({collection:J}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,J){return this.configuredProviders.hasModel($,J)}applyConfig($){for(let J of $.providers)this.configuredProviders.registerSelectionConfig(J);for(let J of $.models??[])this.registerModel(J);for(let J of $.customProviders??[])this.registerProvider(J);for(let J of this.configuredProviders.list()){let Q=GA(J.id),Z=this.configuredProviders.createHandlerConfig({providerId:J.id,modelId:J.defaultModel}).routingProviderId,W=typeof Z==="string"&&GA(Z);if(!Q&&!W)throw Error(`Provider "${J.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function gy($){return new fW($)}T7();async function Ra(){return Promise.resolve().then(() => (eJ(),xB))}export{$Y as writeHubDiscovery,C1 as writeGlobalSettings,JY as withHubStartupLock,r1 as verifyHubConnection,D8 as updateMcpServerOAuthState,$A as updateLocalProvider,SC as uninstallPlugin,w7 as truncateNotificationBody,ZQ as toggleDisabledTool,VJ as toTeamProgressLifecycleEvent,V1 as toProviderConfig,s_ as toHubStatusUrl,QY as toHubHealthUrl,rZ as toHookConfigFileName,jC as syncPluginMcpServersToSettings,GJ as summarizeUsageFromMessages,WT as stopLocalHubServerGracefully,Y1 as startLocalOAuthServer,u7 as startHubWebSocketServer,Qn as startHubServer,dA as startClineDeviceAuth,_9 as splitCoreSessionConfig,s6 as spawnDetachedHubServerWithRetry,kO as spawnDetachedHubServer,PG as setTelemetryOptOutGlobally,G8 as setMcpServerDisabled,A3 as setDisabledTools,yG as setDisabledPlugin,wG as setAutoUpdateEnabledGlobally,ip as sendHubCommand,c2 as saveProviderOAuthCredentials,nC as saveLocalProviderSettings,tC as saveLocalProviderOAuthCredentials,C8 as sanitizeSessionToken,Z3 as safeParseSettings,WG as safeCreateProviderConfig,IJ as runSubprocessEvent,gJ as runHook,Tf as reviveTeamStateDates,zY as restartLocalHubIfIdleAfterStartupTimeout,og as resolveWorkspaceHubOwnerContext,hQ as resolveWorkflowsConfigSearchPaths,EQ as resolveSkillsConfigSearchPaths,D1 as resolveSharedHubOwnerContext,NN as resolveSessionBackend,bQ as resolveRulesConfigSearchPaths,o5 as resolveProviderConfig,MK as resolveProviderApiKeyFromSettings,p1 as resolveProductionHubOwnerContext,a2 as resolvePluginSkillDirectoriesFromPaths,zQ as resolvePluginConfigSearchPaths,m1 as resolveMcpServerRegistrations,$y as resolveLocalClineAuthToken,ww as resolveHubUrl,w$ as resolveHubOwnerContext,l1 as resolveHubEndpointOptions,eX as resolveHubBuildId,lZ as resolveHooksConfigSearchPaths,H1 as resolveDisabledToolNames,v4 as resolveDisabledPluginPaths,H0 as resolveDefaultMcpSettingsPath,n6 as resolveDefaultHubPort,XO as resolveDefaultHubPathname,fO as resolveDefaultHubHost,Nf as resolveCoreSelectedToolIds,g0 as resolveCoreDistinctId,VZ as resolveCompatibleLocalHubUrl,cg as resolveClineDir,x8 as resolveClineDataDir,n4 as resolveAndLoadAgentPlugins,n2 as resolveAgentPluginPaths,WZ as requestHubShutdown,sS as requestDesktopToolApproval,i7 as removePluginMcpServersFromSettings,O2 as rememberRecoverableLocalHubUrl,vB as registerRemoteConfigSessionBlobUpload,U8 as registerMcpServersFromSettingsFile,ga as registerDisposable,aC as refreshProviderModelsFromSource,PW as refreshOpenAICodexToken,hW as refreshOcaToken,MW as refreshClineToken,j7 as readSessionCheckpointHistory,vS as readRemoteConfigSessionBlobUploadMetadata,A0 as readHubDiscovery,M0 as readGlobalSettings,EB as readBearerToken,S$ as probeHubServer,rp as probeHubConnection,yj as prewarmFileIndex,VY as prewarmDetachedHubServer,dS as prepareRemoteConfigCoreIntegration,yQ as parseWorkflowConfigFromMarkdown,xa as parseUserCommandEnvelope,SQ as parseSkillConfigFromMarkdown,Q3 as parseSettings,CQ as parseRuleConfigFromMarkdown,xJ as parseHookEventPayload,UZ as parseConfiguredAgentConfig,T$ as normalizeWorkspacePath,Ia as normalizeUserInput,ka as normalizeSdkError,L0 as normalizeRuntimeCapabilities,k4 as normalizeProviderId,sC as normalizeOAuthProvider,T2 as normalizeHubWebSocketUrl,ha as noopBasicLogger,Q7 as migrateLegacyProviderSettings,J6 as mergeRulesForSystemPrompt,t8 as mergeAgentHooks,d9 as makeTeamTaskSubSessionId,d6 as makeSubSessionId,k5 as loginOpenAICodex,c5 as loginOcaOAuth,oC as loginLocalProvider,b5 as loginClineOAuth,l5 as loginAndSaveProviderOAuthCredentials,eC as loginAndSaveLocalProviderOAuthCredentials,Ra as loadOpenTelemetryAdapter,K8 as loadMcpSettingsFile,wy as loadLlmsConfigFromFile,jJ as loadConfiguredAgentConfigs,r2 as loadAgentPluginsFromPathsWithDiagnostics,N3 as loadAgentPluginsFromPaths,KQ as loadAgentPluginFromPath,k_ as listSessionHistoryFromBackend,WX as listPluginToolsWithDiagnostics,L9 as listPluginTools,F9 as listMcpServerOAuthStatuses,rC as listLocalProviders,w2 as listHookConfigFiles,SG as isToolDisabledGlobally,QQ as isTelemetryOptedOutGlobally,O$ as isSessionNotFoundError,r3 as isRuleEnabled,CG as isPluginDisabledGlobally,v2 as isOAuthProvider,oO as isHubReconnectableTransportError,UY as isHubCommandTimeoutError,lg as isDiscoveryFilePresent,BW as isClineAccountActionRequest,$G as isBuiltInProviderId,NG as isAutoUpdateEnabledGlobally,N1 as identifyAccount,L$ as hasMcpSettingsFile,I5 as getValidOpenAICodexCredentials,u5 as getValidOcaCredentials,h5 as getValidClineCredentials,p5 as getProviderOAuthCredentialsFromSettings,Xy as getProviderConfigFields,pW as getProviderConfig,TK as getProviderAuthStorageId,f0 as getProviderAuthHandler,P4 as getPersistedProviderApiKey,F8 as getMcpServerOAuthState,iC as getLocalProviderModels,h4 as getLiveModelsCatalog,F$ as getFileIndex,Wq as getCurrentContextSize,H9 as getCoreHeadlessToolNames,Pf as getCoreDefaultEnabledToolIds,V8 as getCoreBuiltinToolCatalog,wf as getCoreAcpToolNames,Oa as getClineDefaultSystemPrompt,P9 as generateWorkspaceInfoWithDiagnostics,c6 as generateWorkspaceInfo,$6 as formatRulesForSystemPrompt,qK as formatProviderOAuthApiKey,ba as formatDisplayUserInput,jQ as filterExtensionToolRegistrations,y1 as filterDisabledTools,WQ as filterDisabledPluginPaths,My as fetchClineRecommendedModels,AW as executeClineAccountAction,hB as ensureHubWebSocketServer,Zn as ensureHubServer,Ym as ensureDetachedHubServer,eV as ensureCustomProvidersLoaded,m8 as ensureCompatibleLocalHubUrl,R6 as enrichPromptWithMentions,Ca as emptyWorkspaceManifest,S2 as emptyStoredProviderSettings,LQ as discoverPluginModulePaths,fC as disablePluginMcpServersInSettings,l9 as deriveSubsessionStatus,JA as deleteLocalProvider,Ny as defineLlmsConfig,xQ as createWorkflowsConfigDefinition,U2 as createUserInstructionConfigService,Ij as createToolPoliciesWithPreset,Sa as createTool,UH as createTeamName,bH as createSubprocessHooks,D2 as createSpawnAgentTool,kQ as createSkillsConfigDefinition,kJ as createSessionHost,kJ as createRuntimeHost,IQ as createRulesConfigDefinition,uS as createRemoteConfigSessionMessagesArtifactUploader,ZG as createProviderConfig,lJ as createOpenTelemetryTelemetryService,F4 as createOAuthClientCallbacks,I6 as createMcpTools,jr as createLocalHubScheduleRuntimeHandlers,gy as createLlmsSdk,U0 as createInitialAccumulatedUsage,dg as createInMemoryHubOwnerContext,F1 as createHubServerUrl,tX as createHubAuthToken,sZ as createHookConfigFileHooks,LJ as createHookConfigFileExtension,zJ as createHookAuditHooks,z9 as createDisabledMcpToolPolicy,JX as createDisabledMcpToolPolicies,G2 as createDelegatedAgentConfigProvider,F2 as createDelegatedAgent,xj as createDefaultToolsWithPreset,B2 as createDefaultTools,h6 as createDefaultMcpServerClientFactory,O6 as createDefaultExecutors,L8 as createCoreSettingsService,i1 as createCoreSessionSnapshot,wa as createContributionRegistry,cZ as createContextCompactionPrepareTurn,c$ as createConfiguredTelemetryService,pJ as createConfiguredTelemetryHandle,XJ as createConfiguredAgentTools,Na as createClineTelemetryServiceMetadata,Pa as createClineTelemetryServiceConfig,H8 as createBuiltinTools,Y8 as createAgentTeamsTools,ds as createAgentRuntime,FJ as createAgentHooksExtension,gH as connectToHub,lA as completeClineDeviceAuth,oK as clearPrivateModelsCatalogCache,sK as clearLiveModelsCatalogCache,n0 as clearHubDiscovery,wA as captureWorkspacePathResolved,A5 as captureWorkspaceInitialized,K5 as captureWorkspaceInitError,R5 as captureToolUsage,D5 as captureTokenUsage,F5 as captureTaskRestarted,G5 as captureTaskCreated,U4 as captureTaskCompleted,z4 as captureSubagentExecution,z5 as captureSkillUsed,qa as captureSdkError,SA as captureProviderConfigured,R4 as captureProviderApiError,U5 as captureModeSwitch,_5 as captureMentionUsed,T5 as captureMentionSearchResults,O5 as captureMentionFailed,q5 as captureHookDiscovery,NA as captureExtensionActivated,L5 as captureDiffEditFailure,g2 as captureConversationTurnEvent,N5 as captureCompactionSkipped,P5 as captureCompactionExecuted,q1 as captureAuthSucceeded,M1 as captureAuthStarted,Y$ as captureAuthLoggedOut,P1 as captureAuthFailed,M5 as captureAgentTeamCreated,V$ as captureAgentCreated,N9 as buildWorkspaceMetadata,YJ as buildTeamProgressSummary,Ta as buildSdkErrorProperties,gB as buildRemoteConfigSessionBlobUploadMetadata,f8 as buildDelegatedAgentConfig,zZ as buildConfiguredAgentToolName,LZ as buildConfiguredAgentToolDescriptors,w6 as bootstrapAgentTeams,uf as authorizeMcpServerOAuth,pC as addLocalProvider,K0 as accumulateUsageTotals,qQ as WORKFLOWS_CONFIG_DIRECTORY_NAME,d2 as UnifiedConfigFileWatcher,$1 as ToolPresets,Y4 as TelemetryService,dJ as TelemetryLoggerSink,N6 as TEAM_TOOL_NAMES,u4 as SubprocessSandbox,_J as StoredProviderSettingsSchema,bV as StoredProviderSettingsEntrySchema,J4 as SqliteTeamStore,s1 as SqliteSessionStore,E2 as SessionVersioningService,a0 as SessionVersioningError,z0 as SessionSource,_$ as SessionNotFoundError,eW as SapSettingsSchema,MQ as SKILLS_CONFIG_DIRECTORY_NAME,$Q as SESSION_STATUSES,_8 as SESSION_NOT_FOUND_ERROR_CODE,ma as SDK_ERROR_TELEMETRY_EVENT,B5 as RpcClineAccountService,$J as RemoteRuntimeHost,aW as ReasoningSettingsSchema,m3 as RULES_CONFIG_DIRECTORY_NAME,mB as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,e$ as ProviderSettingsSchema,Q$ as ProviderSettingsManager,rW as ProviderProtocolSchema,e5 as ProviderIdSchema,iW as ProviderClientSchema,V4 as OpenTelemetryProvider,$3 as OcaSettingsSchema,s5 as OPENAI_COMPATIBLE_PROVIDERS,U1 as NodeHubClient,f4 as NoOpFeatureFlagsProvider,m7 as NativeHubTransportAdapter,J3 as ModelCatalogSettingsSchema,Z$ as LocalRuntimeHost,La as Llms,OJ as InMemoryWorkspaceManager,R8 as InMemoryMcpManager,bw as HubUIClient,x0 as HubTransportError,Ew as HubSessionClient,tJ as HubServerTransport,uJ as HubScheduleService,mJ as HubScheduleCommandService,b$ as HubRuntimeHost,o6 as HubCommandError,yH as HookEventPayloadSchema,CH as HookEventNameSchema,DJ as HookConfigFileName,pZ as HOOK_CONFIG_FILE_EVENT_MAP,MV as HOOKS_CONFIG_DIRECTORY_NAME,m4 as GlobalSettingsSchema,oW as GcpSettingsSchema,ZA as FileTeamPersistenceStore,j4 as FeatureFlagsService,Ea as FeatureFlagDefaultValue,ya as FEATURE_FLAGS,HA as FALLBACK_CLINE_RECOMMENDED_MODELS,D0 as DefaultToolNames,EJ as DefaultRuntimeBuilder,fW as DefaultLlmsSdk,uW as DEFAULT_MODELS_CATALOG_URL,WO as DEFAULT_HUB_PORT,jO as DEFAULT_HUB_PATHNAME,ZO as DEFAULT_HUB_HOST,_2 as CoreSettingsService,o1 as CoreSessionService,Ma as ContributionRegistry,_7 as ClineCore,H5 as ClineAccountService,Dy as ChatViewStateSchema,YA as ChatSummarySchema,jA as ChatSessionStatusSchema,WA as ChatSessionConfigSchema,XA as ChatMessageSchema,fA as ChatMessageRoleSchema,k as CORE_TELEMETRY_EVENTS,Uy as CORE_BUILD_VERSION,g7 as BrowserWebSocketHubAdapter,eK as BUILT_IN_PROVIDER_IDS,t5 as BUILT_IN_PROVIDER,tW as AzureSettingsSchema,sW as AwsSettingsSchema,nW as AuthSettingsSchema,l8 as AgentTeamsRuntime,OZ as AgentTeam,us as Agent,X2 as ALL_DEFAULT_TOOL_NAMES};
722
+ `),$.end()}catch{$.destroy()}}function v7($,J){if(!$||!J)return!1;let Q=Buffer.from($,"utf8"),Z=Buffer.from(J,"utf8");return Q.length===Z.length&&_S(Q,Z)}function yB($,J){let Q=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Z=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",W=`Failed to start hub server on ${J.host}:${J.port}${J.pathname}: ${Z}`,j=Error(Q?`${W} (${Q})`:W);if(Q)$.code=Q,j.code=Q;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
723
+ Caused by: ${$.stack}`;return j}async function yS($){return await new Promise((J,Q)=>{let Z=TS.createServer();Z.once("error",Q),Z.listen(0,$,()=>{let W=Z.address();if(!W||typeof W==="string"){Z.close(()=>Q(Error("Failed to resolve free port")));return}let j=W.port;Z.close((f)=>{if(f){Q(f);return}J(j)})})})}function ES($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var c7=new Map,EB="cline-hub-auth.",bS=30000;function kB($){return Array.isArray($)?$.join(","):$??""}function bB($){return $===32||$===9}function hB($){let J=kB($).trim(),Q="bearer";if(J.length<=6||J.slice(0,6).toLowerCase()!=="bearer"||!bB(J.charCodeAt(6)))return null;let Z=7;while(Z<J.length&&bB(J.charCodeAt(Z)))Z+=1;return J.slice(Z).trim()||null}function hS($){for(let J of kB($).split(",")){let Q=J.trim();if(Q.startsWith(EB))return Q.slice(EB.length).trim()||null}return null}async function u7($){let J=$.owner??w$(),Q=$.host??"127.0.0.1",Z=$.pathname??"/hub",W=$.port??n6(),j=W===0?await yS(Q):W,f=j,X=F1(Q,j,Z),Y=JY(),V=$Y(),H=new tJ($);await H.start();let B=new g7(new m7(H),$.telemetry),A=new Set,K=new Date().toISOString(),G={protocolVersion:wB,minClientProtocolVersion:CB,maxClientProtocolVersion:SB,capabilities:MS,coreVersion:I8.version,buildId:Y,pid:process.pid,startedAt:K},R=new Set,D,U,F=async()=>{if(U)return U;return U=(async()=>{if(D)clearInterval(D),D=void 0;for(let z of R)z.terminate?.();R.clear();for(let z of A)z();if(A.clear(),await new Promise((z,M)=>{T.close((P)=>{if(P){M(P);return}z()})}),await new Promise((z,M)=>{O.close((P)=>{if(P){M(P);return}z()})}),await H.stop(),(await A0(J.discoveryPath))?.url===X)await n0(J.discoveryPath)})(),U},O=OS.createServer((L,z)=>{if((L.url??"/")==="/health"){let P=JSON.stringify({ok:!0,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,coreVersion:G.coreVersion,host:Q,port:f,url:X});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(P);return}if((L.url??"/")==="/status"){if(!v7(hB(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}let P=JSON.stringify({hubId:H.getHubId(),...G,authToken:V,host:Q,port:f,url:X,updatedAt:new Date().toISOString()});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(P);return}if((L.url??"/")==="/version"){z.statusCode=200,z.setHeader("content-type","application/json"),z.end(JSON.stringify(G));return}if(new NB(L.url??"/",`http://${Q}:${f}`).pathname==="/shutdown"&&L.method==="POST"){if(!v7(hB(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}z.statusCode=202,z.setHeader("content-type","application/json"),z.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{F()});return}z.statusCode=404,z.end("Not found")}),T=new PS({noServer:!0});D=setInterval(()=>{for(let L of R){if(L.isAlive===!1){try{L.terminate?.()}catch{}R.delete(L);continue}L.isAlive=!1;try{L.ping?.()}catch{try{L.terminate?.()}catch{}R.delete(L)}}},bS),O.on("upgrade",(L,z,M)=>{if(new NB(L.url??"/",`http://${Q}:${f}`).pathname!==Z){z.destroy();return}if(!v7(hS(L.headers["sec-websocket-protocol"]),V)){CS(z);return}try{T.handleUpgrade(L,z,M,(C)=>{let m=C;m.isAlive=!0,m.on("pong",()=>{m.isAlive=!0}),R.add(m);let n=B.attach(wS(C));A.add(n),C.once("close",()=>{R.delete(m),n(),A.delete(n)})})}catch{SS(z)}});try{await new Promise((L,z)=>{O.once("error",(M)=>{z(yB(M,{host:Q,port:j,pathname:Z}))}),O.listen(j,Q,()=>{let M=O.address();if(!M||typeof M==="string"){z(yB(Error("Failed to resolve hub port"),{host:Q,port:j,pathname:Z}));return}f=M.port,X=F1(Q,f,Z),L()})})}catch(L){if(D)clearInterval(D),D=void 0;throw await H.stop().catch(()=>{return}),L}return await QY(J.discoveryPath,{hubId:H.getHubId(),protocolVersion:wB,minClientProtocolVersion:CB,maxClientProtocolVersion:SB,capabilities:[...G.capabilities],coreVersion:I8.version,buildId:Y,authToken:V,host:Q,port:f,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:Q,port:f,url:X,authToken:V,close:F}}async function IB($){let J=$.owner??w$(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.host??"127.0.0.1",W=$.port??n6(),j=$.pathname??"/hub",f=F1(Z,W,j),X=J.discoveryPath,Y=(H)=>{if(!Q)O2(H.url,H.authToken);return H},V=c7.get(X);if(V){let H=await V;if(H.url===f)return Y({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await ZY(J.discoveryPath,async()=>{let H=await A0(J.discoveryPath);if(H?.url&&(H.url===f||$.allowPortFallback===!0)){let K=await S$(H.url,{authToken:H.authToken});if(K?.url&&qS(K).compatible&&await r1(K.url,{authToken:H.authToken}))return Y({url:K.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await n0(J.discoveryPath);let A=async(K)=>{let G=u7({...K,owner:J});c7.set(X,G);try{let R=await G;return Y({server:R,url:R.url,authToken:R.authToken,action:"started"})}catch(R){throw c7.delete(X),R}};try{return await A($)}catch(K){if(!$.allowPortFallback||!ES(K))throw K;return await A({...$,port:0})}})}function gB(){return xB()==="production"?p1():D1()}function kS($){return xB()!=="production"&&!$}async function Zn($){let J=l1({host:$.host,port:$.port,pathname:$.pathname});return await u7({...$,...J,owner:gB()})}async function Wn($){let J=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=l1({host:$.host,port:$.port,pathname:$.pathname});return await IB({...$,...Q,allowPortFallback:$.allowPortFallback??kS(J),owner:gB()})}eJ();import{buildRemoteConfigSessionBlobUploadMetadata as vB,clearRemoteConfigSessionBlobUpload as IS,createClineTelemetryServiceConfig as xS,createSessionId as gS,createRemoteConfigSessionMessagesArtifactUploader as mS,prepareRemoteConfigRuntime as vS,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as cB,readRemoteConfigSessionBlobUploadMetadata as cS,registerRemoteConfigSessionBlobUpload as uB}from"@cline/shared";function uS($,J){let Q=$.telemetry||J.telemetryService?{...J.telemetryService??{},...$.telemetry??{}}:void 0;if(!Q)return;return c$(xS(Q)).telemetry}function dS(){let $=mS();return{async uploadMessagesFile(J){await $.uploadMessagesFile(J)}}}async function lS($){let J=await vS($),Q=uS(J,$),Z=[J.pluginDefinition],W=J.claims?.subject,j=vB(J.bundle?.remoteConfig,W),f;return{prepared:J,extensions:Z,telemetry:Q,applyToStartSessionInput(X){let Y=X.config.extensions??[],V=X.config.telemetry,H=j?X.config.sessionId?.trim()||gS():X.config.sessionId;if(H&&j)f=H;let B=H&&j?uB(H,J.bundle?.remoteConfig,W):void 0,A=B?{...X.sessionMetadata??{},[cB]:B}:X.sessionMetadata;return{...X,...A?{sessionMetadata:A}:{},config:{...X.config,...H?{sessionId:H}:{},extensions:[...Y,...Z],telemetry:Q??V}}},async dispose(){if(f)IS(f)}}}import{mkdir as pS,readFile as rS,unlink as iS,writeFile as nS}from"node:fs/promises";import{join as dB}from"node:path";function aS($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function sS($){return new Promise((J)=>setTimeout(J,$))}async function d7($){try{await iS($)}catch{}}async function oS($,J={}){let Q=J.approvalDir?.trim(),Z=J.sessionId?.trim();if(!Q||!Z)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await pS(Q,{recursive:!0});let W=aS(`${$.toolCallId}`),j=dB(Q,`${Z}.request.${W}.json`),f=dB(Q,`${Z}.decision.${W}.json`),X=J.nowIso??(()=>new Date().toISOString());await nS(j,`${JSON.stringify({requestId:W,sessionId:Z,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
724
+ `,"utf8");let Y=J.timeoutMs??300000,V=J.pollIntervalMs??200,H=Date.now();while(Date.now()-H<Y){try{let B=await rS(f,"utf8"),A=JSON.parse(B),K={approved:A.approved===!0,reason:typeof A.reason==="string"?A.reason:void 0};return await Promise.all([d7(f),d7(j)]),K}catch{}await sS(V)}return await d7(j),{approved:!1,reason:"Tool approval request timed out"}}p0();import{existsSync as tS,mkdirSync as eS,readFileSync as $C,writeFileSync as JC}from"node:fs";import{dirname as pB,isAbsolute as QC,relative as ZC,resolve as lB}from"node:path";function l$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $5($,J){let Q=ZC(lB($),lB(J));return Q===""||!Q.startsWith("..")&&!QC(Q)}function l7($){if(!tS($))return{mcpServers:{}};try{let J=JSON.parse($C($,"utf8"));if(l$(J))return J}catch(J){throw Error(`Invalid MCP settings at "${$}": ${J instanceof Error?J.message:String(J)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function p7($){if(l$($.mcpServers))return{...$.mcpServers};return{}}function r7($,J,Q){eS(pB($),{recursive:!0}),JC($,`${JSON.stringify({...J,mcpServers:Q},null,2)}
725
+ `,"utf8")}function rB($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((J)=>J.trim()).filter((J)=>J.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((J)=>J.trim()).filter((J)=>J.length>0))]}}function Q5($){if(!l$($))return;let J=$.metadata;return l$(J)?J:void 0}function J5($,J){let Q=Q5($);if(!Q||Q.source!=="plugin")return!1;let Z=typeof Q.pluginName==="string"?Q.pluginName:typeof Q.plugin==="string"?Q.plugin:void 0,W=typeof Q.pluginPath==="string"?Q.pluginPath:void 0;if(J.pluginName&&Z===J.pluginName){if(!J.pluginPath||W===J.pluginPath)return!0}if(W&&J.pluginPath&&(W===J.pluginPath||$5(J.pluginPath,W)||$5(W,J.pluginPath)))return!0;if(Z&&J.pluginNames?.some((j)=>j===Z))return!0;if(W&&J.pluginPaths?.some((j)=>W===j||$5(j,W)||$5(W,j)))return!0;return!1}function WC($){let J=l$($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:pB($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...J,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function jC($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let J=await W2({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Q=[],Z=[],W=(J.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of J.extensions??[]){let f=j.__clinePluginPath;if(!f)continue;if(!j.setup){Q.push({pluginName:j.name,pluginPath:f});continue}let X=[],Y={registerTool:(V)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(V)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');X.push(V)}};try{await j.setup(Y,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(V){W.push({pluginPath:f,pluginName:j.name,message:V instanceof Error?V.message:String(V)});continue}Q.push({pluginName:j.name,pluginPath:f});for(let V of X)Z.push({pluginName:j.name,pluginPath:f,server:{...V,metadata:{...V.metadata??{},source:"plugin",pluginName:j.name,pluginPath:f}}})}return{plugins:Q,servers:Z,failures:W}}finally{await J.shutdown().catch(()=>{})}}async function fC($){let J=$.settingsPath??H0(),Q={mutations:[],failures:[]},Z;try{Z=await jC($)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}Q.failures.push(...Z.failures);let W;try{W=l7(J)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}let j=p7(W),f=new Map,X=new Map;for(let V of Z.plugins)f.set(V.pluginPath,new Set),X.set(V.pluginPath,V.pluginName);let Y=R9(Z.servers.map((V)=>({server:V.server,owner:V,ownerLabel:V.pluginName})));for(let V of Y){let H=V.owner;if(!f.has(H.pluginPath))f.set(H.pluginPath,new Set);if(V.name)f.get(H.pluginPath)?.add(V.name);if(!V.registration){Q.mutations.push({name:V.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:V.loadError??"invalid MCP server registration"});continue}let B=j[V.registration.name];if(B!==void 0){if(!J5(B,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[V.registration.name]=WC({registration:V.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:l$(B)?B:void 0}),Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:B===void 0?"created":"updated"})}for(let[V,H]of Object.entries(j)){let B=Q5(H),A=typeof B?.pluginPath==="string"?B.pluginPath:"",K=f.get(A);if(K&&J5(H,{pluginPath:A})&&!K.has(V))delete j[V],Q.mutations.push({name:V,pluginName:typeof B?.pluginName==="string"?B.pluginName:X.get(A)??"plugin",pluginPath:A,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Q.mutations.some((V)=>V.action!=="skipped"))try{r7(J,W,j)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)})}return Q}function XC($){let J=$.settingsPath??H0(),Q;try{Q=l7(J)}catch{return[]}let Z=p7(Q),W=rB($),j=[];for(let[f,X]of Object.entries(Z)){if(!l$(X)||!J5(X,W))continue;let Y=Q5(X);Z[f]={...X,disabled:!0},j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"disabled"})}if(j.length>0)r7(J,Q,Z);return j}function i7($){let J=$.settingsPath??H0(),Q;try{Q=l7(J)}catch{return[]}let Z=p7(Q),W=rB($),j=[];for(let[f,X]of Object.entries(Z)){if(!J5(X,W))continue;let Y=Q5(X);delete Z[f],j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"removed"})}if(j.length>0)r7(J,Q,Z);return j}p0();import{existsSync as I2,readdirSync as YC,readFileSync as VC,rmdirSync as HC,rmSync as BC,statSync as AC}from"node:fs";import{basename as d0,dirname as j$,extname as KC,isAbsolute as GC,join as O1,relative as FC,resolve as k2,sep as n7}from"node:path";import{discoverPluginModulePaths as DC,resolvePluginConfigSearchPaths as UC}from"@cline/shared/storage";var e7="_installed",RC="package",zC=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function a7($){return $.trim().toLowerCase()}function s0($,J){let Q=J?.trim();if(!Q)return;$.add(Q)}function LC($){return $.replace(/-[0-9a-f]{12}$/i,"")}function s7($){let J=KC($);return J?$.slice(0,-J.length):$}function o7($){if(!I2($))return;try{let J=JSON.parse(VC($,"utf8"));return typeof J.name==="string"?J.name.trim():void 0}catch{return}}function $W($,J){let Q=FC(J,$);return Q===""||!Q.startsWith("..")&&!GC(Q)}function iB($){let Q=k2($).split(n7),Z=Q.lastIndexOf(e7);if(Z<0)return;let W=Q[Z+1];if(!W)return;let j=zC.get(W)??1,f=Z+2+j;if(Q.length<f)return;let X=Q.slice(0,f).join(n7)||n7;return I2(X)?X:void 0}function Z5($){try{return YC($,{withFileTypes:!0})}catch{return[]}}function _C($){let J=O1($,e7);if(!I2(J))return[];let Q=[];for(let Z of Z5(J)){if(!Z.isDirectory())continue;let W=O1(J,Z.name);if(Z.name==="git"){for(let j of Z5(W)){if(!j.isDirectory())continue;let f=O1(W,j.name);for(let X of Z5(f))if(X.isDirectory())Q.push(O1(f,X.name))}continue}for(let j of Z5(W))if(j.isDirectory())Q.push(O1(W,j.name))}return Q.sort((Z,W)=>Z.localeCompare(W))}function nB($){try{return DC($)}catch{return[]}}function t7($){let J=nB($),Q=new Set;s0(Q,d0($)),s0(Q,LC(d0($))),s0(Q,o7(O1($,"package.json"))),s0(Q,o7(O1($,RC,"package.json")));for(let Z of J)s0(Q,d0(Z)),s0(Q,s7(d0(Z)));return{installPath:$,entryPaths:J,names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!0}}function OC($,J){let Q=k2($),Z=J.find((f)=>$W(Q,f));if(!Z)return;let W=j$(Q);while(W!==Z&&W!==j$(W)){if(I2(O1(W,"package.json")))return W;W=j$(W)}let j=d0(Q);if((j==="index.ts"||j==="index.js")&&j$(Q)!==Z)return j$(Q);return Q}function aB($,J){let Q=OC($,J);if(!Q)return;let Z=new Set;return s0(Z,d0($)),s0(Z,s7(d0($))),s0(Z,d0(Q)),s0(Z,s7(d0(Q))),s0(Z,o7(O1(Q,"package.json"))),{installPath:Q,entryPaths:[$],names:[...Z].sort((W,j)=>W.localeCompare(j)),installed:!1}}function TC($){let J=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return UC(J).filter((Q)=>I2(Q))}function MC($){let J=new Map;for(let Q of $){for(let Z of _C(Q))J.set(Z,t7(Z));for(let Z of nB(Q)){let W=iB(Z);if(W){if(!J.has(W))J.set(W,t7(W));continue}let j=aB(Z,$);if(j)J.set(j.installPath,j)}}return[...J.values()].sort((Q,Z)=>Q.installPath.localeCompare(Z.installPath))}function qC($,J){let Q=a7(J);if(!Q)return!1;if(a7($.installPath)===Q)return!0;return $.names.some((Z)=>a7(Z)===Q)}function PC($,J,Q){let Z=k2($);for(let j of J){if($W(Z,j.installPath))return j;if(j.entryPaths.some((f)=>k2(f)===Z))return j}let W=iB(Z);if(W)return t7(W);if(I2(Z))return aB(Z,Q);return}function NC($){let J=M0(),Q=J.disabledPlugins;if(!Q?.length)return;let Z=Q.filter((W)=>{let j=k2(W);if($W(j,$.installPath))return!1;return!$.entryPaths.some((f)=>k2(f)===j)});if(Z.length===Q.length)return;C1({...J,disabledPlugins:Z})}function wC($){let J=j$($);while(J!==j$(J)&&d0(J)!==e7){try{HC(J)}catch{return}J=j$(J)}}function SC($){return`${$.names[0]??d0($.installPath)} at ${$.installPath}`}async function CC($){let J=TC($),Q=MC(J),Z=$.path?.trim(),W=$.name?.trim(),j;if(Z){if(j=PC(Z,Q,J),!j)throw Error(`No plugin found at ${Z}`)}else{if(!W)throw Error("plugin uninstall requires a plugin name");let X=Q.filter((Y)=>qC(Y,W));if(X.length===0)throw Error(`No plugin found matching "${W}"`);if(X.length>1)throw Error(`Multiple plugins match "${W}": ${X.map(SC).join(", ")}`);j=X[0]}let f=AC(j.installPath,{throwIfNoEntry:!1});if(!f)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(i7({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),BC(j.installPath,{recursive:f.isDirectory(),force:!0}),NC(j),j.installed)wC(j.installPath);return{name:W||j.names[0]||d0(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}import*as O0 from"@cline/llms";var yC="cline-pass";function EC($){return $.apiKey??$.auth?.apiKey}function bC($){return($.auth?.accessToken?.trim()??"").length>0}function oB($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function hC($){let J=$.split(/\s+/).filter(Boolean);if(J.length===0)return"?";if(J.length===1)return J[0].slice(0,2).toUpperCase();return`${J[0][0]}${J[1][0]}`.toUpperCase()}function kC($){let J=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Q=0;for(let Z of $)Q=Q*31+Z.charCodeAt(0)>>>0;return J[Q%J.length]}function tB($){return Object.entries($).sort(([J],[Q])=>J.localeCompare(Q)).map(([J,Q])=>nV(J,Q))}async function IC($,J){let Q=await O0.getModelsForProvider($);if(!J)return Q;let Z=await o5($,{loadPrivateOnAuth:!0,failOnError:!1},J);return Z?.knownModels?{...Q,...Z.knownModels}:Q}function JW($){return[...new Set(($??[]).map((J)=>J.trim()).filter(Boolean))]}function xC($){if(!$?.length)return;return[...new Set($)]}function gC($,J){return xC([...$??[],...J??[]])}function mC($){let J=$?.popularRank;return typeof J==="number"&&Number.isFinite(J)?J:Number.MAX_SAFE_INTEGER}function vC($){if(!$||typeof $!=="object")return!1;let J=$;return typeof J.path==="string"&&J.path.trim().length>0&&typeof J.label==="string"&&J.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(J.type))}function cC($){let J=$?.configFields;if(!Array.isArray(J))return;return J.filter(vC)}var W5={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},sB={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function uC($){if(!$)return[W5];if($.source!=="system")return $.baseUrl?[W5,sB]:[W5];let J=[];if($.env?.length)J.push(W5);if($.baseUrl)J.push(sB);return J}function dC($,J){return J.split(".").reduce((Q,Z)=>{if(!Q||typeof Q!=="object")return;return Q[Z]},$)}function lC($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function pC($,J,Q){if(!$?.length)return;let Z={};for(let W of $){let f=lC(W.path==="baseUrl"&&J?.baseUrl===void 0?Q?.baseUrl:dC(J,W.path))??W.defaultValue;if(f!==void 0)Z[W.path]=f}return Z}function eB($){let J=Object.entries($??{}).filter(([Q])=>Q.trim().length>0);return J.length>0?Object.fromEntries(J):void 0}function QW($,J){let Q=J?.includes("vision")??!1,Z=J?.includes("reasoning")??!1;return Object.fromEntries($.map((W)=>[W,{id:W,name:W,supportsVision:Q,supportsAttachments:Q,supportsReasoning:Z}]))}async function $A($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let J=$.modelsSourceUrl?await N4($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...J])]}function JA($,J){let Q=$.read(),Z=!1;if(Q.providers[J])delete Q.providers[J],Z=!0;if(Q.lastUsedProvider===J)delete Q.lastUsedProvider,Z=!0;if(Z)$.write(Q);O0.unregisterProvider(J)}async function rC($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=J.baseUrl.trim(),W=J.apiKey?.trim()??"";if(!Z&&!W){let G=x$($);if((await C2(G)).providers[Q]){let D=await ZA($,{providerId:Q});return{providerId:Q,settingsPath:D.settingsPath,modelsPath:D.modelsPath,modelsCount:0}}return JA($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(O0.hasProvider(Q))throw Error(`provider "${Q}" already exists`);let j=J.name.trim();if(!j)throw Error("name is required");if(!Z)throw Error("baseUrl is required");let f=JW(J.models),X=J.modelsSourceUrl?.trim(),Y=await $A({providerId:Q,explicitModels:f,modelsSourceUrl:X,shouldRecompute:!0});if(Y.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let V=J.defaultModelId?.trim()&&Y.includes(J.defaultModelId.trim())?J.defaultModelId.trim():Y[0],H=J.capabilities?.length?[...new Set(J.capabilities)]:void 0,B=eB(J.headers);$.saveProviderSettings({provider:Q,apiKey:W||void 0,baseUrl:Z,headers:B,timeout:J.timeoutMs,model:V,protocol:J.protocol,client:J.client},{setLastUsed:!1});let A=x$($),K=await C2(A);return K.providers[Q]={provider:{name:j,baseUrl:Z,defaultModelId:V,protocol:J.protocol,client:J.client,capabilities:H,modelsSourceUrl:X},models:QW(Y,H)},await qJ(A,K),$4(Q,K.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:Y.length}}async function QA($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=x$($),W=await C2(Z),j=W.providers[Q];if(!j){let T=$.getProviderSettings(Q);if(!T)throw Error(`provider "${Q}" does not exist`);let L=J.modelsSourceUrl?.trim(),z=JW(J.models)[0]??T.model?.trim();if(!z&&!L)throw Error(`provider "${Q}" cannot be updated because no model is configured`);j={provider:{name:J.name?.trim()||oB(Q),baseUrl:J.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:z,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:z?QW([z],T.capabilities):{}}}if(!j.provider)throw Error(`provider "${Q}" cannot be updated because it is a model overlay (no provider metadata)`);let f=J.name?.trim()??j.provider.name.trim();if(!f)throw Error("name is required");let X=J.baseUrl?.trim()??j.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let Y=J.capabilities===void 0?j.provider.capabilities:J.capabilities===null?void 0:[...new Set(J.capabilities)],V=J.protocol===void 0?j.provider.protocol:J.protocol??void 0,H=J.client===void 0?j.provider.client:J.client??void 0,B=JW(J.models),A=J.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:J.modelsSourceUrl?.trim()||void 0,K=J.models!==void 0||J.modelsSourceUrl!==void 0&&!!A,G=Object.keys(j.models??{}).map((T)=>T.trim()).filter(Boolean),R=await $A({providerId:Q,explicitModels:B,modelsSourceUrl:A,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let D=J.defaultModelId===void 0?j.provider.defaultModelId?.trim():J.defaultModelId?.trim(),U=D&&R.includes(D)?D:R[0],O={...$.getProviderSettings(Q)??{},provider:Q,baseUrl:X,model:U};if(V)O.protocol=V;else delete O.protocol;if(H)O.client=H;else delete O.client;if(J.apiKey!==void 0){let T=J.apiKey?.trim()??"";if(T)O.apiKey=T;else delete O.apiKey}if(J.headers!==void 0){let T=eB(J.headers);if(T)O.headers=T;else delete O.headers}if(J.timeoutMs!==void 0)if(typeof J.timeoutMs==="number")O.timeout=J.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),W.providers[Q]={provider:{name:f,baseUrl:X,defaultModelId:U,protocol:V,client:H,capabilities:Y,modelsSourceUrl:A},models:QW(R,Y)},await qJ(Z,W),$4(Q,W.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z,modelsCount:R.length}}async function ZA($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=x$($),W=await C2(Z);if(!W.providers[Q])throw Error(`provider "${Q}" does not exist`);return delete W.providers[Q],await qJ(Z,W),O0.unregisterProvider(Q),JA($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z}}async function iC($,J={}){let Q=$.read(),Z=O0.getProviderIds(),W=await Promise.all(Z.map(async(f)=>{let[X,Y]=await Promise.all([O0.getProvider(f),O0.getModelsForProvider(f)]),V=tB(Y),H=Q.providers[f]?.settings,B=X?.name??oB(f),A=gC(X?.capabilities,H?.capabilities),K=cC(X?.metadata)??uC(X);return{provider:{id:f,name:B,models:V.length,color:kC(f),letter:hC(B),enabled:Boolean(H),apiKey:H?EC(H):void 0,oauthAccessTokenPresent:H?bC(H):void 0,baseUrl:H?.baseUrl??X?.baseUrl,defaultModelId:X?.defaultModelId,protocol:H?.protocol??X?.protocol,client:H?.client??X?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:K,configValues:pC(K,H,X),modelList:V},rank:mC(X?.metadata)}}));W.sort((f,X)=>{if(f.rank!==X.rank)return f.rank-X.rank;return f.provider.name.localeCompare(X.provider.name)||f.provider.id.localeCompare(X.provider.id)});let j=W.map((f)=>f.provider);if(J.isClinePassEnabled!==!0)j=j.filter((f)=>f.id!==yC);return{providers:j,settingsPath:$.getFilePath()}}async function nC($,J){let Q=$.trim(),Z=await IC(Q,J),W=tB(Z);return{providerId:Q,models:W}}function j5($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function WA($,J){if(!j5(J))return j5($)?{...$}:void 0;let Q=j5($)?{...$}:{};for(let[Z,W]of Object.entries(J)){if(W==null||W===""){delete Q[Z];continue}if(j5(W)){let j=WA(Q[Z],W);if(j&&Object.keys(j).length>0)Q[Z]=j;else delete Q[Z];continue}Q[Z]=W}return Object.keys(Q).length>0?Q:void 0}function aC($,J){let Q=J.providerId.trim();if(J.enabled===!1){let j=$.read();if(delete j.providers[Q],j.lastUsedProvider===Q)delete j.lastUsedProvider;return $.write(j),{providerId:Q,enabled:!1,settingsPath:$.getFilePath()}}let W={...$.getProviderSettings(Q)??{},provider:Q};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(J,j)&&typeof J[j]==="string")if(J[j].trim().length===0)delete W[j];else W[j]=J[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(J,j))W[j]=J[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(J,j)&&J[j]!=null){let f=WA(W[j],J[j]);if(f)W[j]=f;else delete W[j]}return $.saveProviderSettings(W,{setLastUsed:!1}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function sC($,J){let Q=J.trim(),Z=$.getProviderSettings(Q),j=O0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Q]?.provider,f=Z?.baseUrl?.trim()||j?.baseUrl?.trim(),X=w4(f,j?.baseUrl,j?.modelsSourceUrl);if(!Z||!j||!f||!X)return{providerId:Q,refreshed:!1};let Y=await QA($,{providerId:Q,name:j.name,baseUrl:f,apiKey:Z.apiKey,headers:Z.headers??null,timeoutMs:Z.timeout??null,modelsSourceUrl:X,protocol:Z.protocol??j.protocol??null,client:Z.client??j.client??null,capabilities:Z.capabilities??null});return{providerId:Q,refreshed:!0,modelsCount:Y.modelsCount}}function oC($){let J=$.trim().toLowerCase(),Q=f0(J);if(Q)return Q.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function tC($,J,Q,Z){let W=f0($);if(!W)throw Error(`provider "${$}" does not support OAuth login`);let j=F4({onPrompt:async(f)=>f.defaultValue??"",openUrl:Q,onOpenUrlError:({error:f})=>{throw f instanceof Error?f:Error(String(f))}});return W.login({settings:J,callbacks:j,telemetry:Z})}function eC($,J,Q,Z,W){return c2({manager:$,providerId:J,settings:Q,credentials:Z,setLastUsed:W?.setLastUsed})}async function $y($,J,Q,Z){let W=F4({onPrompt:async(j)=>j.defaultValue??"",openUrl:Q,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return l5($,J,{callbacks:W,telemetry:Z})}function Jy($){let J=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return J&&J.length>0?J:void 0}import*as f5 from"@cline/llms";var Qy=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Zy={"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 Wy($,J){let Q={};for(let Z of Qy){let W=$[Z],j=J[Z];if(W||j)Q[Z]={...W,...j}}return Q}function jy($){let J=Zy[$.providerId];if(!J)return $;return{...$,description:J.description??$.description,fields:J.mode==="replace"?J.fields:Wy($.fields,J.fields)}}var fy=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Xy($,J){if(!J?.provider.baseUrl)return!1;if(J.provider.source!=="system")return!0;return fy.has($)}function Yy($){let J=f5.normalizeProviderId($);if(v2(J))return{providerId:J,authMethod:"oauth",fields:{}};let Q=f5.MODEL_COLLECTIONS_BY_PROVIDER_ID[J];if(Q?.provider.capabilities?.includes("local-auth"))return{providerId:J,authMethod:"local",fields:{}};let Z=Q?.provider.baseUrl,W={apiKey:{}};if(Xy(J,Q))W.baseUrl={defaultValue:Z};return jy({providerId:J,authMethod:"api-key",fields:W})}eJ();F0();rJ();import{appendFileSync as Vy,existsSync as ZW,mkdirSync as Hy,readFileSync as By,renameSync as Ay,unlinkSync as Ky,writeFileSync as Gy}from"node:fs";import{join as WW}from"node:path";import{resolveTeamDataDir as Fy}from"@cline/shared/storage";function Dy($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class jA{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let J=Dy($.teamName),Q=$.baseDir?.trim()||Fy();this.dirPath=WW(Q,J),this.statePath=WW(this.dirPath,"state.json"),this.taskHistoryPath=WW(this.dirPath,"task-history.jsonl")}loadState(){if(!ZW(this.statePath))return;try{let $=By(this.statePath,"utf8"),J=JSON.parse($);if(J.version!==1||!J.teamState)return;for(let Q of J.teammates??[])this.teammateSpecs.set(Q.agentId,Q);return eY(J.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let J={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Q=`${this.statePath}.tmp`;Gy(Q,`${JSON.stringify(J,null,2)}
726
+ `,"utf8"),Ay(Q,this.statePath)}appendTaskHistory($){let J={};switch($.type){case"team_task_updated":J=$.task;break;case"team_message":J={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":J={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":J={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":J={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":J={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Vy(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:J})}
727
+ `,"utf8")}ensureDir(){if(!ZW(this.dirPath))Hy(this.dirPath,{recursive:!0})}hasPersistableState($){let J=$.exportState();if(this.teammateSpecs.size>0)return!0;if(J.members.some((Q)=>Q.role==="teammate"))return!0;return J.tasks.length>0||J.mailbox.length>0||J.missionLog.length>0}clearPersistedState(){if(ZW(this.statePath))Ky(this.statePath)}}import{z as y}from"zod";var fA=y.object({workspaceRoot:y.string().min(1),cwd:y.string().optional(),provider:y.string().min(1),model:y.string().min(1),mode:y.enum(["act","plan"]).default("act"),apiKey:y.string(),systemPrompt:y.string().optional(),rules:y.string().optional(),maxIterations:y.number().int().positive().optional(),enableTools:y.boolean(),enableSpawn:y.boolean().optional(),enableTeams:y.boolean().optional(),autoApproveTools:y.boolean().optional(),missionStepInterval:y.number().int().positive().optional(),missionTimeIntervalMs:y.number().int().positive().optional()}),XA=y.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),YA=y.enum(["user","assistant","tool","system","status","error"]),VA=y.object({id:y.string().min(1),sessionId:y.string().nullable(),role:YA,content:y.string(),createdAt:y.number().int().nonnegative(),meta:y.object({stream:y.enum(["stdout","stderr"]).optional(),toolName:y.string().optional(),iteration:y.number().int().nonnegative().optional(),agentId:y.string().optional(),conversationId:y.string().optional(),hookEventName:y.string().optional(),inputTokens:y.number().int().nonnegative().optional(),outputTokens:y.number().int().nonnegative().optional(),checkpoint:y.object({ref:y.string(),createdAt:y.number().int().nonnegative(),runCount:y.number().int().positive(),kind:y.enum(["stash","commit"]).optional()}).optional()}).optional()}),HA=y.object({toolCalls:y.number().int().nonnegative(),tokensIn:y.number().int().nonnegative(),tokensOut:y.number().int().nonnegative()}),Uy=y.object({sessionId:y.string().nullable(),status:XA,config:fA,messages:y.array(VA),rawTranscript:y.string(),error:y.string().nullable(),summary:HA});var Ry=nX;import{Agent as ds,createAgentRuntime as ls}from"@cline/agents";import{getClineEnvironmentConfig as zy}from"@cline/shared";var Ly=5000,BA={clinePass:[],recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}]};function _y($){return{clinePass:$.clinePass.map((J)=>({...J,tags:[...J.tags]})),recommended:$.recommended.map((J)=>({...J,tags:[...J.tags]})),free:$.free.map((J)=>({...J,tags:[...J.tags]}))}}function jW($){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.id!=="string"||J.id.length===0)return null;return{id:J.id,name:typeof J.name==="string"&&J.name.length>0?J.name:J.id,description:typeof J.description==="string"?J.description:"",tags:Array.isArray(J.tags)?J.tags.filter((Q)=>typeof Q==="string"):[]}}function Oy($){if(!$||typeof $!=="object")return null;let J=$,Q=Array.isArray(J.recommended)?J.recommended:[],Z=Array.isArray(J.free)?J.free:[],W=Array.isArray(J.clinePass)?J.clinePass:[],j=Q.map(jW).filter((Y)=>Y!==null),f=Z.map(jW).filter((Y)=>Y!==null),X=W.map(jW).filter((Y)=>Y!==null);if(j.length===0&&f.length===0&&X.length===0)return null;return{recommended:j,free:f,clinePass:X}}function Ty($){let J=$.baseUrl?.trim();if(J)return J;let Q=zy().apiBaseUrl;try{return($.providerSettingsManager??new Q$).getProviderSettings("cline")?.baseUrl?.trim()||Q}catch{return Q}}async function My($,J,Q){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await $(J,{signal:Z.signal})}finally{clearTimeout(W)}}async function qy($={}){try{let J=Ty($),Q=$.fetchImpl??fetch,Z=await My(Q,`${J}/api/v1/ai/cline/recommended-models`,$.timeoutMs??Ly);if(!Z.ok)throw Error(`HTTP ${Z.status}`);let W=await Z.json(),j=Oy(W);if(j)return j}catch{}return _y(BA)}import{readFile as Py}from"node:fs/promises";import Ny from"node:path";function wy($){return $}async function Sy($){let J=Ny.resolve($),Q=await Py(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse JSON config at "${J}": ${j}`)}return Cy(Z,J)}function Cy($,J){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${J}": expected an object.`);let Z=$.providers;if(!Array.isArray(Z))throw Error(`Invalid llms config in "${J}": "providers" must be an array.`);if(!Z.length)throw Error(`Invalid llms config in "${J}": "providers" cannot be empty.`);return $}import{BUILT_IN_PROVIDER_IDS as GA,createHandler as by,createHandlerAsync as hy,getProviderCollection as ky,hasProvider as FA,registerAsyncHandler as Iy,registerHandler as xy,registerModel as gy,registerProvider as DA}from"@cline/llms";function AA($){return $?{...$}:{}}function yy($,J){if($)return $;if(!J)return;let Q=globalThis.process;if(!Q?.env)return;return Q.env[J]}function Ey($,J){if(!J.length)throw Error(`Provider "${$}" must include at least one model.`)}function KA($){let J=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:J,defaultModel:$.collection.provider.defaultModelId,modelCount:J.length}}class fW{providers=new Map;register($){Ey($.id,$.models);let J=$.defaultModel??$.models[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(J))throw Error(`Default model "${J}" is not included in configured models for "${$.id}".`);let Q=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Q?.models??[],...$.models]),defaultModel:J,defaults:{...Q?.defaults??{},...AA($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:yy($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...AA($.settings)}})}registerModel($,J){let Q=this.providers.get($);if(!Q){this.providers.set($,{id:$,models:new Set([J]),defaultModel:J,defaults:{}});return}Q.models.add(J)}createHandlerConfig($){let J=this.require($.providerId),Q=$.modelId??J.defaultModel;if(!J.models.has(Q))throw Error(`Model "${Q}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Q,...J.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,J){return this.providers.get($)?.models.has(J)??!1}require($){let J=this.providers.get($);if(!J)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return J}}class XW{configuredProviders=new fW;constructor($){this.applyConfig($)}createHandler($){return by(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return hy(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(DA($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)xy($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)Iy($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let J=$.exposeModels??Object.keys($.models),Q=$.defaultModel??J[0];if(!Q)throw Error(`Provider "${$.id}" must define a default model.`);DA({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Q,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:J,defaultModel:Q,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){gy($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...GA]}async getBuiltInProviders(){return(await Promise.all(GA.map((J)=>ky(J)))).filter((J)=>J!==void 0).map((J)=>KA({collection:J}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,J){return this.configuredProviders.hasModel($,J)}applyConfig($){for(let J of $.providers)this.configuredProviders.registerSelectionConfig(J);for(let J of $.models??[])this.registerModel(J);for(let J of $.customProviders??[])this.registerProvider(J);for(let J of this.configuredProviders.list()){let Q=FA(J.id),Z=this.configuredProviders.createHandlerConfig({providerId:J.id,modelId:J.defaultModel}).routingProviderId,W=typeof Z==="string"&&FA(Z);if(!Q&&!W)throw Error(`Provider "${J.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function my($){return new XW($)}T7();async function za(){return Promise.resolve().then(() => (eJ(),mB))}export{QY as writeHubDiscovery,C1 as writeGlobalSettings,ZY as withHubStartupLock,r1 as verifyHubConnection,D8 as updateMcpServerOAuthState,QA as updateLocalProvider,CC as uninstallPlugin,w7 as truncateNotificationBody,ZQ as toggleDisabledTool,VJ as toTeamProgressLifecycleEvent,V1 as toProviderConfig,o_ as toHubStatusUrl,WY as toHubHealthUrl,rZ as toHookConfigFileName,fC as syncPluginMcpServersToSettings,GJ as summarizeUsageFromMessages,jT as stopLocalHubServerGracefully,Y1 as startLocalOAuthServer,u7 as startHubWebSocketServer,Zn as startHubServer,lA as startClineDeviceAuth,_9 as splitCoreSessionConfig,s6 as spawnDetachedHubServerWithRetry,IO as spawnDetachedHubServer,NG as setTelemetryOptOutGlobally,G8 as setMcpServerDisabled,K3 as setDisabledTools,EG as setDisabledPlugin,SG as setAutoUpdateEnabledGlobally,np as sendHubCommand,c2 as saveProviderOAuthCredentials,aC as saveLocalProviderSettings,eC as saveLocalProviderOAuthCredentials,C8 as sanitizeSessionToken,W3 as safeParseSettings,jG as safeCreateProviderConfig,IJ as runSubprocessEvent,gJ as runHook,qf as reviveTeamStateDates,_Y as restartLocalHubIfIdleAfterStartupTimeout,tg as resolveWorkspaceHubOwnerContext,hQ as resolveWorkflowsConfigSearchPaths,EQ as resolveSkillsConfigSearchPaths,D1 as resolveSharedHubOwnerContext,wN as resolveSessionBackend,bQ as resolveRulesConfigSearchPaths,o5 as resolveProviderConfig,qK as resolveProviderApiKeyFromSettings,p1 as resolveProductionHubOwnerContext,a2 as resolvePluginSkillDirectoriesFromPaths,zQ as resolvePluginConfigSearchPaths,m1 as resolveMcpServerRegistrations,Jy as resolveLocalClineAuthToken,Sw as resolveHubUrl,w$ as resolveHubOwnerContext,l1 as resolveHubEndpointOptions,JY as resolveHubBuildId,lZ as resolveHooksConfigSearchPaths,H1 as resolveDisabledToolNames,v4 as resolveDisabledPluginPaths,H0 as resolveDefaultMcpSettingsPath,n6 as resolveDefaultHubPort,YO as resolveDefaultHubPathname,XO as resolveDefaultHubHost,Sf as resolveCoreSelectedToolIds,g0 as resolveCoreDistinctId,VZ as resolveCompatibleLocalHubUrl,ug as resolveClineDir,x8 as resolveClineDataDir,n4 as resolveAndLoadAgentPlugins,n2 as resolveAgentPluginPaths,WZ as requestHubShutdown,oS as requestDesktopToolApproval,i7 as removePluginMcpServersFromSettings,O2 as rememberRecoverableLocalHubUrl,uB as registerRemoteConfigSessionBlobUpload,U8 as registerMcpServersFromSettingsFile,ma as registerDisposable,sC as refreshProviderModelsFromSource,NW as refreshOpenAICodexToken,kW as refreshOcaToken,qW as refreshClineToken,j7 as readSessionCheckpointHistory,cS as readRemoteConfigSessionBlobUploadMetadata,A0 as readHubDiscovery,M0 as readGlobalSettings,hB as readBearerToken,S$ as probeHubServer,ip as probeHubConnection,Ej as prewarmFileIndex,BY as prewarmDetachedHubServer,lS as prepareRemoteConfigCoreIntegration,yQ as parseWorkflowConfigFromMarkdown,ga as parseUserCommandEnvelope,SQ as parseSkillConfigFromMarkdown,Z3 as parseSettings,CQ as parseRuleConfigFromMarkdown,xJ as parseHookEventPayload,UZ as parseConfiguredAgentConfig,T$ as normalizeWorkspacePath,xa as normalizeUserInput,Ia as normalizeSdkError,L0 as normalizeRuntimeCapabilities,k4 as normalizeProviderId,oC as normalizeOAuthProvider,T2 as normalizeHubWebSocketUrl,ka as noopBasicLogger,Q7 as migrateLegacyProviderSettings,J6 as mergeRulesForSystemPrompt,t8 as mergeAgentHooks,d9 as makeTeamTaskSubSessionId,d6 as makeSubSessionId,k5 as loginOpenAICodex,c5 as loginOcaOAuth,tC as loginLocalProvider,b5 as loginClineOAuth,l5 as loginAndSaveProviderOAuthCredentials,$y as loginAndSaveLocalProviderOAuthCredentials,za as loadOpenTelemetryAdapter,K8 as loadMcpSettingsFile,Sy as loadLlmsConfigFromFile,jJ as loadConfiguredAgentConfigs,r2 as loadAgentPluginsFromPathsWithDiagnostics,w3 as loadAgentPluginsFromPaths,KQ as loadAgentPluginFromPath,I_ as listSessionHistoryFromBackend,fX as listPluginToolsWithDiagnostics,L9 as listPluginTools,F9 as listMcpServerOAuthStatuses,iC as listLocalProviders,w2 as listHookConfigFiles,CG as isToolDisabledGlobally,QQ as isTelemetryOptedOutGlobally,O$ as isSessionNotFoundError,i3 as isRuleEnabled,yG as isPluginDisabledGlobally,v2 as isOAuthProvider,tO as isHubReconnectableTransportError,zY as isHubCommandTimeoutError,pg as isDiscoveryFilePresent,AW as isClineAccountActionRequest,JG as isBuiltInProviderId,wG as isAutoUpdateEnabledGlobally,N1 as identifyAccount,L$ as hasMcpSettingsFile,I5 as getValidOpenAICodexCredentials,u5 as getValidOcaCredentials,h5 as getValidClineCredentials,p5 as getProviderOAuthCredentialsFromSettings,Yy as getProviderConfigFields,rW as getProviderConfig,MK as getProviderAuthStorageId,f0 as getProviderAuthHandler,P4 as getPersistedProviderApiKey,F8 as getMcpServerOAuthState,nC as getLocalProviderModels,h4 as getLiveModelsCatalog,F$ as getFileIndex,jq as getCurrentContextSize,H9 as getCoreHeadlessToolNames,wf as getCoreDefaultEnabledToolIds,V8 as getCoreBuiltinToolCatalog,Cf as getCoreAcpToolNames,Ta as getClineDefaultSystemPrompt,P9 as generateWorkspaceInfoWithDiagnostics,c6 as generateWorkspaceInfo,$6 as formatRulesForSystemPrompt,PK as formatProviderOAuthApiKey,ha as formatDisplayUserInput,jQ as filterExtensionToolRegistrations,y1 as filterDisabledTools,WQ as filterDisabledPluginPaths,qy as fetchClineRecommendedModels,KW as executeClineAccountAction,IB as ensureHubWebSocketServer,Wn as ensureHubServer,Vm as ensureDetachedHubServer,JH as ensureCustomProvidersLoaded,m8 as ensureCompatibleLocalHubUrl,R6 as enrichPromptWithMentions,ya as emptyWorkspaceManifest,S2 as emptyStoredProviderSettings,LQ as discoverPluginModulePaths,XC as disablePluginMcpServersInSettings,l9 as deriveSubsessionStatus,ZA as deleteLocalProvider,wy as defineLlmsConfig,xQ as createWorkflowsConfigDefinition,U2 as createUserInstructionConfigService,xj as createToolPoliciesWithPreset,Ca as createTool,zH as createTeamName,kH as createSubprocessHooks,D2 as createSpawnAgentTool,kQ as createSkillsConfigDefinition,kJ as createSessionHost,kJ as createRuntimeHost,IQ as createRulesConfigDefinition,dS as createRemoteConfigSessionMessagesArtifactUploader,WG as createProviderConfig,lJ as createOpenTelemetryTelemetryService,F4 as createOAuthClientCallbacks,I6 as createMcpTools,fr as createLocalHubScheduleRuntimeHandlers,my as createLlmsSdk,U0 as createInitialAccumulatedUsage,lg as createInMemoryHubOwnerContext,F1 as createHubServerUrl,$Y as createHubAuthToken,sZ as createHookConfigFileHooks,LJ as createHookConfigFileExtension,zJ as createHookAuditHooks,z9 as createDisabledMcpToolPolicy,ZX as createDisabledMcpToolPolicies,G2 as createDelegatedAgentConfigProvider,F2 as createDelegatedAgent,gj as createDefaultToolsWithPreset,B2 as createDefaultTools,h6 as createDefaultMcpServerClientFactory,O6 as createDefaultExecutors,L8 as createCoreSettingsService,i1 as createCoreSessionSnapshot,Sa as createContributionRegistry,cZ as createContextCompactionPrepareTurn,c$ as createConfiguredTelemetryService,pJ as createConfiguredTelemetryHandle,XJ as createConfiguredAgentTools,wa as createClineTelemetryServiceMetadata,Na as createClineTelemetryServiceConfig,H8 as createBuiltinTools,Y8 as createAgentTeamsTools,ls as createAgentRuntime,FJ as createAgentHooksExtension,vH as connectToHub,pA as completeClineDeviceAuth,tK as clearPrivateModelsCatalogCache,oK as clearLiveModelsCatalogCache,n0 as clearHubDiscovery,SA as captureWorkspacePathResolved,A5 as captureWorkspaceInitialized,K5 as captureWorkspaceInitError,R5 as captureToolUsage,D5 as captureTokenUsage,F5 as captureTaskRestarted,G5 as captureTaskCreated,U4 as captureTaskCompleted,z4 as captureSubagentExecution,z5 as captureSkillUsed,Pa as captureSdkError,CA as captureProviderConfigured,R4 as captureProviderApiError,U5 as captureModeSwitch,_5 as captureMentionUsed,T5 as captureMentionSearchResults,O5 as captureMentionFailed,q5 as captureHookDiscovery,wA as captureExtensionActivated,L5 as captureDiffEditFailure,g2 as captureConversationTurnEvent,N5 as captureCompactionSkipped,P5 as captureCompactionExecuted,q1 as captureAuthSucceeded,M1 as captureAuthStarted,Y$ as captureAuthLoggedOut,P1 as captureAuthFailed,M5 as captureAgentTeamCreated,V$ as captureAgentCreated,N9 as buildWorkspaceMetadata,YJ as buildTeamProgressSummary,Ma as buildSdkErrorProperties,vB as buildRemoteConfigSessionBlobUploadMetadata,f8 as buildDelegatedAgentConfig,zZ as buildConfiguredAgentToolName,LZ as buildConfiguredAgentToolDescriptors,w6 as bootstrapAgentTeams,lf as authorizeMcpServerOAuth,rC as addLocalProvider,K0 as accumulateUsageTotals,qQ as WORKFLOWS_CONFIG_DIRECTORY_NAME,d2 as UnifiedConfigFileWatcher,$1 as ToolPresets,Y4 as TelemetryService,dJ as TelemetryLoggerSink,N6 as TEAM_TOOL_NAMES,u4 as SubprocessSandbox,_J as StoredProviderSettingsSchema,kV as StoredProviderSettingsEntrySchema,J4 as SqliteTeamStore,s1 as SqliteSessionStore,E2 as SessionVersioningService,a0 as SessionVersioningError,z0 as SessionSource,_$ as SessionNotFoundError,$3 as SapSettingsSchema,MQ as SKILLS_CONFIG_DIRECTORY_NAME,$Q as SESSION_STATUSES,_8 as SESSION_NOT_FOUND_ERROR_CODE,va as SDK_ERROR_TELEMETRY_EVENT,B5 as RpcClineAccountService,$J as RemoteRuntimeHost,sW as ReasoningSettingsSchema,v3 as RULES_CONFIG_DIRECTORY_NAME,cB as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,e$ as ProviderSettingsSchema,Q$ as ProviderSettingsManager,iW as ProviderProtocolSchema,e5 as ProviderIdSchema,nW as ProviderClientSchema,V4 as OpenTelemetryProvider,J3 as OcaSettingsSchema,s5 as OPENAI_COMPATIBLE_PROVIDERS,U1 as NodeHubClient,f4 as NoOpFeatureFlagsProvider,m7 as NativeHubTransportAdapter,Q3 as ModelCatalogSettingsSchema,Z$ as LocalRuntimeHost,_a as Llms,OJ as InMemoryWorkspaceManager,R8 as InMemoryMcpManager,hw as HubUIClient,x0 as HubTransportError,bw as HubSessionClient,tJ as HubServerTransport,uJ as HubScheduleService,mJ as HubScheduleCommandService,b$ as HubRuntimeHost,o6 as HubCommandError,bH as HookEventPayloadSchema,EH as HookEventNameSchema,DJ as HookConfigFileName,pZ as HOOK_CONFIG_FILE_EVENT_MAP,PV as HOOKS_CONFIG_DIRECTORY_NAME,m4 as GlobalSettingsSchema,tW as GcpSettingsSchema,jA as FileTeamPersistenceStore,j4 as FeatureFlagsService,ba as FeatureFlagDefaultValue,Ea as FEATURE_FLAGS,BA as FALLBACK_CLINE_RECOMMENDED_MODELS,D0 as DefaultToolNames,EJ as DefaultRuntimeBuilder,XW as DefaultLlmsSdk,dW as DEFAULT_MODELS_CATALOG_URL,jO as DEFAULT_HUB_PORT,fO as DEFAULT_HUB_PATHNAME,WO as DEFAULT_HUB_HOST,_2 as CoreSettingsService,o1 as CoreSessionService,qa as ContributionRegistry,_7 as ClineCore,H5 as ClineAccountService,Uy as ChatViewStateSchema,HA as ChatSummarySchema,XA as ChatSessionStatusSchema,fA as ChatSessionConfigSchema,VA as ChatMessageSchema,YA as ChatMessageRoleSchema,k as CORE_TELEMETRY_EVENTS,Ry as CORE_BUILD_VERSION,g7 as BrowserWebSocketHubAdapter,$G as BUILT_IN_PROVIDER_IDS,t5 as BUILT_IN_PROVIDER,eW as AzureSettingsSchema,oW as AwsSettingsSchema,aW as AuthSettingsSchema,l8 as AgentTeamsRuntime,OZ as AgentTeam,ds as Agent,X2 as ALL_DEFAULT_TOOL_NAMES};