@cline/core 0.0.61 → 0.0.62

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/hub/index.js CHANGED
@@ -1,19 +1,19 @@
1
- import{createRequire as b_}from"node:module";var{defineProperty:q7,getOwnPropertyNames:C_}=Object;var gY=Object.prototype.hasOwnProperty;function mY($){return this[$]}var R=($,W,Z)=>{var Q=C_(W);for(let J of Q)if(!gY.call($,J)&&J!=="default")q7($,J,{get:mY.bind(W,J),enumerable:!0});if(Z){for(let J of Q)if(!gY.call(Z,J)&&J!=="default")q7(Z,J,{get:mY.bind(W,J),enumerable:!0});return Z}};var P_=($)=>$;function S_($,W){this[$]=P_.bind(null,W)}var w=($,W)=>{for(var Z in W)q7($,Z,{get:W[Z],enumerable:!0,configurable:!0,set:S_.bind(W,Z)})};var $2=($,W)=>()=>($&&(W=$($=0)),W);var vY=b_(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as AL,captureAgentUnexpectedReasoningTokens as HV,SDK_ERROR_TELEMETRY_EVENT as UL}from"@cline/shared";function a($,W,Z){$?.capture({event:W,properties:Z})}function uW($){if(!$)return;return $.substring(0,fL)}function DL($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function _L($){return typeof $==="string"?$:$.message}function BV($,W){return $.some((Z)=>W.has(Z.trim().toLowerCase()))}function GV($){a($,v.CLIENT.EXTENSION_ACTIVATED)}function dW($,W){let Z=[...W.vcs_types],Q={root_count:W.root_count,vcs_types:Z,is_multi_root:W.root_count>1,has_git:BV(Z,new Set(["git"])),has_mercurial:BV(Z,new Set(["mercurial","hg"]))};if(W.init_duration_ms!==void 0)Q.init_duration_ms=W.init_duration_ms;if(W.feature_flag_enabled!==void 0)Q.feature_flag_enabled=W.feature_flag_enabled;if(W.is_remote_workspace!==void 0)Q.is_remote_workspace=W.is_remote_workspace;a($,v.WORKSPACE.INITIALIZED,Q)}function lW($,W,Z){a($,v.WORKSPACE.INIT_ERROR,{error_type:DL(W),error_message:uW(_L(W)),fallback_to_single_root:Z.fallback_to_single_root,workspace_count:Z.workspace_count??0})}function KV($,W){a($,v.WORKSPACE.PATH_RESOLVED,{...W})}function x1($,W){a($,v.USER.AUTH_STARTED,{provider:W})}function g1($,W){a($,v.USER.AUTH_SUCCEEDED,{provider:W})}function m1($,W,Z){a($,v.USER.AUTH_FAILED,{provider:W,errorMessage:uW(Z)})}function _$($,W,Z,Q){a($,v.USER.AUTH_LOGGED_OUT,{provider:W,reason:Z,status:Q?.status,errorCode:Q?.errorCode})}function g7($,W,Z){a($,v.USER.AUTH_REFRESH_SOFT_FAILURE,{provider:W,status:Z?.status,errorCode:Z?.errorCode,errorName:Z?.errorName,tokenExpired:Z?.tokenExpired})}function FV($,W){a($,v.USER.PROVIDER_CONFIGURED,{provider:W})}function AV($,W){$?.captureRequired(v.USER.TELEMETRY_OPT_OUT,W)}function v1($,W){let Z=W.id?.trim();if(Z)$?.setDistinctId(Z);$?.updateCommonProperties({user_id:Z||W.id,account_id:W.id,account_email:W.email,provider:W.provider,organization_id:W.organizationId,organization_name:W.organizationName,member_id:W.memberId})}function pW($,W){a($,v.TASK.CREATED,W)}function rW($,W){a($,v.TASK.RESTARTED,W)}function j4($,W){a($,v.TASK.COMPLETED,W)}function D8($,W){a($,v.TASK.CONVERSATION_TURN,{...W,timestamp:new Date().toISOString()})}function iW($,W){a($,v.TASK.TOKEN_USAGE,W)}function nW($,W,Z){a($,v.TASK.MODE_SWITCH,{ulid:W,mode:Z})}function _8($,W){a($,v.TASK.TOOL_USED,W)}function aW($,W){a($,v.TASK.SKILL_USED,W)}function oW($,W){a($,v.TASK.DIFF_EDIT_FAILED,W)}function X4($,W){a($,v.TASK.PROVIDER_API_ERROR,{...W,errorMessage:uW(W.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function UV($,W){a($,v.SDK.TOOL_TIMEOUT,LL(W))}function LL($){let W={};for(let[Z,Q]of Object.entries($))if(Q!==void 0)W[Z]=Q;return W}function sW($,W,Z){a($,v.TASK.MENTION_USED,{mentionType:W,contentLength:Z,timestamp:new Date().toISOString()})}function tW($,W,Z,Q){a($,v.TASK.MENTION_FAILED,{mentionType:W,errorType:Z,errorMessage:uW(Q),timestamp:new Date().toISOString()})}function eW($,W,Z,Q,J){a($,v.TASK.MENTION_SEARCH_RESULTS,{queryLength:W.length,resultCount:Z,searchType:Q,isEmpty:J,timestamp:new Date().toISOString()})}function L$($,W){a($,v.TASK.AGENT_CREATED,{...W,timestamp:new Date().toISOString()})}function $9($,W){a($,v.TASK.AGENT_TEAM_CREATED,{...W,timestamp:new Date().toISOString()})}function Y4($,W){a($,W.event==="ended"?v.TASK.SUBAGENT_COMPLETED:v.TASK.SUBAGENT_STARTED,{...W,timestamp:new Date().toISOString()})}function W9($,W,Z,Q){a($,v.HOOKS.DISCOVERY_COMPLETED,{hookName:W,globalCount:Z,workspaceCount:Q,totalCount:Z+Q,timestamp:new Date().toISOString()})}function Z9($,W){a($,v.TASK.COMPACTION_EXECUTED,{...W,timestamp:new Date().toISOString()})}function Q9($,W){a($,v.TASK.COMPACTION_SKIPPED,{...W,timestamp:new Date().toISOString()})}function fV($,W){a($,v.TASK.COMPACTION_BUDGET_EMERGENCY,{...W,timestamp:new Date().toISOString()})}var fL=500,v;var M0=$2(()=>{v={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:AL},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",AUTH_REFRESH_SOFT_FAILURE:"user.auth_refresh_soft_failure",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",COMPACTION_BUDGET_EMERGENCY:"task.compaction_budget_emergency"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:UL,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as TL,readFileSync as OL,statSync as zL,writeFileSync as qL}from"node:fs";import{dirname as ML}from"node:path";import{resolveGlobalSettingsPath as _V}from"@cline/shared/storage";import{z as J2}from"zod";function J9(){return V4.parse({})}function NL(){j9=void 0}function EL($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function wL($){let W;try{W=OL($,"utf8")}catch{return J9()}try{let Z=V4.safeParse(JSON.parse(W));return Z.success?Z.data:J9()}catch{return J9()}}function CL(){let $=_V(),W=zL($,{throwIfNoEntry:!1}),Z=W?.mtimeMs??0,Q=W?.size??0,J=j9;if(J&&J.path===$&&J.mtimeMs===Z&&J.size===Q)return J;let j=EL(W?wL($):J9());return j9={path:$,mtimeMs:Z,size:Q,value:j},j9}function R0(){return CL().value}function _1($,W={}){let Z=_V(),Q=R0();TL(ML(Z),{recursive:!0});let J=V4.parse($);if(!Q.telemetryOptOut&&J.telemetryOptOut)AV(W.telemetry);qL(Z,`${JSON.stringify(J,null,2)}
2
- `,"utf8"),NL()}function X9(){return R0().telemetryOptOut}function LV($,W={}){_1({...R0(),telemetryOptOut:$},W)}function TV(){return R0().autoUpdateEnabled}function OV($,W={}){_1({...R0(),autoUpdateEnabled:$},W)}function zV(){return R0().compactionStrategy??"basic"}function qV($){_1({...R0(),compactionStrategy:$})}function L1($){return new Set($??R0().disabledTools??[])}function B4($){return new Set($??R0().disabledPlugins??[])}function MV($){return L1().has($)}function Y9($){let W=R0(),Z=new Set(W.disabledTools??[]),Q=Z.has($);if(Q)Z.delete($);else Z.add($);return _1({...W,disabledTools:[...Z]}),!Q}function m7($,W){let Z=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Z.length===0)return;let Q=R0(),J=L1(Q.disabledTools);for(let j of Z)if(W)J.add(j);else J.delete(j);_1({...Q,disabledTools:[...J]})}function RV($,W){return m7([$],W),W}function NV($){return B4().has($)}function EV($,W){let Z=$.trim();if(!Z)return;let Q=R0(),J=B4(Q.disabledPlugins);if(W)J.add(Z);else J.delete(Z);_1({...Q,disabledPlugins:[...J]})}function V9($,W){let Z=B4(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q))}function c1($,W){let Z=L1(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q.name))}function B9($,W){if(!$||$.length===0)return $;let Z=L1(W);if(Z.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,j)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},j)}})}var DV,RL,V4,j9;var X1=$2(()=>{M0();DV=J2.preprocess(($)=>Array.isArray($)?$.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean):void 0,J2.array(J2.string()).optional()).transform(($)=>{if(!$)return;let W=[...new Set($)].sort((Z,Q)=>Z.localeCompare(Q));return W.length>0?W:void 0}),RL=J2.enum(["basic","agentic"]).catch("basic"),V4=J2.object({telemetryOptOut:J2.boolean().default(!1).catch(!1),autoUpdateEnabled:J2.boolean().default(!0).catch(!0),compactionStrategy:RL.optional(),disabledTools:DV.optional(),disabledPlugins:DV.optional()}).strip().transform(($)=>{let W={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.compactionStrategy)W.compactionStrategy=$.compactionStrategy;if($.disabledTools?.length)W.disabledTools=$.disabledTools;if($.disabledPlugins?.length)W.disabledPlugins=$.disabledPlugins;return W})});import{existsSync as PL,mkdirSync as SL,readFileSync as bL,writeFileSync as yL}from"node:fs";import{resolve as hL}from"node:path";import{resolveSessionDataDir as kL}from"@cline/shared/storage";import{nanoid as IL}from"nanoid";import*as xL from"node-machine-id";function I0($){let W=$?.trim();if(W)return W;let Z=vL();if(Z)return Z;return cL()}function mL(){let $=xL;return $.machineIdSync??$.default?.machineIdSync}function vL(){try{let $=mL();if(!$)return;return $().trim()||void 0}catch{return}}function cL(){let $=kL(),W=hL($,gL);try{if(PL(W)){let Q=bL(W,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${IL()}`;try{SL($,{recursive:!0}),yL(W,Z,"utf8")}catch{}return Z}var gL="machine-id";var L8=()=>{};class G4{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($,W){if(!this.isEnabled())return;this.emitLog($,W,!1)}emitRequired($,W){this.emitLog($,W,!0)}recordCounter($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,j);j.add(W,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,j);j.record(W,this.flattenProperties(this.buildAttributes(Z)))}recordGauge($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.buildAttributes(Z),X=JSON.stringify(j),Y=this.gaugeValues.get($);if(W===null){if(Y){if(Y.delete(X),Y.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=Y;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let B=this.meter.createObservableGauge($,Q?{description:Q}:void 0);B.addCallback((H)=>{for(let G of this.snapshotGaugeSeries($))H.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,B)}V.set(X,{value:W,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($,W,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(W,Z));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,W=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...W?{_required:!0}:{}}}snapshotGaugeSeries($){let W=this.gaugeValues.get($);if(!W)return[];return Array.from(W.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties($,W="",Z=new WeakSet,Q=0){if(!$)return{};let J={},j=100,X=10;for(let[Y,V]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let B=W?`${W}.${Y}`:Y;if(V===null||V===void 0){J[B]=String(V);continue}if(Array.isArray(V)){let H=V.length>j?V.slice(0,j):V;try{J[B]=JSON.stringify(H)}catch{J[B]="[UnserializableArray]"}if(V.length>j)J[`${B}_truncated`]=!0,J[`${B}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[B]=V.toISOString();continue}if(V instanceof Error){J[B]=V.message;continue}if(Z.has(V)){J[B]="[Circular]";continue}if(Q>=X){J[B]="[MaxDepthExceeded]";continue}Z.add(V),Object.assign(J,this.flattenProperties(V,B,Z,Q+1));continue}if(uL(V)){J[B]=V;continue}try{J[B]=JSON.stringify(V)}catch{J[B]=String(V)}}return J}}function uL($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class K4{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,W){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:W})}emitRequired($,W){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:W})}recordCounter($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordHistogram($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordGauge($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:W,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class T8{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new K4({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 W=this.buildAttributes($.properties);for(let Z of this.adapters)Z.emit($.event,W)}captureRequired($,W){let Z=this.buildAttributes(W);for(let Q of this.adapters)Q.emitRequired($,Z)}recordCounter($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter($,W,j,Q,J)}recordHistogram($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram($,W,j,Q,J)}recordGauge($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge($,W,j,Q,J)}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 v7=()=>{};import{metrics as dL,trace as lL}from"@opentelemetry/api";import{logs as pL}from"@opentelemetry/api-logs";import{OTLPLogExporter as rL}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as iL}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as nL}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as aL}from"@opentelemetry/resources";import{BatchLogRecordProcessor as oL,ConsoleLogRecordExporter as sL,LoggerProvider as tL}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as eL,MeterProvider as $T,PeriodicExportingMetricReader as wV}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as WT,ConsoleSpanExporter as ZT,SimpleSpanProcessor as QT}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as JT}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as jT,ATTR_SERVICE_VERSION as XT}from"@opentelemetry/semantic-conventions";class CV{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($,W){this.resolveProperties(W)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class O8{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let W=aL({[jT]:$.serviceName??"cline",...$.serviceVersion?{[XT]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(W),this.loggerProvider=this.createLoggerProvider(W),this.tracerProvider=this.createTracerProvider(W),this.meterProvider)dL.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)pL.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",W){return lL.getTracer($,W??this.options.serviceVersion)}createAdapter($){return new G4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let W=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new T8({...$,adapters:[W],distinctId:I0($.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 W=c7(this.options.metricsExporter);if(W.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=W.map((j)=>BT(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((j)=>j!==null);if(J.length===0)return null;return new $T({resource:$,readers:J})}createTracerProvider($){let W=c7(this.options.tracesExporter);if(W.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let j of W){let X=VT(j,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new JT({resource:$,spanProcessors:J})}createLoggerProvider($){let W=c7(this.options.logsExporter);if(W.length===0)return null;let Z=W.map((Q)=>{let J=YT(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new oL(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new tL({resource:$,processors:Z})}}function F4($){let W=new O8($),Z=W.createTelemetryService($);return Z.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:W,telemetry:Z}}function u1($){if(X9())return{telemetry:new CV($)};if($.enabled!==!0)return{telemetry:new T8({...$,distinctId:I0($.distinctId)})};return F4($)}function z8($){let{telemetry:W,provider:Z}=u1($);return{telemetry:W,provider:Z,flush:async()=>{let j=Z;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([W.dispose(),Z?.dispose()])}}}function c7($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function YT($,W){if($==="console")return new sL;if(!W.endpoint)return null;let Z=u7(W.endpoint,"/v1/logs");return new rL({url:Z,headers:W.headers})}function VT($,W){if($==="console")return new QT(new ZT);if(!W.endpoint)return null;let Z=u7(W.endpoint,"/v1/traces");return new WT(new nL({url:Z,headers:W.headers}))}function BT($,W){if($==="console")return new wV({exporter:new eL,exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout});if(!W.endpoint)return null;let Z=u7(W.endpoint,"/v1/metrics");return new wV({exporter:new iL({url:Z,headers:W.headers}),exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout})}function u7($,W){let Z=new URL($),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith(W)?Q:`${Q}${W}`,Z.toString()}var H9=$2(()=>{X1();L8();v7()});var TG={};w(TG,{normalizeUserMessage:()=>MR,buildInitialUserContent:()=>qR});async function qR($,W,Z,Q){let J=RR(W),j=await ER(Z,Q);if(J.length===0&&!j)return $;let X=[{type:"text",text:$},...J];if(j)X.push(...j);return X}function MR($){if($==null)return"";if(typeof $==="string")return $;let W=$.content;if(typeof W==="string")return W;if(!Array.isArray(W))return"";let Z=[];for(let Q of W)if(Q&&typeof Q==="object"&&Q.type==="text"){let J=Q.text;if(typeof J==="string")Z.push(J)}return Z.join(`
3
- `)}function RR($){if(!$||$.length===0)return[];let W=[];for(let Z of $){let Q=NR(Z);if(Q)W.push(Q)}return W}function NR($){let W=$.trim();if(!W)return;let Z=W.match(/^data:([^;,]+);base64,(.+)$/);if(Z){let Q=Z[1],J=Z[2];if(!Q||!J)return;return{type:"image",mediaType:Q,data:J}}return{type:"image",mediaType:"image/png",data:W}}async function ER($,W){if(!$||$.length===0)return;let Z=W??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(J)=>{let j=J.replace(/\\/g,"/");try{let X=await Z(J);return{type:"file",path:j,content:X}}catch(X){let Y=X instanceof Error?X.message:String(X);return{type:"file",path:j,content:`Error fetching content: ${Y}`}}}));if(Q.length===0)return;return Q}var rF={};w(rF,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>_6,updateMcpServerOAuthStateAsync:()=>p5,updateMcpServerOAuthState:()=>r2,setMcpServerDisabled:()=>l2,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>i2,normalizeMcpServerOAuthState:()=>L6,loadMcpSettingsFile:()=>d2,listMcpServerOAuthStatuses:()=>r5,hasMcpSettingsFile:()=>j$,getMcpServerOAuthState:()=>p2,McpSettingsUpdateSkippedError:()=>D6,McpSettingsMutatorPurityError:()=>c$,McpSettingsLockTimeoutError:()=>u$});import{existsSync as SF,mkdirSync as Wj,readFileSync as bF,renameSync as Jj,rmdirSync as MC,rmSync as Zj,statSync as RC,unlinkSync as yF,writeFileSync as hF}from"node:fs";import{randomUUID as NC}from"node:crypto";import{dirname as kF,join as PF}from"node:path";import{setTimeout as EC}from"node:timers/promises";import{resolveMcpSettingsPath as wC}from"@cline/shared/storage";import{z as S}from"zod";function Qj($){if(!$)return;if($==="http")return"streamableHttp";return $}function J0(){return wC()}function mC($,W){Wj(kF($),{recursive:!0});let Z=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{hF(Z,W,{encoding:"utf8",flag:"wx"}),Jj(Z,$)}catch(Q){try{yF(Z)}catch{}throw Q}}function cC($){Atomics.wait(vC,0,0,$)}function uC($){return`${$}.lock`}function mF(){return`${process.pid}.${Date.now()}.${NC()}`}function vF($,W){Wj(kF($),{recursive:!0});let Z=`${$}.tmp.${W}`;Zj(Z,{recursive:!0,force:!0}),Wj(Z,{recursive:!0}),hF(PF(Z,`owner.${W}`),W,{encoding:"utf8",flag:"wx"});try{return Jj(Z,$),{lockDir:$,ownerFile:PF($,`owner.${W}`)}}catch(Q){if(Zj(Z,{recursive:!0,force:!0}),SF($))return;throw Q}}function cF($,W){let Z;try{Z=Date.now()-RC($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Z<Xj)return;W.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Z}ms); reclaiming.`,{severity:"warn"});let Q=`${$}.stale.${mF()}`;try{Jj($,Q)}catch(J){if(J.code==="ENOENT")return;throw J}Zj(Q,{recursive:!0,force:!0})}function dC($){try{yF($.ownerFile)}catch(W){if(W.code!=="ENOENT")throw W}try{MC($.lockDir)}catch(W){let Z=W.code;if(Z!=="ENOENT"&&Z!=="ENOTEMPTY"&&Z!=="EEXIST")throw W}}function uF($){let W=uC($);if(tZ.has(W))throw Error(`Reentrant MCP settings update for ${$}. Keep mutators pure: compute values up front and do not call back into the settings API.`);return{lockDir:W,token:mF()}}function lC($,W){let{lockDir:Z,token:Q}=uF($),J=W.timeoutMs??Xj,j=Date.now();while(!0){let X=vF(Z,Q);if(X)return tZ.add(Z),X;if(Date.now()-j>J)throw new u$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);cF(Z,W),cC(gF)}}async function pC($,W){let{lockDir:Z,token:Q}=uF($),J=W.timeoutMs??Xj,j=Date.now();while(!0){let X=vF(Z,Q);if(X)return tZ.add(Z),X;if(Date.now()-j>J)throw new u$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);cF(Z,W),await EC(gF)}}function dF($,W,Z){try{let Q=rC(W),J=iC(Q,Z);return mC(W,`${JSON.stringify(Q,null,2)}
4
- `),J}finally{tZ.delete($.lockDir),dC($)}}function A1($,W,Z={}){let Q=lC($,Z);return dF(Q,$,W)}async function _6($,W,Z={}){let Q=await pC($,Z);return dF(Q,$,W)}function rC($){let W=aC($);if(!W.mcpServers||typeof W.mcpServers!=="object"||Array.isArray(W.mcpServers))W.mcpServers={};return W}function iC($,W){let Z=JSON.stringify($),Q=JSON.parse(Z),J=W(Q),j=JSON.stringify(Q),X=W($);if(JSON.stringify($)!==j)throw new c$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(X)!==JSON.stringify(J))throw new c$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return X}function nC($){let W=bF($,"utf8"),Z;try{Z=JSON.parse(W)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Z}function aC($){try{return nC($)}catch(W){if(W.code==="ENOENT")return{};throw W}}function lF($,W){if(!Object.hasOwn($,W))return;let Z=$[W];if(!Z||typeof Z!=="object"||Array.isArray(Z))return;return Z}function oC($,W,Z){Object.defineProperty($,W,{value:Z,enumerable:!0,configurable:!0,writable:!0})}function d2($={}){let W=$.filePath??J0(),Z=bF(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(j){let X=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${W}": ${X}`)}let J=gC.safeParse(Q);if(!J.success){let j=J.error.issues.map((X)=>{let Y=X.path.join(".");return Y?`${Y}: ${X.message}`:X.message}).join("; ");throw Error(`Invalid MCP settings at "${W}": ${j}`)}return J.data}function L6($){if(!$)return;let W={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(W).length>0?W:void 0}function sC($){if($===void 0)return;let W=jj.safeParse($);if(!W.success)return;return L6(W.data)}function j$($={}){let W=$.filePath??J0();return SF(W)}function t0($={}){let W=d2($);return Object.entries(W.mcpServers).map(([Z,Q])=>({name:Z,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function l2($){let W=$.filePath??J0(),Z=$.name.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");A1(W,(Q)=>{let J=Q.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${W}": mcpServers must be an object.`);let j={...J},X=lF(j,Z);if(!X)throw Error(`Unknown MCP server: ${Z}`);let Y={...X};if($.disabled)Y.disabled=!0;else delete Y.disabled;oC(j,Z,Y),Q.mcpServers=j})}function p2($,W={}){let Z=d2(W);if(!Object.hasOwn(Z.mcpServers,$))return;return L6(Z.mcpServers[$]?.oauth)}function pF($,W){return(Z)=>{let Q=Z.mcpServers,J=lF(Q,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let j=sC(J.oauth)??{},X=L6(W(j));if(X)J.oauth=X;else delete J.oauth;return X??{}}}function r2($,W,Z={}){let Q=Z.filePath??J0();return A1(Q,pF($,W))}async function p5($,W,Z={}){let Q=Z.filePath??J0();return _6(Q,pF($,W))}function r5($={}){return t0($).map((Z)=>{let Q=Z.transport.type!=="stdio",J=Z.oauth?.tokens?.access_token;return{serverName:Z.name,oauthSupported:Q,oauthConfigured:Q&&typeof J==="string"&&J.trim().length>0,lastError:Z.oauth?.lastError,lastAuthenticatedAt:Z.oauth?.lastAuthenticatedAt}}).sort((Z,Q)=>Z.serverName.localeCompare(Q.serverName))}async function i2($,W={}){let Z=t0(W);for(let Q of Z)await $.registerServer(Q);return Z}var l5,IF,jj,CC,PC,SC,bC,yC,hC,xF,kC,IC,xC,gC,D6,u$,c$,Xj=1e4,gF=25,vC,tZ;var eZ=$2(()=>{l5=S.record(S.string(),S.string()),IF=S.record(S.string(),S.unknown()),jj=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),CC=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:l5.optional()}),PC=S.object({type:S.literal("sse"),url:S.string().url(),headers:l5.optional()}),SC=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:l5.optional()}),bC=S.discriminatedUnion("type",[CC,PC,SC]),yC=S.object({transport:bC,disabled:S.boolean().optional(),metadata:IF.optional(),oauth:jj.optional()}),hC=S.enum(["stdio","sse","http","streamableHttp"]).optional(),xF=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:hC,disabled:S.boolean().optional(),metadata:IF.optional(),oauth:jj.optional()});kC=xF.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:l5.optional()}).superRefine(($,W)=>{let Z=$.type??Qj($.transportType);if(Z&&Z!=="stdio")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),IC=xF.extend({url:S.string().url(),headers:l5.optional()}).superRefine(($,W)=>{let Z=$.type??Qj($.transportType)??"sse";if(Z!=="sse"&&Z!=="streamableHttp")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??Qj($.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}}),xC=S.union([yC,kC,IC]),gC=S.object({mcpServers:S.record(S.string(),xC)}).passthrough();D6=class D6 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};u$=class u$ extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};c$=class c$ extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};vC=new Int32Array(new SharedArrayBuffer(4)),tZ=new Set});var mU={};w(mU,{resolveCoreDistinctId:()=>I0,createOpenTelemetryTelemetryService:()=>F4,createConfiguredTelemetryService:()=>u1,createConfiguredTelemetryHandle:()=>z8,OpenTelemetryProvider:()=>O8,OpenTelemetryAdapter:()=>G4});var qQ=$2(()=>{L8();H9()});var AD={};w(AD,{writeHubDiscovery:()=>F9,withHubStartupLock:()=>A9,verifyHubConnection:()=>z1,truncateNotificationBody:()=>EW,toHubStatusUrl:()=>r7,toHubHealthUrl:()=>U9,stopLocalHubServerGracefully:()=>J3,startHubWebSocketServer:()=>PW,startHubServer:()=>KD,spawnDetachedHubServerWithRetry:()=>R8,spawnDetachedHubServer:()=>t7,sendHubCommand:()=>JB,restartLocalHubIfIdleAfterStartupTimeout:()=>T9,resolveWorkspaceHubOwnerContext:()=>cV,resolveSharedHubOwnerContext:()=>V1,resolveProductionHubOwnerContext:()=>O1,resolveHubUrl:()=>j3,resolveHubOwnerContext:()=>p1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>K9,resolveDefaultHubPort:()=>M8,resolveDefaultHubPathname:()=>s7,resolveDefaultHubHost:()=>o7,resolveCompatibleLocalHubUrl:()=>_4,resolveClineDir:()=>xV,resolveClineDataDir:()=>X2,requestHubShutdown:()=>D4,rememberRecoverableLocalHubUrl:()=>T$,readHubDiscovery:()=>U0,readBearerToken:()=>F7,probeHubServer:()=>r1,probeHubConnection:()=>QB,prewarmDetachedHubServer:()=>D9,normalizeHubWebSocketUrl:()=>O$,isLocalHubOrigin:()=>JY,isLocalHubHostName:()=>A7,isHubReconnectableTransportError:()=>Z3,isHubCommandTimeoutError:()=>L9,isDiscoveryFilePresent:()=>mV,ensureHubWebSocketServer:()=>U7,ensureHubServer:()=>FD,ensureDetachedHubServer:()=>iV,ensureCompatibleLocalHubUrl:()=>B2,createLocalHubScheduleRuntimeHandlers:()=>GD,createInMemoryHubOwnerContext:()=>gV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>G9,createConfiguredTelemetryService:()=>u1,createConfiguredTelemetryHandle:()=>z8,connectToHub:()=>O9,clearHubDiscovery:()=>x0,NodeHubClient:()=>B1,NativeHubTransportAdapter:()=>CW,HubUIClient:()=>V3,HubTransportError:()=>b0,HubSessionClient:()=>Y3,HubServerTransport:()=>n6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>K8,HubCommandError:()=>N8,DEFAULT_HUB_PORT:()=>n7,DEFAULT_HUB_PATHNAME:()=>a7,DEFAULT_HUB_HOST:()=>i7,BrowserWebSocketHubAdapter:()=>wW});import{createSessionId as y_}from"@cline/shared";function p0($,W){return{version:$.version,requestId:$.requestId,ok:!0,payload:W}}function cY($,W,Z){return{version:$.version,requestId:$.requestId??y_("hubreq_"),ok:!1,error:{code:W,message:Z}}}class K8{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return p0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return p0($,{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 p0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return p0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return p0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return p0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return p0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return p0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return p0($,{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 p0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return p0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return p0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return cY($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(W){return cY($,"schedule_command_failed",W instanceof Error?W.message:String(W))}}toCreateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:W}}toUpdateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:W}}}class s6{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},W=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of W)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let Z=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of Z)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as u_}from"node:path";import{buildClineSystemPrompt as d_}from"@cline/shared";import{nowIso as sY}from"@cline/shared/db";var T0={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"},U$=[T0.READ_FILES,T0.SEARCH_CODEBASE,T0.RUN_COMMANDS,T0.FETCH_WEB_CONTENT,T0.APPLY_PATCH,T0.EDITOR,T0.SKILLS,T0.ASK,T0.SUBMIT_AND_EXIT];var dY={};w(dY,{mergeRulesForSystemPrompt:()=>A8,loadRulesForSystemPromptFromWatcher:()=>M7,listEnabledRulesFromWatcher:()=>uY,isRuleEnabled:()=>IW,formatRulesForSystemPrompt:()=>F8});function IW($){return $.disabled!==!0}function F8($){if($.length===0)return"";return`
1
+ import{createRequire as gf}from"node:module";var{defineProperty:w7,getOwnPropertyNames:kf}=Object;var nY=Object.prototype.hasOwnProperty;function aY($){return this[$]}var M=($,W,Z)=>{var Q=kf(W);for(let J of Q)if(!nY.call($,J)&&J!=="default")w7($,J,{get:aY.bind(W,J),enumerable:!0});if(Z){for(let J of Q)if(!nY.call(Z,J)&&J!=="default")w7(Z,J,{get:aY.bind(W,J),enumerable:!0});return Z}};var If=($)=>$;function xf($,W){this[$]=If.bind(null,W)}var w=($,W)=>{for(var Z in W)w7($,Z,{get:W[Z],enumerable:!0,configurable:!0,set:xf.bind(W,Z)})};var W2=($,W)=>()=>($&&(W=$($=0)),W);var oY=gf(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as OL,captureAgentUnexpectedReasoningTokens as TV,SDK_ERROR_TELEMETRY_EVENT as zL}from"@cline/shared";function a($,W,Z){$?.capture({event:W,properties:Z})}function o9($){if(!$)return;return $.substring(0,qL)}function ML($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function RL($){return typeof $==="string"?$:$.message}function LV($,W){return $.some((Z)=>W.has(Z.trim().toLowerCase()))}function OV($){a($,v.CLIENT.EXTENSION_ACTIVATED)}function s9($,W){let Z=[...W.vcs_types],Q={root_count:W.root_count,vcs_types:Z,is_multi_root:W.root_count>1,has_git:LV(Z,new Set(["git"])),has_mercurial:LV(Z,new Set(["mercurial","hg"]))};if(W.init_duration_ms!==void 0)Q.init_duration_ms=W.init_duration_ms;if(W.feature_flag_enabled!==void 0)Q.feature_flag_enabled=W.feature_flag_enabled;if(W.is_remote_workspace!==void 0)Q.is_remote_workspace=W.is_remote_workspace;a($,v.WORKSPACE.INITIALIZED,Q)}function t9($,W,Z){a($,v.WORKSPACE.INIT_ERROR,{error_type:ML(W),error_message:o9(RL(W)),fallback_to_single_root:Z.fallback_to_single_root,workspace_count:Z.workspace_count??0})}function zV($,W){a($,v.WORKSPACE.PATH_RESOLVED,{...W})}function g1($,W){a($,v.USER.AUTH_STARTED,{provider:W})}function m1($,W){a($,v.USER.AUTH_SUCCEEDED,{provider:W})}function v1($,W,Z){a($,v.USER.AUTH_FAILED,{provider:W,errorMessage:o9(Z)})}function L$($,W,Z,Q){a($,v.USER.AUTH_LOGGED_OUT,{provider:W,reason:Z,status:Q?.status,errorCode:Q?.errorCode})}function d7($,W,Z){a($,v.USER.AUTH_REFRESH_SOFT_FAILURE,{provider:W,status:Z?.status,errorCode:Z?.errorCode,errorName:Z?.errorName,tokenExpired:Z?.tokenExpired})}function qV($,W){a($,v.USER.PROVIDER_CONFIGURED,{provider:W})}function MV($,W){$?.captureRequired(v.USER.TELEMETRY_OPT_OUT,W)}function c1($,W){let Z=W.id?.trim();if(Z)$?.setDistinctId(Z);$?.updateCommonProperties({user_id:Z||W.id,account_id:W.id,account_email:W.email,provider:W.provider,organization_id:W.organizationId,organization_name:W.organizationName,member_id:W.memberId})}function e9($,W){a($,v.TASK.CREATED,W)}function $W($,W){a($,v.TASK.RESTARTED,W)}function Y4($,W){a($,v.TASK.COMPLETED,W)}function L8($,W){a($,v.TASK.CONVERSATION_TURN,{...W,timestamp:new Date().toISOString()})}function WW($,W){a($,v.TASK.TOKEN_USAGE,W)}function ZW($,W,Z){a($,v.TASK.MODE_SWITCH,{ulid:W,mode:Z})}function T8($,W){a($,v.TASK.TOOL_USED,W)}function QW($,W){a($,v.TASK.SKILL_USED,W)}function JW($,W){a($,v.TASK.DIFF_EDIT_FAILED,W)}function V4($,W){a($,v.TASK.PROVIDER_API_ERROR,{...W,errorMessage:o9(W.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function RV($,W){a($,v.SDK.TOOL_TIMEOUT,EL(W))}function EL($){let W={};for(let[Z,Q]of Object.entries($))if(Q!==void 0)W[Z]=Q;return W}function jW($,W,Z){a($,v.TASK.MENTION_USED,{mentionType:W,contentLength:Z,timestamp:new Date().toISOString()})}function XW($,W,Z,Q){a($,v.TASK.MENTION_FAILED,{mentionType:W,errorType:Z,errorMessage:o9(Q),timestamp:new Date().toISOString()})}function YW($,W,Z,Q,J){a($,v.TASK.MENTION_SEARCH_RESULTS,{queryLength:W.length,resultCount:Z,searchType:Q,isEmpty:J,timestamp:new Date().toISOString()})}function T$($,W){a($,v.TASK.AGENT_CREATED,{...W,timestamp:new Date().toISOString()})}function VW($,W){a($,v.TASK.AGENT_TEAM_CREATED,{...W,timestamp:new Date().toISOString()})}function B4($,W){a($,W.event==="ended"?v.TASK.SUBAGENT_COMPLETED:v.TASK.SUBAGENT_STARTED,{...W,timestamp:new Date().toISOString()})}function BW($,W,Z,Q){a($,v.HOOKS.DISCOVERY_COMPLETED,{hookName:W,globalCount:Z,workspaceCount:Q,totalCount:Z+Q,timestamp:new Date().toISOString()})}function HW($,W){a($,v.TASK.COMPACTION_EXECUTED,{...W,timestamp:new Date().toISOString()})}function GW($,W){a($,v.TASK.COMPACTION_SKIPPED,{...W,timestamp:new Date().toISOString()})}function EV($,W){a($,v.TASK.COMPACTION_BUDGET_EMERGENCY,{...W,timestamp:new Date().toISOString()})}var qL=500,v;var R0=W2(()=>{v={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:OL},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",AUTH_REFRESH_SOFT_FAILURE:"user.auth_refresh_soft_failure",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",COMPACTION_BUDGET_EMERGENCY:"task.compaction_budget_emergency"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:zL,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as NL,readFileSync as wL,statSync as CL,writeFileSync as PL}from"node:fs";import{dirname as SL}from"node:path";import{resolveGlobalSettingsPath as wV}from"@cline/shared/storage";import{z as j2}from"zod";function KW(){return H4.parse({})}function yL(){FW=void 0}function hL($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function kL($){let W;try{W=wL($,"utf8")}catch{return KW()}try{let Z=H4.safeParse(JSON.parse(W));return Z.success?Z.data:KW()}catch{return KW()}}function IL(){let $=wV(),W=CL($,{throwIfNoEntry:!1}),Z=W?.mtimeMs??0,Q=W?.size??0,J=FW;if(J&&J.path===$&&J.mtimeMs===Z&&J.size===Q)return J;let j=hL(W?kL($):KW());return FW={path:$,mtimeMs:Z,size:Q,value:j},FW}function E0(){return IL().value}function f1($,W={}){let Z=wV(),Q=E0();NL(SL(Z),{recursive:!0});let J=H4.parse($);if(!Q.telemetryOptOut&&J.telemetryOptOut)MV(W.telemetry);PL(Z,`${JSON.stringify(J,null,2)}
2
+ `,"utf8"),yL()}function AW(){return E0().telemetryOptOut}function CV($,W={}){f1({...E0(),telemetryOptOut:$},W)}function PV(){return E0().autoUpdateEnabled}function SV($,W={}){f1({...E0(),autoUpdateEnabled:$},W)}function bV(){return E0().compactionStrategy??"basic"}function yV($){f1({...E0(),compactionStrategy:$})}function L1($){return new Set($??E0().disabledTools??[])}function G4($){return new Set($??E0().disabledPlugins??[])}function hV($){return L1().has($)}function UW($){let W=E0(),Z=new Set(W.disabledTools??[]),Q=Z.has($);if(Q)Z.delete($);else Z.add($);return f1({...W,disabledTools:[...Z]}),!Q}function l7($,W){let Z=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Z.length===0)return;let Q=E0(),J=L1(Q.disabledTools);for(let j of Z)if(W)J.add(j);else J.delete(j);f1({...Q,disabledTools:[...J]})}function kV($,W){return l7([$],W),W}function IV($){return G4().has($)}function xV($,W){let Z=$.trim();if(!Z)return;let Q=E0(),J=G4(Q.disabledPlugins);if(W)J.add(Z);else J.delete(Z);f1({...Q,disabledPlugins:[...J]})}function DW($,W){let Z=G4(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q))}function u1($,W){let Z=L1(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q.name))}function _W($,W){if(!$||$.length===0)return $;let Z=L1(W);if(Z.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,j)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},j)}})}var NV,bL,H4,FW;var X1=W2(()=>{R0();NV=j2.preprocess(($)=>Array.isArray($)?$.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean):void 0,j2.array(j2.string()).optional()).transform(($)=>{if(!$)return;let W=[...new Set($)].sort((Z,Q)=>Z.localeCompare(Q));return W.length>0?W:void 0}),bL=j2.enum(["basic","agentic"]).catch("basic"),H4=j2.object({telemetryOptOut:j2.boolean().default(!1).catch(!1),autoUpdateEnabled:j2.boolean().default(!0).catch(!0),compactionStrategy:bL.optional(),disabledTools:NV.optional(),disabledPlugins:NV.optional()}).strip().transform(($)=>{let W={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.compactionStrategy)W.compactionStrategy=$.compactionStrategy;if($.disabledTools?.length)W.disabledTools=$.disabledTools;if($.disabledPlugins?.length)W.disabledPlugins=$.disabledPlugins;return W})});import{existsSync as xL,mkdirSync as gL,readFileSync as mL,writeFileSync as vL}from"node:fs";import{resolve as cL}from"node:path";import{resolveSessionDataDir as uL}from"@cline/shared/storage";import{nanoid as dL}from"nanoid";import*as lL from"node-machine-id";function x0($){let W=$?.trim();if(W)return W;let Z=iL();if(Z)return Z;return nL()}function rL(){let $=lL;return $.machineIdSync??$.default?.machineIdSync}function iL(){try{let $=rL();if(!$)return;return $().trim()||void 0}catch{return}}function nL(){let $=uL(),W=cL($,pL);try{if(xL(W)){let Q=mL(W,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${dL()}`;try{gL($,{recursive:!0}),vL(W,Z,"utf8")}catch{}return Z}var pL="machine-id";var O8=()=>{};class F4{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($,W){if(!this.isEnabled())return;this.emitLog($,W,!1)}emitRequired($,W){this.emitLog($,W,!0)}recordCounter($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,j);j.add(W,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,j);j.record(W,this.flattenProperties(this.buildAttributes(Z)))}recordGauge($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.buildAttributes(Z),X=JSON.stringify(j),Y=this.gaugeValues.get($);if(W===null){if(Y){if(Y.delete(X),Y.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=Y;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let B=this.meter.createObservableGauge($,Q?{description:Q}:void 0);B.addCallback((H)=>{for(let G of this.snapshotGaugeSeries($))H.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,B)}V.set(X,{value:W,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($,W,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(W,Z));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,W=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...W?{_required:!0}:{}}}snapshotGaugeSeries($){let W=this.gaugeValues.get($);if(!W)return[];return Array.from(W.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties($,W="",Z=new WeakSet,Q=0){if(!$)return{};let J={},j=100,X=10;for(let[Y,V]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let B=W?`${W}.${Y}`:Y;if(V===null||V===void 0){J[B]=String(V);continue}if(Array.isArray(V)){let H=V.length>j?V.slice(0,j):V;try{J[B]=JSON.stringify(H)}catch{J[B]="[UnserializableArray]"}if(V.length>j)J[`${B}_truncated`]=!0,J[`${B}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[B]=V.toISOString();continue}if(V instanceof Error){J[B]=V.message;continue}if(Z.has(V)){J[B]="[Circular]";continue}if(Q>=X){J[B]="[MaxDepthExceeded]";continue}Z.add(V),Object.assign(J,this.flattenProperties(V,B,Z,Q+1));continue}if(aL(V)){J[B]=V;continue}try{J[B]=JSON.stringify(V)}catch{J[B]=String(V)}}return J}}function aL($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class A4{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,W){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:W})}emitRequired($,W){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:W})}recordCounter($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordHistogram($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordGauge($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:W,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class z8{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new A4({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 W=this.buildAttributes($.properties);for(let Z of this.adapters)Z.emit($.event,W)}captureRequired($,W){let Z=this.buildAttributes(W);for(let Q of this.adapters)Q.emitRequired($,Z)}recordCounter($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter($,W,j,Q,J)}recordHistogram($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram($,W,j,Q,J)}recordGauge($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge($,W,j,Q,J)}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 p7=()=>{};import{metrics as oL,trace as sL}from"@opentelemetry/api";import{logs as tL}from"@opentelemetry/api-logs";import{OTLPLogExporter as eL}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as $T}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as WT}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as ZT}from"@opentelemetry/resources";import{BatchLogRecordProcessor as QT,ConsoleLogRecordExporter as JT,LoggerProvider as jT}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as XT,MeterProvider as YT,PeriodicExportingMetricReader as gV}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as VT,ConsoleSpanExporter as BT,SimpleSpanProcessor as HT}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as GT}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as KT,ATTR_SERVICE_VERSION as FT}from"@opentelemetry/semantic-conventions";class mV{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($,W){this.resolveProperties(W)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class q8{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let W=ZT({[KT]:$.serviceName??"cline",...$.serviceVersion?{[FT]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(W),this.loggerProvider=this.createLoggerProvider(W),this.tracerProvider=this.createTracerProvider(W),this.meterProvider)oL.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)tL.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",W){return sL.getTracer($,W??this.options.serviceVersion)}createAdapter($){return new F4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let W=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new z8({...$,adapters:[W],distinctId:x0($.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 W=r7(this.options.metricsExporter);if(W.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=W.map((j)=>DT(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((j)=>j!==null);if(J.length===0)return null;return new YT({resource:$,readers:J})}createTracerProvider($){let W=r7(this.options.tracesExporter);if(W.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let j of W){let X=UT(j,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new GT({resource:$,spanProcessors:J})}createLoggerProvider($){let W=r7(this.options.logsExporter);if(W.length===0)return null;let Z=W.map((Q)=>{let J=AT(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new QT(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new jT({resource:$,processors:Z})}}function U4($){let W=new q8($),Z=W.createTelemetryService($);return Z.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:W,telemetry:Z}}function d1($){if(AW())return{telemetry:new mV($)};if($.enabled!==!0)return{telemetry:new z8({...$,distinctId:x0($.distinctId)})};return U4($)}function M8($){let{telemetry:W,provider:Z}=d1($);return{telemetry:W,provider:Z,flush:async()=>{let j=Z;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([W.dispose(),Z?.dispose()])}}}function r7($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function AT($,W){if($==="console")return new JT;if(!W.endpoint)return null;let Z=i7(W.endpoint,"/v1/logs");return new eL({url:Z,headers:W.headers})}function UT($,W){if($==="console")return new HT(new BT);if(!W.endpoint)return null;let Z=i7(W.endpoint,"/v1/traces");return new VT(new WT({url:Z,headers:W.headers}))}function DT($,W){if($==="console")return new gV({exporter:new XT,exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout});if(!W.endpoint)return null;let Z=i7(W.endpoint,"/v1/metrics");return new gV({exporter:new $T({url:Z,headers:W.headers}),exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout})}function i7($,W){let Z=new URL($),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith(W)?Q:`${Q}${W}`,Z.toString()}var fW=W2(()=>{X1();O8();p7()});var CG={};w(CG,{normalizeUserMessage:()=>bR,buildInitialUserContent:()=>SR});async function SR($,W,Z,Q){let J=yR(W),j=await kR(Z,Q);if(J.length===0&&!j)return $;let X=[{type:"text",text:$},...J];if(j)X.push(...j);return X}function bR($){if($==null)return"";if(typeof $==="string")return $;let W=$.content;if(typeof W==="string")return W;if(!Array.isArray(W))return"";let Z=[];for(let Q of W)if(Q&&typeof Q==="object"&&Q.type==="text"){let J=Q.text;if(typeof J==="string")Z.push(J)}return Z.join(`
3
+ `)}function yR($){if(!$||$.length===0)return[];let W=[];for(let Z of $){let Q=hR(Z);if(Q)W.push(Q)}return W}function hR($){let W=$.trim();if(!W)return;let Z=W.match(/^data:([^;,]+);base64,(.+)$/);if(Z){let Q=Z[1],J=Z[2];if(!Q||!J)return;return{type:"image",mediaType:Q,data:J}}return{type:"image",mediaType:"image/png",data:W}}async function kR($,W){if(!$||$.length===0)return;let Z=W??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(J)=>{let j=J.replace(/\\/g,"/");try{let X=await Z(J);return{type:"file",path:j,content:X}}catch(X){let Y=X instanceof Error?X.message:String(X);return{type:"file",path:j,content:`Error fetching content: ${Y}`}}}));if(Q.length===0)return;return Q}var WA={};w(WA,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,setMcpServerDisabled:()=>p2,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>n2,normalizeMcpServerOAuthState:()=>O6,loadMcpSettingsFile:()=>l2,listMcpServerOAuthStatuses:()=>n5,hasMcpSettingsFile:()=>X$,getMcpServerOAuthState:()=>r2,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$});import{existsSync as vF,mkdirSync as Xj,readFileSync as cF,renameSync as Bj,rmdirSync as bC,rmSync as Yj,statSync as yC,unlinkSync as uF,writeFileSync as dF}from"node:fs";import{randomUUID as hC}from"node:crypto";import{dirname as lF,join as mF}from"node:path";import{setTimeout as kC}from"node:timers/promises";import{resolveMcpSettingsPath as IC}from"@cline/shared/storage";import{z as S}from"zod";function Vj($){if(!$)return;if($==="http")return"streamableHttp";return $}function J0(){return IC()}function iC($,W){Xj(lF($),{recursive:!0});let Z=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{dF(Z,W,{encoding:"utf8",flag:"wx"}),Bj(Z,$)}catch(Q){try{uF(Z)}catch{}throw Q}}function aC($){Atomics.wait(nC,0,0,$)}function oC($){return`${$}.lock`}function nF(){return`${process.pid}.${Date.now()}.${hC()}`}function aF($,W){Xj(lF($),{recursive:!0});let Z=`${$}.tmp.${W}`;Yj(Z,{recursive:!0,force:!0}),Xj(Z,{recursive:!0}),dF(mF(Z,`owner.${W}`),W,{encoding:"utf8",flag:"wx"});try{return Bj(Z,$),{lockDir:$,ownerFile:mF($,`owner.${W}`)}}catch(Q){if(Yj(Z,{recursive:!0,force:!0}),vF($))return;throw Q}}function oF($,W){let Z;try{Z=Date.now()-yC($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Z<Gj)return;W.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Z}ms); reclaiming.`,{severity:"warn"});let Q=`${$}.stale.${nF()}`;try{Bj($,Q)}catch(J){if(J.code==="ENOENT")return;throw J}Yj(Q,{recursive:!0,force:!0})}function sC($){try{uF($.ownerFile)}catch(W){if(W.code!=="ENOENT")throw W}try{bC($.lockDir)}catch(W){let Z=W.code;if(Z!=="ENOENT"&&Z!=="ENOTEMPTY"&&Z!=="EEXIST")throw W}}function sF($){let W=oC($);if(YQ.has(W))throw Error(`Reentrant MCP settings update for ${$}. Keep mutators pure: compute values up front and do not call back into the settings API.`);return{lockDir:W,token:nF()}}function tC($,W){let{lockDir:Z,token:Q}=sF($),J=W.timeoutMs??Gj,j=Date.now();while(!0){let X=aF(Z,Q);if(X)return YQ.add(Z),X;if(Date.now()-j>J)throw new d$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);oF(Z,W),aC(iF)}}async function eC($,W){let{lockDir:Z,token:Q}=sF($),J=W.timeoutMs??Gj,j=Date.now();while(!0){let X=aF(Z,Q);if(X)return YQ.add(Z),X;if(Date.now()-j>J)throw new d$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);oF(Z,W),await kC(iF)}}function tF($,W,Z){try{let Q=$P(W),J=WP(Q,Z);return iC(W,`${JSON.stringify(Q,null,2)}
4
+ `),J}finally{YQ.delete($.lockDir),sC($)}}function A1($,W,Z={}){let Q=tC($,Z);return tF(Q,$,W)}async function T6($,W,Z={}){let Q=await eC($,Z);return tF(Q,$,W)}function $P($){let W=QP($);if(!W.mcpServers||typeof W.mcpServers!=="object"||Array.isArray(W.mcpServers))W.mcpServers={};return W}function WP($,W){let Z=JSON.stringify($),Q=JSON.parse(Z),J=W(Q),j=JSON.stringify(Q),X=W($);if(JSON.stringify($)!==j)throw new u$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(X)!==JSON.stringify(J))throw new u$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return X}function ZP($){let W=cF($,"utf8"),Z;try{Z=JSON.parse(W)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Z}function QP($){try{return ZP($)}catch(W){if(W.code==="ENOENT")return{};throw W}}function eF($,W){if(!Object.hasOwn($,W))return;let Z=$[W];if(!Z||typeof Z!=="object"||Array.isArray(Z))return;return Z}function JP($,W,Z){Object.defineProperty($,W,{value:Z,enumerable:!0,configurable:!0,writable:!0})}function l2($={}){let W=$.filePath??J0(),Z=cF(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(j){let X=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${W}": ${X}`)}let J=rC.safeParse(Q);if(!J.success){let j=J.error.issues.map((X)=>{let Y=X.path.join(".");return Y?`${Y}: ${X.message}`:X.message}).join("; ");throw Error(`Invalid MCP settings at "${W}": ${j}`)}return J.data}function O6($){if(!$)return;let W={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(W).length>0?W:void 0}function jP($){if($===void 0)return;let W=Hj.safeParse($);if(!W.success)return;return O6(W.data)}function X$($={}){let W=$.filePath??J0();return vF(W)}function t0($={}){let W=l2($);return Object.entries(W.mcpServers).map(([Z,Q])=>({name:Z,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function p2($){let W=$.filePath??J0(),Z=$.name.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");A1(W,(Q)=>{let J=Q.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${W}": mcpServers must be an object.`);let j={...J},X=eF(j,Z);if(!X)throw Error(`Unknown MCP server: ${Z}`);let Y={...X};if($.disabled)Y.disabled=!0;else delete Y.disabled;JP(j,Z,Y),Q.mcpServers=j})}function r2($,W={}){let Z=l2(W);if(!Object.hasOwn(Z.mcpServers,$))return;return O6(Z.mcpServers[$]?.oauth)}function $A($,W){return(Z)=>{let Q=Z.mcpServers,J=eF(Q,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let j=jP(J.oauth)??{},X=O6(W(j));if(X)J.oauth=X;else delete J.oauth;return X??{}}}function i2($,W,Z={}){let Q=Z.filePath??J0();return A1(Q,$A($,W))}async function i5($,W,Z={}){let Q=Z.filePath??J0();return T6(Q,$A($,W))}function n5($={}){return t0($).map((Z)=>{let Q=Z.transport.type!=="stdio",J=Z.oauth?.tokens?.access_token;return{serverName:Z.name,oauthSupported:Q,oauthConfigured:Q&&typeof J==="string"&&J.trim().length>0,lastError:Z.oauth?.lastError,lastAuthenticatedAt:Z.oauth?.lastAuthenticatedAt}}).sort((Z,Q)=>Z.serverName.localeCompare(Q.serverName))}async function n2($,W={}){let Z=t0(W);for(let Q of Z)await $.registerServer(Q);return Z}var r5,pF,Hj,xC,gC,mC,vC,cC,uC,rF,dC,lC,pC,rC,L6,d$,u$,Gj=1e4,iF=25,nC,YQ;var VQ=W2(()=>{r5=S.record(S.string(),S.string()),pF=S.record(S.string(),S.unknown()),Hj=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),xC=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:r5.optional()}),gC=S.object({type:S.literal("sse"),url:S.string().url(),headers:r5.optional()}),mC=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:r5.optional()}),vC=S.discriminatedUnion("type",[xC,gC,mC]),cC=S.object({transport:vC,disabled:S.boolean().optional(),metadata:pF.optional(),oauth:Hj.optional()}),uC=S.enum(["stdio","sse","http","streamableHttp"]).optional(),rF=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:uC,disabled:S.boolean().optional(),metadata:pF.optional(),oauth:Hj.optional()});dC=rF.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:r5.optional()}).superRefine(($,W)=>{let Z=$.type??Vj($.transportType);if(Z&&Z!=="stdio")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),lC=rF.extend({url:S.string().url(),headers:r5.optional()}).superRefine(($,W)=>{let Z=$.type??Vj($.transportType)??"sse";if(Z!=="sse"&&Z!=="streamableHttp")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??Vj($.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}}),pC=S.union([cC,dC,lC]),rC=S.object({mcpServers:S.record(S.string(),pC)}).passthrough();L6=class L6 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};d$=class d$ extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};u$=class u$ extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};nC=new Int32Array(new SharedArrayBuffer(4)),YQ=new Set});var nU={};w(nU,{resolveCoreDistinctId:()=>x0,createOpenTelemetryTelemetryService:()=>U4,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,OpenTelemetryProvider:()=>q8,OpenTelemetryAdapter:()=>F4});var bQ=W2(()=>{O8();fW()});var T_={};w(T_,{writeHubDiscovery:()=>OW,withHubStartupLock:()=>zW,verifyHubConnection:()=>z1,truncateNotificationBody:()=>k9,toHubStatusUrl:()=>s7,toHubHealthUrl:()=>qW,stopLocalHubServerGracefully:()=>B3,startHubWebSocketServer:()=>g9,startHubServer:()=>f_,spawnDetachedHubServerWithRetry:()=>N8,spawnDetachedHubServer:()=>Q3,sendHubCommand:()=>AB,restartLocalHubIfIdleAfterStartupTimeout:()=>wW,resolveWorkspaceHubOwnerContext:()=>sV,resolveSharedHubOwnerContext:()=>V1,resolveProductionHubOwnerContext:()=>O1,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>r1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>TW,resolveDefaultHubPort:()=>E8,resolveDefaultHubPathname:()=>Z3,resolveDefaultHubHost:()=>W3,resolveCompatibleLocalHubUrl:()=>T4,resolveClineDir:()=>iV,resolveClineDataDir:()=>Y2,requestHubShutdown:()=>L4,rememberRecoverableLocalHubUrl:()=>O$,readHubDiscovery:()=>D0,readBearerToken:()=>f7,probeHubServer:()=>i1,probeHubConnection:()=>FB,prewarmDetachedHubServer:()=>RW,normalizeHubWebSocketUrl:()=>z$,isLocalHubOrigin:()=>AY,isLocalHubHostName:()=>L7,isHubReconnectableTransportError:()=>Y3,isHubCommandTimeoutError:()=>NW,isDiscoveryFilePresent:()=>aV,ensureHubWebSocketServer:()=>T7,ensureHubServer:()=>L_,ensureDetachedHubServer:()=>QB,ensureCompatibleLocalHubUrl:()=>H2,createLocalHubScheduleRuntimeHandlers:()=>__,createInMemoryHubOwnerContext:()=>nV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>LW,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,connectToHub:()=>CW,clearHubDiscovery:()=>g0,NodeHubClient:()=>B1,NativeHubTransportAdapter:()=>x9,HubUIClient:()=>F3,HubTransportError:()=>y0,HubSessionClient:()=>K3,HubServerTransport:()=>o6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>A8,HubCommandError:()=>w8,DEFAULT_HUB_PORT:()=>e7,DEFAULT_HUB_PATHNAME:()=>$3,DEFAULT_HUB_HOST:()=>t7,BrowserWebSocketHubAdapter:()=>I9});import{createSessionId as mf}from"@cline/shared";function p0($,W){return{version:$.version,requestId:$.requestId,ok:!0,payload:W}}function sY($,W,Z){return{version:$.version,requestId:$.requestId??mf("hubreq_"),ok:!1,error:{code:W,message:Z}}}class A8{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return p0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return p0($,{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 p0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return p0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return p0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return p0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return p0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return p0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return p0($,{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 p0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return p0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return p0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return sY($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(W){return sY($,"schedule_command_failed",W instanceof Error?W.message:String(W))}}toCreateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:W}}toUpdateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:W}}}class e6{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},W=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of W)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let Z=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of Z)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as af}from"node:path";import{buildClineSystemPrompt as of}from"@cline/shared";import{nowIso as YV}from"@cline/shared/db";var O0={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"},D$=[O0.READ_FILES,O0.SEARCH_CODEBASE,O0.RUN_COMMANDS,O0.FETCH_WEB_CONTENT,O0.APPLY_PATCH,O0.EDITOR,O0.SKILLS,O0.ASK,O0.SUBMIT_AND_EXIT];var eY={};w(eY,{mergeRulesForSystemPrompt:()=>D8,loadRulesForSystemPromptFromWatcher:()=>C7,listEnabledRulesFromWatcher:()=>tY,isRuleEnabled:()=>l9,formatRulesForSystemPrompt:()=>U8});function l9($){return $.disabled!==!0}function U8($){if($.length===0)return"";return`
5
5
 
6
6
  # Rules
7
7
  ${$.map((Z)=>`## ${Z.name}
8
8
  ${Z.instructions}`).join(`
9
9
 
10
- `)}`}function A8($,W){let Z=$?.trim(),Q=W?.trim();if(Z&&Q)return`${Z}
10
+ `)}`}function D8($,W){let Z=$?.trim(),Q=W?.trim();if(Z&&Q)return`${Z}
11
11
 
12
- ${Q}`;return Z||Q||void 0}function uY($){return[...$.getSnapshot("rule").values()].map((Z)=>Z.item).filter(IW).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function M7($){return F8(uY($))}var oY={};w(oY,{withSessionGitMetadata:()=>gW,readSessionGitMetadata:()=>nY,readGitWorkspaceState:()=>N7,normalizeWorkspacePath:()=>D1,hasCurrentSessionGitMetadata:()=>R7,generateWorkspaceInfoWithDiagnostics:()=>t6,generateWorkspaceInfo:()=>U8,buildWorkspaceMetadataWithInfo:()=>E7,buildWorkspaceMetadata:()=>e6});import{basename as h_,resolve as k_}from"node:path";import{performance as lY}from"node:perf_hooks";import{processWorkspaceInfo as rY}from"@cline/shared";import iY from"simple-git";function nY($){let W=$?.git;if(!W||typeof W!=="object"||Array.isArray(W))return{};let Z=W;return{...typeof Z.url==="string"&&Z.url.trim()?{url:Z.url.trim()}:{},...typeof Z.branch==="string"&&Z.branch.trim()?{branch:Z.branch.trim()}:{}}}function gW($,W){let Z={...$??{}};if(!W.url&&!W.branch)return delete Z.git,Object.keys(Z).length>0?Z:void 0;let J={...Z.git&&typeof Z.git==="object"&&!Array.isArray(Z.git)?Z.git:{}};if(W.url)J.url=W.url;else delete J.url;if(W.branch)J.branch=W.branch;else delete J.branch;return Z.git=J,Z}function R7($,W){let Z=nY($);return Z.url===W.url&&Z.branch===W.branch}function aY($){let W=$.find(({name:Z})=>Z==="origin")??$[0];return(W?.refs.fetch||W?.refs.push)?.trim()||void 0}function D1($){return k_($)}async function U8($){return(await t6($)).info}function pY($){let W=$ instanceof Error?$.message:String($);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(W)}function xW($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function t6($){let W=D1($),Z={rootPath:W,hint:h_(W)},Q={},J;try{let j=iY({baseDir:W});if(!await j.checkIsRepo())return{info:Z,vcsType:"none",gitState:Q};try{let Y=await j.getRemotes(!0);if(Y.length>0){let V=Y.map((H)=>{let G=H.refs.fetch||H.refs.push;return`${H.name}: ${G}`});Z.associatedRemoteUrls=V;let B=aY(Y);if(B)Q.url=B}}catch(Y){J??=xW(Y)}try{let Y=(await j.revparse(["HEAD"])).trim();if(Y.length>0)Z.latestGitCommitHash=Y}catch(Y){if(!pY(Y))J??=xW(Y)}try{let Y=(await j.branch()).current.trim();if(Y.length>0)Z.latestGitBranchName=Y,Q.branch=Y}catch(Y){if(!pY(Y))J??=xW(Y)}return{info:Z,vcsType:"git",gitState:Q,error:J}}catch(j){return{info:Z,vcsType:"none",gitState:Q,error:xW(j)}}}async function N7($){try{let W=iY({baseDir:D1($)});if(!await W.checkIsRepo())return{};let[Z,Q]=await Promise.all([W.getRemotes(!0),W.branch()]),J=aY(Z),j=Q.current.trim();return{...J?{url:J}:{},...j?{branch:j}:{}}}catch{return}}async function e6($){let W=await U8($);return rY(W)}async function E7($){let W=lY.now(),Z=await t6($),Q=lY.now()-W,J=Z.info;return{workspaceInfo:J,workspaceMetadata:rY(J),durationMs:Q,vcsType:Z.vcsType,gitState:Z.gitState,initError:Z.error}}import{mkdirSync as I_,writeFileSync as x_}from"node:fs";import{join as g_}from"node:path";import{resolveCronReportsDir as m_}from"@cline/shared/storage";function f$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function W2($,W){if(W===void 0||W===null)return;return`${$}: ${f$(W)}`}function v_($,W,Z){let Q=[`runId: ${f$($.runId)}`,`specId: ${f$(W.specId)}`,`externalId: ${f$(W.externalId)}`,`title: ${f$(W.title)}`,`triggerKind: ${f$($.triggerKind)}`,`status: ${f$($.status)}`,`sourcePath: ${f$(W.sourcePath)}`],J=[W2("sessionId",$.sessionId),W2("startedAt",$.startedAt),W2("completedAt",$.completedAt),W2("triggerEventId",$.triggerEventId),W2("triggerEventType",Z?.eventType),W2("triggerEventSource",Z?.source),W2("triggerEventSubject",Z?.subject)];for(let j of J)if(j)Q.push(j);return`---
12
+ ${Q}`;return Z||Q||void 0}function tY($){return[...$.getSnapshot("rule").values()].map((Z)=>Z.item).filter(l9).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function C7($){return U8(tY($))}var XV={};w(XV,{withSessionGitMetadata:()=>r9,readSessionGitMetadata:()=>JV,readGitWorkspaceState:()=>S7,normalizeWorkspacePath:()=>_1,hasCurrentSessionGitMetadata:()=>P7,generateWorkspaceInfoWithDiagnostics:()=>$4,generateWorkspaceInfo:()=>_8,buildWorkspaceMetadataWithInfo:()=>b7,buildWorkspaceMetadata:()=>W4});import{basename as vf,resolve as cf}from"node:path";import{performance as $V}from"node:perf_hooks";import{processWorkspaceInfo as ZV}from"@cline/shared";import QV from"simple-git";function JV($){let W=$?.git;if(!W||typeof W!=="object"||Array.isArray(W))return{};let Z=W;return{...typeof Z.url==="string"&&Z.url.trim()?{url:Z.url.trim()}:{},...typeof Z.branch==="string"&&Z.branch.trim()?{branch:Z.branch.trim()}:{}}}function r9($,W){let Z={...$??{}};if(!W.url&&!W.branch)return delete Z.git,Object.keys(Z).length>0?Z:void 0;let J={...Z.git&&typeof Z.git==="object"&&!Array.isArray(Z.git)?Z.git:{}};if(W.url)J.url=W.url;else delete J.url;if(W.branch)J.branch=W.branch;else delete J.branch;return Z.git=J,Z}function P7($,W){let Z=JV($);return Z.url===W.url&&Z.branch===W.branch}function jV($){let W=$.find(({name:Z})=>Z==="origin")??$[0];return(W?.refs.fetch||W?.refs.push)?.trim()||void 0}function _1($){return cf($)}async function _8($){return(await $4($)).info}function WV($){let W=$ instanceof Error?$.message:String($);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(W)}function p9($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function $4($){let W=_1($),Z={rootPath:W,hint:vf(W)},Q={},J;try{let j=QV({baseDir:W});if(!await j.checkIsRepo())return{info:Z,vcsType:"none",gitState:Q};try{let Y=await j.getRemotes(!0);if(Y.length>0){let V=Y.map((H)=>{let G=H.refs.fetch||H.refs.push;return`${H.name}: ${G}`});Z.associatedRemoteUrls=V;let B=jV(Y);if(B)Q.url=B}}catch(Y){J??=p9(Y)}try{let Y=(await j.revparse(["HEAD"])).trim();if(Y.length>0)Z.latestGitCommitHash=Y}catch(Y){if(!WV(Y))J??=p9(Y)}try{let Y=(await j.branch()).current.trim();if(Y.length>0)Z.latestGitBranchName=Y,Q.branch=Y}catch(Y){if(!WV(Y))J??=p9(Y)}return{info:Z,vcsType:"git",gitState:Q,error:J}}catch(j){return{info:Z,vcsType:"none",gitState:Q,error:p9(j)}}}async function S7($){try{let W=QV({baseDir:_1($)});if(!await W.checkIsRepo())return{};let[Z,Q]=await Promise.all([W.getRemotes(!0),W.branch()]),J=jV(Z),j=Q.current.trim();return{...J?{url:J}:{},...j?{branch:j}:{}}}catch{return}}async function W4($){let W=await _8($);return ZV(W)}async function b7($){let W=$V.now(),Z=await $4($),Q=$V.now()-W,J=Z.info;return{workspaceInfo:J,workspaceMetadata:ZV(J),durationMs:Q,vcsType:Z.vcsType,gitState:Z.gitState,initError:Z.error}}import{mkdirSync as uf,writeFileSync as df}from"node:fs";import{join as lf}from"node:path";import{resolveCronReportsDir as pf}from"@cline/shared/storage";function _$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function Z2($,W){if(W===void 0||W===null)return;return`${$}: ${_$(W)}`}function rf($,W,Z){let Q=[`runId: ${_$($.runId)}`,`specId: ${_$(W.specId)}`,`externalId: ${_$(W.externalId)}`,`title: ${_$(W.title)}`,`triggerKind: ${_$($.triggerKind)}`,`status: ${_$($.status)}`,`sourcePath: ${_$(W.sourcePath)}`],J=[Z2("sessionId",$.sessionId),Z2("startedAt",$.startedAt),Z2("completedAt",$.completedAt),Z2("triggerEventId",$.triggerEventId),Z2("triggerEventType",Z?.eventType),Z2("triggerEventSource",Z?.source),Z2("triggerEventSubject",Z?.subject)];for(let j of J)if(j)Q.push(j);return`---
13
13
  ${Q.join(`
14
14
  `)}
15
15
  ---
16
- `}function c_($){let W=[];if($.triggerEvent){let Z=$.triggerEvent,Q=[`- eventId: ${Z.eventId}`,`- eventType: ${Z.eventType}`,`- source: ${Z.source}`,Z.subject?`- subject: ${Z.subject}`:"",`- occurredAt: ${Z.occurredAt}`,Z.dedupeKey?`- dedupeKey: ${Z.dedupeKey}`:"",Z.attributes?`- attributes: ${JSON.stringify(Z.attributes)}`:""].filter((J)=>J.length>0);W.push(`## Trigger Event
16
+ `}function nf($){let W=[];if($.triggerEvent){let Z=$.triggerEvent,Q=[`- eventId: ${Z.eventId}`,`- eventType: ${Z.eventType}`,`- source: ${Z.source}`,Z.subject?`- subject: ${Z.subject}`:"",`- occurredAt: ${Z.occurredAt}`,Z.dedupeKey?`- dedupeKey: ${Z.dedupeKey}`:"",Z.attributes?`- attributes: ${JSON.stringify(Z.attributes)}`:""].filter((J)=>J.length>0);W.push(`## Trigger Event
17
17
 
18
18
  ${Q.join(`
19
19
  `)}
@@ -32,12 +32,12 @@ ${Q.join(`
32
32
  ${Z.join(`
33
33
  `)}
34
34
  `)}return W.join(`
35
- `)}function w7($){let W=m_($.specs);I_(W,{recursive:!0});let Z=g_(W,`${$.run.runId}.md`),Q=`${v_($.run,$.spec,$.data.triggerEvent)}
36
- ${c_($.data)}`;return x_(Z,Q,"utf8"),Z}class C7{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,W,Z){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(Z)),J=this.activeExecutions.get($)??new Set;if(J.size>=Q)return!1;return J.add(W),this.activeExecutions.set($,J),!0}release($,W){let Z=this.activeExecutions.get($);if(!Z)return;if(Z.delete(W),Z.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let W of this.activeExecutions.values())$+=W.size;return $}}var l_=15000,p_=90,tY=["rules","skills","plugins"];function r_($,W){return new Set($.extensions??tY).has(W)}function i_($,W){if($.tools===void 0)return{"*":{autoApprove:!0}};let Z={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)Z[Q]={enabled:!0,autoApprove:!0};if(W==="yolo")Z[T0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Z}function n_($){let W=$?.trim();if(!W)return;return["# Notes Directory",`Use ${W} 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(`
37
- `)}class P7 extends Error{constructor($){super($);this.name="TimeoutError"}}async function a_($,W){if(W<=0)return $;let Z,Q=new Promise((J,j)=>{Z=setTimeout(()=>{j(new P7("cron run timed out"))},W)});try{return await Promise.race([$,Q])}finally{if(Z)clearTimeout(Z)}}class $4{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 C7($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??p_)*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??l_);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 W=[...this.activeRuns.entries()];await Promise.all(W.map(async([Z,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:Z,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:sY(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((W)=>this.executeClaim(W)))}catch($){let W=this.options.logger;if(W)if(W.error)W.error("cron.runner.tick.failed",{error:$});else W.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,W])=>{let Z=this.store.getRun($);return Z?[{...Z,...W}]:[]})}async executeClaim($){let W=$.run,Z=this.store.getSpec(W.specId);if(!Z){this.store.completeRun(W.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Z.enabled||Z.removed){this.store.completeRun(W.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=Z.maxParallel&&Z.maxParallel>0?Z.maxParallel:1;if(!this.limiter.acquire(Z.specId,W.runId,Q)){this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Z.specId,W.runId),this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(W.runId,{claimToken:$.claimToken});let j=W.triggerEventId?this.store.getEventLog(W.triggerEventId):void 0,X,Y,V=Date.now(),B;if(Z.timeoutSeconds&&Z.timeoutSeconds>0)B=V+Z.timeoutSeconds*1000;try{Y=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Z);if(X=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!X)throw Error("runtime returned empty sessionId");this.activeRuns.set(W.runId,{claimToken:$.claimToken,sessionId:X}),this.store.attachSessionIdToRun(W.runId,X);let K={config:H,prompt:this.buildPrompt(Z,j)},F=this.options.runtimeHandlers.sendSession(X,K),A=B?Math.max(1,B-Date.now()):0,U=(await a_(F,A)).result,_=Date.now(),D=w7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"done"},spec:Z,data:{finalText:U.text,usage:U.usage,toolCalls:U.toolCalls,durationMs:_-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"done",sessionId:X,reportPath:D,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Z,W.runId),this.store.updateSpecLastRunAt(Z.specId,sY())}catch(H){let G=H instanceof P7;if(X&&G)try{await this.options.runtimeHandlers.abortSession(X)}catch{}let K=H instanceof Error?H.message:String(H),F=Date.now(),A=w7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"failed"},spec:Z,data:{error:K,durationMs:F-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"failed",sessionId:X,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Z,W.runId)}finally{if(Y?.(),X)try{await this.options.runtimeHandlers.stopSession(X)}catch{}this.activeRuns.delete(W.runId),this.limiter.release(Z.specId,W.runId)}}publishScheduleExecutionEvent($,W,Z){if(W.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(Z);if(!Q)return;let J=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:W.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:J,errorMessage:Q.error})}buildPrompt($,W){let Z=$.prompt??"";if(!W)return Z;let Q={eventId:W.eventId,eventType:W.eventType,source:W.source,subject:W.subject,occurredAt:W.occurredAt,workspaceRoot:W.workspaceRoot,dedupeKey:W.dedupeKey,attributes:W.attributes,payload:W.payload};return`${Z}
35
+ `)}function y7($){let W=pf($.specs);uf(W,{recursive:!0});let Z=lf(W,`${$.run.runId}.md`),Q=`${rf($.run,$.spec,$.data.triggerEvent)}
36
+ ${nf($.data)}`;return df(Z,Q,"utf8"),Z}class h7{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,W,Z){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(Z)),J=this.activeExecutions.get($)??new Set;if(J.size>=Q)return!1;return J.add(W),this.activeExecutions.set($,J),!0}release($,W){let Z=this.activeExecutions.get($);if(!Z)return;if(Z.delete(W),Z.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let W of this.activeExecutions.values())$+=W.size;return $}}var sf=15000,tf=90,VV=["rules","skills","plugins"];function ef($,W){return new Set($.extensions??VV).has(W)}function $L($,W){if($.tools===void 0)return{"*":{autoApprove:!0}};let Z={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)Z[Q]={enabled:!0,autoApprove:!0};if(W==="yolo")Z[O0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Z}function WL($){let W=$?.trim();if(!W)return;return["# Notes Directory",`Use ${W} 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(`
37
+ `)}class k7 extends Error{constructor($){super($);this.name="TimeoutError"}}async function ZL($,W){if(W<=0)return $;let Z,Q=new Promise((J,j)=>{Z=setTimeout(()=>{j(new k7("cron run timed out"))},W)});try{return await Promise.race([$,Q])}finally{if(Z)clearTimeout(Z)}}class Z4{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 h7($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??tf)*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??sf);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 W=[...this.activeRuns.entries()];await Promise.all(W.map(async([Z,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:Z,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:YV(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((W)=>this.executeClaim(W)))}catch($){let W=this.options.logger;if(W)if(W.error)W.error("cron.runner.tick.failed",{error:$});else W.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,W])=>{let Z=this.store.getRun($);return Z?[{...Z,...W}]:[]})}async executeClaim($){let W=$.run,Z=this.store.getSpec(W.specId);if(!Z){this.store.completeRun(W.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Z.enabled||Z.removed){this.store.completeRun(W.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=Z.maxParallel&&Z.maxParallel>0?Z.maxParallel:1;if(!this.limiter.acquire(Z.specId,W.runId,Q)){this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Z.specId,W.runId),this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(W.runId,{claimToken:$.claimToken});let j=W.triggerEventId?this.store.getEventLog(W.triggerEventId):void 0,X,Y,V=Date.now(),B;if(Z.timeoutSeconds&&Z.timeoutSeconds>0)B=V+Z.timeoutSeconds*1000;try{Y=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Z);if(X=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!X)throw Error("runtime returned empty sessionId");this.activeRuns.set(W.runId,{claimToken:$.claimToken,sessionId:X}),this.store.attachSessionIdToRun(W.runId,X);let K={config:H,prompt:this.buildPrompt(Z,j)},F=this.options.runtimeHandlers.sendSession(X,K),A=B?Math.max(1,B-Date.now()):0,U=(await ZL(F,A)).result,f=Date.now(),_=y7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"done"},spec:Z,data:{finalText:U.text,usage:U.usage,toolCalls:U.toolCalls,durationMs:f-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"done",sessionId:X,reportPath:_,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Z,W.runId),this.store.updateSpecLastRunAt(Z.specId,YV())}catch(H){let G=H instanceof k7;if(X&&G)try{await this.options.runtimeHandlers.abortSession(X)}catch{}let K=H instanceof Error?H.message:String(H),F=Date.now(),A=y7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"failed"},spec:Z,data:{error:K,durationMs:F-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"failed",sessionId:X,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Z,W.runId)}finally{if(Y?.(),X)try{await this.options.runtimeHandlers.stopSession(X)}catch{}this.activeRuns.delete(W.runId),this.limiter.release(Z.specId,W.runId)}}publishScheduleExecutionEvent($,W,Z){if(W.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(Z);if(!Q)return;let J=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:W.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:J,errorMessage:Q.error})}buildPrompt($,W){let Z=$.prompt??"";if(!W)return Z;let Q={eventId:W.eventId,eventType:W.eventType,source:W.source,subject:W.subject,occurredAt:W.occurredAt,workspaceRoot:W.workspaceRoot,dedupeKey:W.dedupeKey,attributes:W.attributes,payload:W.payload};return`${Z}
38
38
 
39
39
  Trigger event:
40
- ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Z=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(Z)},W);return()=>clearInterval(Z)}async buildSystemPrompt($,W,Z,Q){let J=n_($.notesDirectory),j=A8(void 0,J),X=await e6(W),Y=d_({ide:"Cline Cron",workspaceRoot:W,workspaceName:u_(W),metadata:X,rules:$.systemPrompt?void 0:j,mode:Z,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?A8(Y,j)??Y:Y}async buildStartRequest($){let W=($.workspaceRoot??"").trim(),Z=($.providerId??"").trim(),Q=($.modelId??"").trim(),J=$.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():W;if(!W)throw Error("cron spec requires workspaceRoot");let X=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:W,cwd:j,provider:Z,model:Q,mode:X,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,W,X,Z),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:i_($,X),configExtensions:tY.filter((Y)=>r_($,Y))}}}function W4($,W,Z,Q){let J=new Set;function j(X){let Y=X.toLowerCase();if(Q){let B=Q.indexOf(Y);if(B!==-1)return B+W}let V=Number(X);if(!Number.isInteger(V)||V<W||V>Z)throw Error(`Invalid cron value "${X}" for range [${W}-${Z}]`);return V}for(let X of $.split(",")){if(X==="*"){for(let B=W;B<=Z;B+=1)J.add(B);continue}let Y=X.indexOf("/");if(Y!==-1){let B=X.slice(0,Y),H=Number(X.slice(Y+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${X.slice(Y+1)}"`);let G=W,K=Z;if(B!=="*"){let F=B.indexOf("-");if(F!==-1)G=j(B.slice(0,F)),K=j(B.slice(F+1));else G=j(B)}if(G>K)throw Error(`Invalid cron range "${B}"`);for(let F=G;F<=K;F+=H)J.add(F);continue}let V=X.indexOf("-");if(V!==-1){let B=j(X.slice(0,V)),H=j(X.slice(V+1));if(B>H)throw Error(`Invalid cron range "${X}"`);for(let G=B;G<=H;G+=1)J.add(G);continue}J.add(j(X))}return[...J].sort((X,Y)=>X-Y)}var o_=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],$V=["sun","mon","tue","wed","thu","fri","sat"];function Z4($,W,Z){let Q=$[W];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${Z}": missing field ${W+1}`);return Q}function S7($,W){let Z=$[0];if(typeof Z!=="number")throw Error(`Invalid cron pattern: no values parsed for ${W}`);return Z}function b7($){let W=$.trim().split(/\s+/);if(W.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${W.length}`);return{minutes:W4(Z4(W,0,$),0,59),hours:W4(Z4(W,1,$),0,23),daysOfMonth:W4(Z4(W,2,$),1,31),months:W4(Z4(W,3,$),1,12,o_),daysOfWeek:W4(Z4(W,4,$),0,6,$V)}}function y7($){b7($)}function WV($,W,Z=Date.now()){Z2($,Z,W)}var eY=new Map,s_=new Map($V.map(($,W)=>[$,W]));function ZV($){let W=$?.trim();return W?W:void 0}function QV($){let W=eY.get($);if(W)return W;let Z=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 eY.set($,Z),Z}function t_($){let W=ZV($);if(!W)return;QV(W).format(new Date)}function e_($,W){let Z=QV(W).formatToParts(new Date($)),Q=new Map(Z.map((X)=>[X.type,X.value])),J=Q.get("weekday")?.toLowerCase().slice(0,3)??"",j=s_.get(J);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${W}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:j,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function $L($){let W=new Date($);return{month:W.getMonth()+1,dayOfMonth:W.getDate(),dayOfWeek:W.getDay(),hour:W.getHours(),minute:W.getMinutes()}}function WL($,W){return $.months.includes(W.month)&&$.daysOfMonth.includes(W.dayOfMonth)&&$.daysOfWeek.includes(W.dayOfWeek)&&$.hours.includes(W.hour)&&$.minutes.includes(W.minute)}function ZL($,W,Z){let Q=b7($),J=new Date(W);J.setSeconds(0,0);let j=J.getTime()+60000,X=new Date(W);X.setFullYear(X.getFullYear()+4);let Y=X.getTime();while(j<=Y){if(WL(Q,e_(j,Z)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Z}"`)}function Z2($,W,Z){let Q=ZV(Z);if(Q)return t_(Q),ZL($,W,Q);let J=b7($),j=new Date(W);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let X=new Date(W);X.setFullYear(X.getFullYear()+4);while(j<=X){let{month:Y,dayOfMonth:V,dayOfWeek:B,hour:H,minute:G}=$L(j.getTime());if(!J.months.includes(Y)){let K=J.months.find((A)=>A>Y)??S7(J.months,"months"),F=K<=Y?1:0;j=new Date(j.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(B)){j=new Date(j.getFullYear(),j.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(H)){let K=J.hours.find((A)=>A>H)??S7(J.hours,"hours"),F=K<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??S7(J.minutes,"minutes"),F=K<=G?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+F,K,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as Q4}from"node:crypto";import{asOptionalString as c,asString as Z0,loadSqliteDb as JL,nowIso as q0}from"@cline/shared/db";import{resolveCronDbPath as jL}from"@cline/shared/storage";var QL=[`CREATE TABLE IF NOT EXISTS cron_specs (
40
+ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Z=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(Z)},W);return()=>clearInterval(Z)}async buildSystemPrompt($,W,Z,Q){let J=WL($.notesDirectory),j=D8(void 0,J),X=await W4(W),Y=of({ide:"Cline Cron",workspaceRoot:W,workspaceName:af(W),metadata:X,rules:$.systemPrompt?void 0:j,mode:Z,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?D8(Y,j)??Y:Y}async buildStartRequest($){let W=($.workspaceRoot??"").trim(),Z=($.providerId??"").trim(),Q=($.modelId??"").trim(),J=$.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():W;if(!W)throw Error("cron spec requires workspaceRoot");let X=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:W,cwd:j,provider:Z,model:Q,mode:X,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,W,X,Z),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:$L($,X),configExtensions:VV.filter((Y)=>ef($,Y))}}}function Q4($,W,Z,Q){let J=new Set;function j(X){let Y=X.toLowerCase();if(Q){let B=Q.indexOf(Y);if(B!==-1)return B+W}let V=Number(X);if(!Number.isInteger(V)||V<W||V>Z)throw Error(`Invalid cron value "${X}" for range [${W}-${Z}]`);return V}for(let X of $.split(",")){if(X==="*"){for(let B=W;B<=Z;B+=1)J.add(B);continue}let Y=X.indexOf("/");if(Y!==-1){let B=X.slice(0,Y),H=Number(X.slice(Y+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${X.slice(Y+1)}"`);let G=W,K=Z;if(B!=="*"){let F=B.indexOf("-");if(F!==-1)G=j(B.slice(0,F)),K=j(B.slice(F+1));else G=j(B)}if(G>K)throw Error(`Invalid cron range "${B}"`);for(let F=G;F<=K;F+=H)J.add(F);continue}let V=X.indexOf("-");if(V!==-1){let B=j(X.slice(0,V)),H=j(X.slice(V+1));if(B>H)throw Error(`Invalid cron range "${X}"`);for(let G=B;G<=H;G+=1)J.add(G);continue}J.add(j(X))}return[...J].sort((X,Y)=>X-Y)}var QL=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],HV=["sun","mon","tue","wed","thu","fri","sat"];function J4($,W,Z){let Q=$[W];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${Z}": missing field ${W+1}`);return Q}function I7($,W){let Z=$[0];if(typeof Z!=="number")throw Error(`Invalid cron pattern: no values parsed for ${W}`);return Z}function x7($){let W=$.trim().split(/\s+/);if(W.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${W.length}`);return{minutes:Q4(J4(W,0,$),0,59),hours:Q4(J4(W,1,$),0,23),daysOfMonth:Q4(J4(W,2,$),1,31),months:Q4(J4(W,3,$),1,12,QL),daysOfWeek:Q4(J4(W,4,$),0,6,HV)}}function g7($){x7($)}function GV($,W,Z=Date.now()){Q2($,Z,W)}var BV=new Map,JL=new Map(HV.map(($,W)=>[$,W]));function KV($){let W=$?.trim();return W?W:void 0}function FV($){let W=BV.get($);if(W)return W;let Z=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 BV.set($,Z),Z}function jL($){let W=KV($);if(!W)return;FV(W).format(new Date)}function XL($,W){let Z=FV(W).formatToParts(new Date($)),Q=new Map(Z.map((X)=>[X.type,X.value])),J=Q.get("weekday")?.toLowerCase().slice(0,3)??"",j=JL.get(J);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${W}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:j,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function YL($){let W=new Date($);return{month:W.getMonth()+1,dayOfMonth:W.getDate(),dayOfWeek:W.getDay(),hour:W.getHours(),minute:W.getMinutes()}}function VL($,W){return $.months.includes(W.month)&&$.daysOfMonth.includes(W.dayOfMonth)&&$.daysOfWeek.includes(W.dayOfWeek)&&$.hours.includes(W.hour)&&$.minutes.includes(W.minute)}function BL($,W,Z){let Q=x7($),J=new Date(W);J.setSeconds(0,0);let j=J.getTime()+60000,X=new Date(W);X.setFullYear(X.getFullYear()+4);let Y=X.getTime();while(j<=Y){if(VL(Q,XL(j,Z)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Z}"`)}function Q2($,W,Z){let Q=KV(Z);if(Q)return jL(Q),BL($,W,Q);let J=x7($),j=new Date(W);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let X=new Date(W);X.setFullYear(X.getFullYear()+4);while(j<=X){let{month:Y,dayOfMonth:V,dayOfWeek:B,hour:H,minute:G}=YL(j.getTime());if(!J.months.includes(Y)){let K=J.months.find((A)=>A>Y)??I7(J.months,"months"),F=K<=Y?1:0;j=new Date(j.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(B)){j=new Date(j.getFullYear(),j.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(H)){let K=J.hours.find((A)=>A>H)??I7(J.hours,"hours"),F=K<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??I7(J.minutes,"minutes"),F=K<=G?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+F,K,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as j4}from"node:crypto";import{asOptionalString as c,asString as Q0,loadSqliteDb as GL,nowIso as M0}from"@cline/shared/db";import{resolveCronDbPath as KL}from"@cline/shared/storage";var HL=[`CREATE TABLE IF NOT EXISTS cron_specs (
41
41
  spec_id TEXT PRIMARY KEY,
42
42
  external_id TEXT NOT NULL,
43
43
  source_path TEXT NOT NULL UNIQUE,
@@ -128,17 +128,17 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
128
128
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
129
129
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
130
130
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
131
- ON cron_specs(source_path);`];function JV($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let W of QL)$.exec(W)}function mW($){if(!$)return;try{let W=JSON.parse($);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return}function h7($,W={}){if(!$)return;try{let Z=JSON.parse($);if(!Array.isArray(Z))return;let Q=Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(W.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function Q2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function D$($){return{specId:Z0($.spec_id),externalId:Z0($.external_id),sourcePath:Z0($.source_path),triggerKind:Z0($.trigger_kind),sourceMtimeMs:Q2($.source_mtime_ms),sourceHash:c($.source_hash),parseStatus:Z0($.parse_status)==="invalid"?"invalid":"valid",parseError:c($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:Z0($.title),prompt:c($.prompt),workspaceRoot:c($.workspace_root),scheduleExpr:c($.schedule_expr),timezone:c($.timezone),eventType:c($.event_type),filters:mW(c($.filters_json)),debounceSeconds:Q2($.debounce_seconds),dedupeWindowSeconds:Q2($.dedupe_window_seconds),cooldownSeconds:Q2($.cooldown_seconds),mode:c($.mode),systemPrompt:c($.system_prompt),providerId:c($.provider_id),modelId:c($.model_id),maxIterations:Q2($.max_iterations),timeoutSeconds:Q2($.timeout_seconds),maxParallel:Q2($.max_parallel),tools:h7(c($.tools_json),{preserveEmpty:!0}),notesDirectory:c($.notes_directory),extensions:h7(c($.extensions_json),{preserveEmpty:!0}),source:c($.source),tags:h7(c($.tags_json)),metadata:mW(c($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:c($.last_materialized_run_id),lastRunAt:c($.last_run_at),nextRunAt:c($.next_run_at),createdAt:Z0($.created_at),updatedAt:Z0($.updated_at)}}function k7($){return{runId:Z0($.run_id),specId:Z0($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:Z0($.trigger_kind),status:Z0($.status),claimToken:c($.claim_token),claimStartedAt:c($.claim_started_at),claimUntilAt:c($.claim_until_at),scheduledFor:c($.scheduled_for),triggerEventId:c($.trigger_event_id),startedAt:c($.started_at),completedAt:c($.completed_at),sessionId:c($.session_id),reportPath:c($.report_path),error:c($.error),attemptCount:Number($.attempt_count??0),createdAt:Z0($.created_at),updatedAt:Z0($.updated_at)}}function jV($){return{eventId:Z0($.event_id),eventType:Z0($.event_type),source:Z0($.source),subject:c($.subject),occurredAt:Z0($.occurred_at),receivedAt:Z0($.received_at),workspaceRoot:c($.workspace_root),dedupeKey:c($.dedupe_key),payload:mW(c($.payload_json)),attributes:mW(c($.attributes_json)),processingStatus:Z0($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:c($.error),createdAt:Z0($.created_at),updatedAt:Z0($.updated_at)}}function XV($){return $?JSON.stringify($):null}var XL=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function YV($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function YL($,W,Z,Q){for(let J of XL){let j=$[J],X=W[J];if(YV(j)!==YV(X))return!0}if(Z===!1&&Q===!0)return!0;return!1}function VL($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function BL($){return`hub/schedules/${$}.cron.md`}function HL($){let W={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(W).length>0?W:void 0}function I7($){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((W)=>W.trim().length>0),enabled:$.enabled!==!1,metadata:HL($)}}function VV($){return JSON.stringify(I7($))}function GL($,W){let Z=$.metadata?{...$.metadata}:{},Q=W.createdBy===null?void 0:W.createdBy!==void 0?W.createdBy:typeof Z.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,J=W.cwd!==void 0?W.cwd:typeof Z.__hubScheduleCwd==="string"?Z.__hubScheduleCwd:void 0,j=W.runtimeOptions!==void 0?W.runtimeOptions:Z.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0;return delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions,{name:W.name??$.title,cronPattern:W.cronPattern??$.scheduleExpr??"",prompt:W.prompt??$.prompt??"",workspaceRoot:W.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:W.modelSelection!==void 0?W.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:W.enabled??$.enabled,mode:W.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:W.systemPrompt===null?void 0:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,maxIterations:W.maxIterations===null?void 0:W.maxIterations!==void 0?W.maxIterations:$.maxIterations,timeoutSeconds:W.timeoutSeconds===null?void 0:W.timeoutSeconds!==void 0?W.timeoutSeconds:$.timeoutSeconds,maxParallel:W.maxParallel??$.maxParallel??1,createdBy:Q,tags:W.tags??$.tags,runtimeOptions:j,metadata:W.metadata!==void 0?W.metadata:Object.keys(Z).length>0?Z:void 0}}class J4{db;constructor($={}){let W=$.dbPath??jL();this.db=JL(W),JV(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return W?D$(W):void 0}getSpec($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return W?D$(W):void 0}getSpecByExternalId($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return W?D$(W):void 0}listSpecs($={}){let W=[],Z=[];if($.triggerKind)W.push("trigger_kind = ?"),Z.push($.triggerKind);if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.parseStatus)W.push("parse_status = ?"),Z.push($.parseStatus);if(!$.includeRemoved)W.push("removed = 0");let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>D$(X))}createHubSchedule($){let W=`sched_${Q4()}`,Z=this.upsertSpec({externalId:W,sourcePath:BL(W),triggerKind:"schedule",sourceHash:VV($),parseStatus:"valid",spec:I7($)});this.initializeScheduleNextRun(Z.record.specId);let Q=this.getSpec(Z.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let W=this.db.prepare(`SELECT * FROM cron_specs
131
+ ON cron_specs(source_path);`];function AV($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let W of HL)$.exec(W)}function i9($){if(!$)return;try{let W=JSON.parse($);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return}function m7($,W={}){if(!$)return;try{let Z=JSON.parse($);if(!Array.isArray(Z))return;let Q=Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(W.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function J2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function f$($){return{specId:Q0($.spec_id),externalId:Q0($.external_id),sourcePath:Q0($.source_path),triggerKind:Q0($.trigger_kind),sourceMtimeMs:J2($.source_mtime_ms),sourceHash:c($.source_hash),parseStatus:Q0($.parse_status)==="invalid"?"invalid":"valid",parseError:c($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:Q0($.title),prompt:c($.prompt),workspaceRoot:c($.workspace_root),scheduleExpr:c($.schedule_expr),timezone:c($.timezone),eventType:c($.event_type),filters:i9(c($.filters_json)),debounceSeconds:J2($.debounce_seconds),dedupeWindowSeconds:J2($.dedupe_window_seconds),cooldownSeconds:J2($.cooldown_seconds),mode:c($.mode),systemPrompt:c($.system_prompt),providerId:c($.provider_id),modelId:c($.model_id),maxIterations:J2($.max_iterations),timeoutSeconds:J2($.timeout_seconds),maxParallel:J2($.max_parallel),tools:m7(c($.tools_json),{preserveEmpty:!0}),notesDirectory:c($.notes_directory),extensions:m7(c($.extensions_json),{preserveEmpty:!0}),source:c($.source),tags:m7(c($.tags_json)),metadata:i9(c($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:c($.last_materialized_run_id),lastRunAt:c($.last_run_at),nextRunAt:c($.next_run_at),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function v7($){return{runId:Q0($.run_id),specId:Q0($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:Q0($.trigger_kind),status:Q0($.status),claimToken:c($.claim_token),claimStartedAt:c($.claim_started_at),claimUntilAt:c($.claim_until_at),scheduledFor:c($.scheduled_for),triggerEventId:c($.trigger_event_id),startedAt:c($.started_at),completedAt:c($.completed_at),sessionId:c($.session_id),reportPath:c($.report_path),error:c($.error),attemptCount:Number($.attempt_count??0),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function UV($){return{eventId:Q0($.event_id),eventType:Q0($.event_type),source:Q0($.source),subject:c($.subject),occurredAt:Q0($.occurred_at),receivedAt:Q0($.received_at),workspaceRoot:c($.workspace_root),dedupeKey:c($.dedupe_key),payload:i9(c($.payload_json)),attributes:i9(c($.attributes_json)),processingStatus:Q0($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:c($.error),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function DV($){return $?JSON.stringify($):null}var FL=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function _V($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function AL($,W,Z,Q){for(let J of FL){let j=$[J],X=W[J];if(_V(j)!==_V(X))return!0}if(Z===!1&&Q===!0)return!0;return!1}function UL($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function DL($){return`hub/schedules/${$}.cron.md`}function _L($){let W={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(W).length>0?W:void 0}function c7($){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((W)=>W.trim().length>0),enabled:$.enabled!==!1,metadata:_L($)}}function fV($){return JSON.stringify(c7($))}function fL($,W){let Z=$.metadata?{...$.metadata}:{},Q=W.createdBy===null?void 0:W.createdBy!==void 0?W.createdBy:typeof Z.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,J=W.cwd!==void 0?W.cwd:typeof Z.__hubScheduleCwd==="string"?Z.__hubScheduleCwd:void 0,j=W.runtimeOptions!==void 0?W.runtimeOptions:Z.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0;return delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions,{name:W.name??$.title,cronPattern:W.cronPattern??$.scheduleExpr??"",prompt:W.prompt??$.prompt??"",workspaceRoot:W.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:W.modelSelection!==void 0?W.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:W.enabled??$.enabled,mode:W.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:W.systemPrompt===null?void 0:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,maxIterations:W.maxIterations===null?void 0:W.maxIterations!==void 0?W.maxIterations:$.maxIterations,timeoutSeconds:W.timeoutSeconds===null?void 0:W.timeoutSeconds!==void 0?W.timeoutSeconds:$.timeoutSeconds,maxParallel:W.maxParallel??$.maxParallel??1,createdBy:Q,tags:W.tags??$.tags,runtimeOptions:j,metadata:W.metadata!==void 0?W.metadata:Object.keys(Z).length>0?Z:void 0}}class X4{db;constructor($={}){let W=$.dbPath??KL();this.db=GL(W),AV(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return W?f$(W):void 0}getSpec($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return W?f$(W):void 0}getSpecByExternalId($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return W?f$(W):void 0}listSpecs($={}){let W=[],Z=[];if($.triggerKind)W.push("trigger_kind = ?"),Z.push($.triggerKind);if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.parseStatus)W.push("parse_status = ?"),Z.push($.parseStatus);if(!$.includeRemoved)W.push("removed = 0");let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>f$(X))}createHubSchedule($){let W=`sched_${j4()}`,Z=this.upsertSpec({externalId:W,sourcePath:DL(W),triggerKind:"schedule",sourceHash:fV($),parseStatus:"valid",spec:c7($)});this.initializeScheduleNextRun(Z.record.specId);let Q=this.getSpec(Z.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let W=this.db.prepare(`SELECT * FROM cron_specs
132
132
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
133
- ORDER BY created_at ASC LIMIT 1`).get($);return W?D$(W):void 0}listHubSchedules($={}){let W=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Z=[];if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)W.push("tags_json LIKE ?"),Z.push(`%"${j.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
133
+ ORDER BY created_at ASC LIMIT 1`).get($);return W?f$(W):void 0}listHubSchedules($={}){let W=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Z=[];if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)W.push("tags_json LIKE ?"),Z.push(`%"${j.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
134
134
  WHERE ${W.join(" AND ")}
135
- ORDER BY created_at DESC LIMIT ?`).all(...Z,Q).map((j)=>D$(j))}updateHubSchedule($,W){let Z=this.getHubSchedule($);if(!Z)return;let Q=GL(Z,W),J=this.upsertSpec({externalId:$,sourcePath:Z.sourcePath,triggerKind:"schedule",sourceHash:VV(Q),parseStatus:"valid",spec:I7(Q)});if(W.cronPattern!==void 0||W.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let W=this.getHubSchedule($);if(!W)return!1;return this.markSpecRemoved(W.specId),this.cancelQueuedRunsForSpec(W.specId),!0}enqueueHubScheduleRun($,W="manual"){let Z=this.getHubSchedule($);if(!Z||!Z.enabled||Z.removed||Z.parseStatus!=="valid")return;return this.enqueueRun({specId:Z.specId,specRevision:Z.revision,triggerKind:W,scheduledFor:q0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
135
+ ORDER BY created_at DESC LIMIT ?`).all(...Z,Q).map((j)=>f$(j))}updateHubSchedule($,W){let Z=this.getHubSchedule($);if(!Z)return;let Q=fL(Z,W),J=this.upsertSpec({externalId:$,sourcePath:Z.sourcePath,triggerKind:"schedule",sourceHash:fV(Q),parseStatus:"valid",spec:c7(Q)});if(W.cronPattern!==void 0||W.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let W=this.getHubSchedule($);if(!W)return!1;return this.markSpecRemoved(W.specId),this.cancelQueuedRunsForSpec(W.specId),!0}enqueueHubScheduleRun($,W="manual"){let Z=this.getHubSchedule($);if(!Z||!Z.enabled||Z.removed||Z.parseStatus!=="valid")return;return this.enqueueRun({specId:Z.specId,specRevision:Z.revision,triggerKind:W,scheduledFor:M0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
136
136
  WHERE trigger_kind = 'event'
137
137
  AND event_type = ?
138
138
  AND enabled = 1
139
139
  AND removed = 0
140
140
  AND parse_status = 'valid'
141
- ORDER BY created_at ASC`).all($).map((Z)=>D$(Z))}upsertSpec($){let W=q0(),Z=this.getSpecBySourcePath($.sourcePath),Q=$.spec,J={title:Q?.title??Z?.title??VL($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},j=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!Z){let H=`cspec_${Q4()}`;this.insertSpecRow(H,$,J,j,W);let G=this.getSpec(H);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let Y=Z.sourceHash!==$.sourceHash&&YL(Z,J,Z.enabled,j),V=Y?Z.revision+1:Z.revision;this.updateSpecRow(Z.specId,$,J,j,V,W);let B=this.getSpec(Z.specId);if(!B)throw Error("failed to reload cron_spec after update");return{record:B,created:!1,revisionChanged:Y}}insertSpecRow($,W,Z,Q,J){let j=W.spec;this.db.prepare(`INSERT INTO cron_specs (
141
+ ORDER BY created_at ASC`).all($).map((Z)=>f$(Z))}upsertSpec($){let W=M0(),Z=this.getSpecBySourcePath($.sourcePath),Q=$.spec,J={title:Q?.title??Z?.title??UL($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},j=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!Z){let H=`cspec_${j4()}`;this.insertSpecRow(H,$,J,j,W);let G=this.getSpec(H);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let Y=Z.sourceHash!==$.sourceHash&&AL(Z,J,Z.enabled,j),V=Y?Z.revision+1:Z.revision;this.updateSpecRow(Z.specId,$,J,j,V,W);let B=this.getSpec(Z.specId);if(!B)throw Error("failed to reload cron_spec after update");return{record:B,created:!1,revisionChanged:Y}}insertSpecRow($,W,Z,Q,J){let j=W.spec;this.db.prepare(`INSERT INTO cron_specs (
142
142
  spec_id, external_id, source_path, trigger_kind,
143
143
  source_mtime_ms, source_hash, parse_status, parse_error,
144
144
  enabled, removed, title, prompt, workspace_root,
@@ -161,7 +161,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
161
161
  tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
162
162
  tags_json = ?, metadata_json = ?,
163
163
  revision = ?, updated_at = ?
164
- WHERE spec_id = ?`).run(W.externalId,W.triggerKind,W.sourceMtimeMs??null,W.sourceHash,W.parseStatus,W.parseError??null,Q?1:0,Z.title??"",Z.prompt??null,Z.workspaceRoot??null,Z.scheduleExpr??null,Z.timezone??null,Z.eventType??null,Z.filters?JSON.stringify(Z.filters):null,Z.debounceSeconds??null,Z.dedupeWindowSeconds??null,Z.cooldownSeconds??null,Z.mode??null,Z.systemPrompt??null,Z.providerId??null,Z.modelId??null,Z.maxIterations??null,Z.timeoutSeconds??null,Z.maxParallel??null,Z.tools?JSON.stringify(Z.tools):null,Z.notesDirectory??null,Z.extensions?JSON.stringify(Z.extensions):null,Z.source??null,X?.tags?JSON.stringify(X.tags):null,X?.metadata?JSON.stringify(X.metadata):null,J,j,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(q0(),$)}updateSpecNextRunAt($,W){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W??null,q0(),$)}updateSpecLastRunAt($,W){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W,q0(),$)}updateLastMaterializedRunId($,W){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(W,q0(),$)}initializeScheduleNextRun($){let W=this.getSpec($);if(!W||W.triggerKind!=="schedule"||!W.enabled||!W.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Z=new Date(Z2(W.scheduleExpr,Date.now(),W.timezone)).toISOString();this.updateSpecNextRunAt($,Z)}materializeDueScheduleRun($){let W=$.nowMs,Z=new Date(W).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let J=D$(Q);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let j=J.nextRunAt;if(!j){let V=new Date(Z2(J.scheduleExpr,W,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Z,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(j).getTime()>W)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:j};let X=`crun_${Q4()}`,Y;try{Y=new Date(Z2(J.scheduleExpr,W,J.timezone)).toISOString()}catch{Y=void 0}return this.db.prepare(`INSERT INTO cron_runs (
164
+ WHERE spec_id = ?`).run(W.externalId,W.triggerKind,W.sourceMtimeMs??null,W.sourceHash,W.parseStatus,W.parseError??null,Q?1:0,Z.title??"",Z.prompt??null,Z.workspaceRoot??null,Z.scheduleExpr??null,Z.timezone??null,Z.eventType??null,Z.filters?JSON.stringify(Z.filters):null,Z.debounceSeconds??null,Z.dedupeWindowSeconds??null,Z.cooldownSeconds??null,Z.mode??null,Z.systemPrompt??null,Z.providerId??null,Z.modelId??null,Z.maxIterations??null,Z.timeoutSeconds??null,Z.maxParallel??null,Z.tools?JSON.stringify(Z.tools):null,Z.notesDirectory??null,Z.extensions?JSON.stringify(Z.extensions):null,Z.source??null,X?.tags?JSON.stringify(X.tags):null,X?.metadata?JSON.stringify(X.metadata):null,J,j,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(M0(),$)}updateSpecNextRunAt($,W){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W??null,M0(),$)}updateSpecLastRunAt($,W){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W,M0(),$)}updateLastMaterializedRunId($,W){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(W,M0(),$)}initializeScheduleNextRun($){let W=this.getSpec($);if(!W||W.triggerKind!=="schedule"||!W.enabled||!W.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Z=new Date(Q2(W.scheduleExpr,Date.now(),W.timezone)).toISOString();this.updateSpecNextRunAt($,Z)}materializeDueScheduleRun($){let W=$.nowMs,Z=new Date(W).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let J=f$(Q);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let j=J.nextRunAt;if(!j){let V=new Date(Q2(J.scheduleExpr,W,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Z,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(j).getTime()>W)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:j};let X=`crun_${j4()}`,Y;try{Y=new Date(Q2(J.scheduleExpr,W,J.timezone)).toISOString()}catch{Y=void 0}return this.db.prepare(`INSERT INTO cron_runs (
165
165
  run_id, spec_id, spec_revision, trigger_kind, status,
166
166
  scheduled_for, trigger_event_id, attempt_count,
167
167
  created_at, updated_at
@@ -170,22 +170,22 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
170
170
  last_run_at = ?,
171
171
  next_run_at = ?,
172
172
  updated_at = ?
173
- WHERE spec_id = ?`).run(X,Z,Y??null,Z,J.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(X),nextRunAt:Y}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let W=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return W?k7(W):void 0}insertEventLog($,W={}){let Z=q0(),Q=W.receivedAtIso??Z,J=$.eventId.trim();if(!J)throw Error("automation event requires eventId");let j=$.eventType.trim();if(!j)throw Error("automation event requires eventType");let X=$.source.trim();if(!X)throw Error("automation event requires source");let Y=$.occurredAt.trim()||Q,V=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
173
+ WHERE spec_id = ?`).run(X,Z,Y??null,Z,J.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(X),nextRunAt:Y}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let W=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return W?v7(W):void 0}insertEventLog($,W={}){let Z=M0(),Q=W.receivedAtIso??Z,J=$.eventId.trim();if(!J)throw Error("automation event requires eventId");let j=$.eventType.trim();if(!j)throw Error("automation event requires eventType");let X=$.source.trim();if(!X)throw Error("automation event requires source");let Y=$.occurredAt.trim()||Q,V=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
174
174
  event_id, event_type, source, subject,
175
175
  occurred_at, received_at, workspace_root, dedupe_key,
176
176
  payload_json, attributes_json, processing_status,
177
177
  matched_spec_count, queued_run_count, suppressed_count,
178
178
  error, created_at, updated_at
179
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(J,j,X,$.subject?.trim()||null,Y,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,XV($.payload),XV($.attributes),"received",0,0,0,null,Z,Z).changes??0,B=this.getEventLog(J);if(!B)throw Error("failed to insert cron_event_log row");return{record:B,created:V===1}}getEventLog($){let W=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return W?jV(W):void 0}listEventLogs($={}){let W=[],Z=[];if($.eventType)W.push("event_type = ?"),Z.push($.eventType);if($.source)W.push("source = ?"),Z.push($.source);if($.processingStatus)W.push("processing_status = ?"),Z.push($.processingStatus);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
179
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(J,j,X,$.subject?.trim()||null,Y,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,DV($.payload),DV($.attributes),"received",0,0,0,null,Z,Z).changes??0,B=this.getEventLog(J);if(!B)throw Error("failed to insert cron_event_log row");return{record:B,created:V===1}}getEventLog($){let W=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return W?UV(W):void 0}listEventLogs($={}){let W=[],Z=[];if($.eventType)W.push("event_type = ?"),Z.push($.eventType);if($.source)W.push("source = ?"),Z.push($.source);if($.processingStatus)W.push("processing_status = ?"),Z.push($.processingStatus);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
180
180
  ORDER BY received_at DESC, created_at DESC
181
- LIMIT ?`).all(...Z,J).map((X)=>jV(X))}updateEventLogProcessing($,W){return(this.db.prepare(`UPDATE cron_event_log SET
181
+ LIMIT ?`).all(...Z,J).map((X)=>UV(X))}updateEventLogProcessing($,W){return(this.db.prepare(`UPDATE cron_event_log SET
182
182
  processing_status = ?,
183
183
  matched_spec_count = COALESCE(?, matched_spec_count),
184
184
  queued_run_count = COALESCE(?, queued_run_count),
185
185
  suppressed_count = COALESCE(?, suppressed_count),
186
186
  error = ?,
187
187
  updated_at = ?
188
- WHERE event_id = ?`).run(W.status,W.matchedSpecCount??null,W.queuedRunCount??null,W.suppressedCount??null,W.error??null,q0(),$).changes??0)===1}listRuns($={}){let W=[],Z=[];if($.specId)W.push("spec_id = ?"),Z.push($.specId);if($.status){let X=Array.isArray($.status)?$.status:[$.status];if(X.length>0){let Y=X.map(()=>"?").join(",");W.push(`status IN (${Y})`);for(let V of X)Z.push(V)}}let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>k7(X))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
188
+ WHERE event_id = ?`).run(W.status,W.matchedSpecCount??null,W.queuedRunCount??null,W.suppressedCount??null,W.error??null,M0(),$).changes??0)===1}listRuns($={}){let W=[],Z=[];if($.specId)W.push("spec_id = ?"),Z.push($.specId);if($.status){let X=Array.isArray($.status)?$.status:[$.status];if(X.length>0){let Y=X.map(()=>"?").join(",");W.push(`status IN (${Y})`);for(let V of X)Z.push(V)}}let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>v7(X))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
189
189
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
190
190
  WHERE r.spec_id = ?
191
191
  AND r.trigger_kind = 'event'
@@ -203,7 +203,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
203
203
  AND r.status = 'queued'
204
204
  AND e.dedupe_key = ?
205
205
  ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
206
- LIMIT 1`).get($.specId,$.dedupeKey);return W?k7(W):void 0}updateQueuedEventRunForDebounce($){let W=q0();if((this.db.prepare(`UPDATE cron_runs SET
206
+ LIMIT 1`).get($.specId,$.dedupeKey);return W?v7(W):void 0}updateQueuedEventRunForDebounce($){let W=M0();if((this.db.prepare(`UPDATE cron_runs SET
207
207
  trigger_event_id = ?,
208
208
  scheduled_for = ?,
209
209
  updated_at = ?
@@ -212,12 +212,12 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
212
212
  AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,W,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,W){return!!this.db.prepare(`SELECT run_id FROM cron_runs
213
213
  WHERE spec_id = ? AND spec_revision = ?
214
214
  AND trigger_kind = 'one_off'
215
- LIMIT 1`).get($,W)}enqueueRun($){let W=`crun_${Q4()}`,Z=q0();this.db.prepare(`INSERT INTO cron_runs (
215
+ LIMIT 1`).get($,W)}enqueueRun($){let W=`crun_${j4()}`,Z=M0();this.db.prepare(`INSERT INTO cron_runs (
216
216
  run_id, spec_id, spec_revision, trigger_kind, status,
217
217
  scheduled_for, trigger_event_id, attempt_count,
218
218
  created_at, updated_at
219
219
  ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(W,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,Z,Z),this.updateLastMaterializedRunId($.specId,W);let Q=this.getRun(W);if(!Q)throw Error("failed to insert cron_run row");return Q}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
220
- WHERE spec_id = ? AND status = 'queued'`).run(q0(),$).changes??0}claimDueRuns($){let W=$.nowIso,Z=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(W).getTime()+Z).toISOString(),J=Math.max(1,Math.floor($.limit??25)),j=[];this.db.exec("BEGIN IMMEDIATE;");try{let X=this.db.prepare(`SELECT * FROM cron_runs
220
+ WHERE spec_id = ? AND status = 'queued'`).run(M0(),$).changes??0}claimDueRuns($){let W=$.nowIso,Z=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(W).getTime()+Z).toISOString(),J=Math.max(1,Math.floor($.limit??25)),j=[];this.db.exec("BEGIN IMMEDIATE;");try{let X=this.db.prepare(`SELECT * FROM cron_runs
221
221
  WHERE (
222
222
  status = 'queued'
223
223
  OR (
@@ -229,7 +229,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
229
229
  )
230
230
  AND (scheduled_for IS NULL OR scheduled_for <= ?)
231
231
  ORDER BY COALESCE(scheduled_for, created_at) ASC
232
- LIMIT ?`).all(W,W,J);for(let Y of X){let V=Z0(Y.run_id);if(!V)continue;let B=`cclaim_${Q4()}`;if((this.db.prepare(`UPDATE cron_runs SET
232
+ LIMIT ?`).all(W,W,J);for(let Y of X){let V=Q0(Y.run_id);if(!V)continue;let B=`cclaim_${j4()}`;if((this.db.prepare(`UPDATE cron_runs SET
233
233
  status = 'running',
234
234
  claim_token = ?,
235
235
  claim_started_at = ?,
@@ -251,7 +251,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
251
251
  AND completed_at IS NULL
252
252
  )
253
253
  )`).run(B,W,Q,W,W,V,W).changes??0)!==1)continue;let G=this.getRun(V);if(!G)continue;j.push({run:G,claimToken:B,claimUntilAt:Q})}this.db.exec("COMMIT;")}catch(X){throw this.db.exec("ROLLBACK;"),X}return j}renewClaim($,W,Z){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
254
- WHERE run_id = ? AND claim_token = ?`).run(Z,q0(),$,W).changes??0)===1}completeRun($,W){let Z=W.completedAtIso??q0(),Q=W.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
254
+ WHERE run_id = ? AND claim_token = ?`).run(Z,M0(),$,W).changes??0)===1}completeRun($,W){let Z=W.completedAtIso??M0(),Q=W.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
255
255
  status = ?,
256
256
  session_id = COALESCE(?, session_id),
257
257
  report_path = COALESCE(?, report_path),
@@ -261,7 +261,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
261
261
  claim_token = NULL,
262
262
  claim_until_at = NULL,
263
263
  updated_at = ?
264
- ${Q}`).run(W.status,W.sessionId??null,W.reportPath??null,W.error??null,Z,Z,$,...W.claimToken?[W.claimToken]:[]).changes??0)>0}requeueRun($){let W=q0();return(this.db.prepare(`UPDATE cron_runs SET
264
+ ${Q}`).run(W.status,W.sessionId??null,W.reportPath??null,W.error??null,Z,Z,$,...W.claimToken?[W.claimToken]:[]).changes??0)>0}requeueRun($){let W=M0();return(this.db.prepare(`UPDATE cron_runs SET
265
265
  status = 'queued',
266
266
  claim_started_at = NULL,
267
267
  claim_token = NULL,
@@ -273,9 +273,9 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
273
273
  error = ?,
274
274
  scheduled_for = COALESCE(?, scheduled_for),
275
275
  updated_at = ?
276
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,q0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,q0(),$)}}function cW($){return $?new Date($).getTime():void 0}function KL($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function vW($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__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:cW($.nextRunAt),lastRunAt:cW($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:KL($)}}function FL($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function x7($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:cW($.startedAt),endedAt:cW($.completedAt),status:FL($.status),errorMessage:$.error}}class f8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new J4({dbPath:$.dbPath}),this.materializer=new s6({store:this.store}),this.runner=new $4({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(y7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return vW(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?vW(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>vW(W))}updateSchedule($,W){if(W.cronPattern!==void 0)y7(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?vW(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 W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return x7(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),x7(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return x7(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}H9();import{createSessionId as QO,isHubProtocolCompatible as JO,resolveClineBuildEnv as jO,resolveHubCommandTimeoutMs as XO}from"@cline/shared";var PV={};w(PV,{splitCoreSessionConfig:()=>A4,isSessionNotFoundError:()=>l1,SessionNotFoundError:()=>d1,SESSION_NOT_FOUND_ERROR_CODE:()=>j2});var j2="session_not_found";class d1 extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function l1($){return $ instanceof d1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function A4($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}import{spawn as hT}from"node:child_process";import{closeSync as kT,mkdirSync as IT,openSync as xT}from"node:fs";import{basename as gT,dirname as mT,join as vT}from"node:path";import{fileURLToPath as cT}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as uT,isHubDaemonProcess as dV,isHubProtocolCompatible as dT,resolveClineBuildEnv as lV,withResolvedClineBuildEnv as lT}from"@cline/shared";import{createHash as HT,randomBytes as GT}from"node:crypto";import{existsSync as KT}from"node:fs";import{chmod as FT,mkdir as d7,readFile as hV,rm as l7,writeFile as kV}from"node:fs/promises";import{dirname as IV,join as p7}from"node:path";import{resolveClineDataDir as X2,resolveClineDir as xV}from"@cline/shared/storage";var q8="0.0.61";var U4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:q8,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 AT="CLINE_HUB_DISCOVERY_PATH",UT="CLINE_HUB_BUILD_ID",bV=30000,fT=15000,DT=100;function _T($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function LT($){return HT("sha256").update($).digest("hex").slice(0,12)}function TT($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function G9(){return GT(32).toString("hex")}function OT($){return new Promise((W)=>setTimeout(W,$))}function zT($){return`${$}.lock`}async function qT($){try{let W=JSON.parse(await hV(p7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function yV($){await l7($,{recursive:!0,force:!0}).catch(()=>{return})}function K9(){return process.env[UT]?.trim()||String(U4.version)}function p1($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${LT($)}`,Z=process.env[AT]?.trim()||p7(X2(),"locks","hub","owners",`${_T(W)}.json`);return{ownerId:W,discoveryPath:Z}}function gV($=`hub-${Date.now().toString(36)}`){return p1($)}async function U0($){try{let W=JSON.parse(await hV($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function F9($,W){await d7(IV($),{recursive:!0}),await l7($,{force:!0}).catch(()=>{return}),await kV($,`${JSON.stringify(W,null,2)}
277
- `,{encoding:"utf8",mode:384}),await FT($,384)}async function x0($){await l7($,{force:!0}).catch(()=>{return})}async function A9($,W){let Z=zT($);await d7(IV(Z),{recursive:!0});let Q=Date.now()+fT;while(!0)try{await d7(Z,{recursive:!1}),await kV(p7(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
278
- `,"utf8");try{return await W()}finally{await yV(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await qT(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):bV+1;if(!X||!TT(X.pid)||Y>bV){await yV(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await OT(DT)}}async function r1($,W){try{let Z=await fetch(W?.authToken?r7($):U9($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function Y1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function U9($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function r7($){let W=new URL(U9($));return W.pathname="/status",W.toString()}function mV($){return KT($)}import{CLINE_HUB_DEV_PORT as MT,CLINE_HUB_PORT as RT,resolveClineBuildEnv as NT}from"@cline/shared";var ET="CLINE_HUB_HOST",wT="CLINE_HUB_PORT",CT="CLINE_HUB_PATHNAME",i7="127.0.0.1",n7=RT,a7="/hub";function vV($){return NT($)==="development"?MT:n7}function o7($={}){return($.env??process.env)[ET]?.trim()||i7}function M8($={}){let Z=($.env??process.env)[wT]?.trim();if(!Z)return vV($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return vV($);return Q}function s7($={}){return($.env??process.env)[CT]?.trim()||a7}function T1($={},W={}){return{host:$.host??o7(W),port:$.port??M8(W),pathname:$.pathname??s7(W)}}import{join as PT}from"node:path";var ST="shared:cline",bT="CLINE_HUB_DISCOVERY_PATH",yT="hub-production";function cV($){let W=D1($.trim());return p1(`workspace:${W||$.trim()}`)}function V1($=ST){return p1($)}function O1(){return{ownerId:yT,discoveryPath:process.env[bT]?.trim()||PT(X2(),"locks","hub","production.json")}}var pT=8000,rT=200,iT=3000,nT=100,aT=[100,250,500,1000,2000],oT="--cline-hub-daemon";function sT($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function tT(){try{let $=vT(X2(),"logs","hub-daemon.log");return IT(mT($),{recursive:!0}),{fd:xT($,"a"),logPath:$}}catch{return}}function pV(){return lV()==="production"?O1():V1()}function Y2($){return dT($).compatible}function uV($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function V2($,W){try{return await r1($,{authToken:W})}catch{return}}async function eT($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await V2($))?.url)return!0;await new Promise((J)=>setTimeout(J,nT))}return!1}async function f9($,W){if(await D4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await eT($.url,iT);return await x0(W).catch(()=>{return}),Z}async function f4($,W){if(Y2($))return!0;return f9($,W)}async function rV($){if(lV()!=="production")return;let W=V1();if(W.discoveryPath===$.discoveryPath)return;let Z=await U0(W.discoveryPath);if(Z?.url)await f9(Z,W.discoveryPath);else await x0(W.discoveryPath).catch(()=>{return})}function $O(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return cT(new URL(`./entry.${$}`,import.meta.url))}function WO($,W){let Z=$O(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=gT(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[oT]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...sT(W)],cwd:$,env:{...lT(process.env),CLINE_NO_INTERACTIVE:"1",[uT]:"1"}}}function ZO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function t7($,W={}){if(dV())return;let Z=WO($,W),Q=tT();try{hT(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)kT(Q.fd)}}async function R8($,W={}){for(let Z=0;;Z++)try{t7($,W);return}catch(Q){let J=aT[Z];if(!ZO(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function D9($,W={}){if(dV())return;let Z=pV(),Q=T1(W),J=Y1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;rV(Z).catch(()=>{return}).then(()=>U0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await f9(X,Z.discoveryPath)&&!j)return}else{let H=await V2(X.url,X.authToken);if(H?.url&&Y2(H)&&await z1(H.url,{authToken:X.authToken}))return;if(H?.url)await f4({...H,authToken:X.authToken},Z.discoveryPath);else await x0(Z.discoveryPath).catch(()=>{return})}let V=await V2(J);if(V?.url){if(Y2(V)){if(!j||!Y)return}else if(!await f4({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await R8($,B)}).catch(()=>{})}async function iV($,W={}){let Z=pV(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=T1(W),j=Y1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)T$(F.url,F.authToken);return F};await rV(Z).catch(()=>{return});let Y=await U0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await f9(Y,Z.discoveryPath);else{let A=await V2(Y.url,F);if(A?.url&&Y2(A)&&await z1(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await f4({...A,authToken:F},Z.discoveryPath);else await x0(Z.discoveryPath).catch(()=>{return})}}let B=await V2(j);if(B?.url){let F=uV(B,Y,j);if(Y2(B))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.${V?" 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 f4(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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 G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await R8($,G);let K=Date.now()+pT;while(Date.now()<K){let F=await U0(Z.discoveryPath);if(F?.url&&F.authToken){let f=await V2(F.url,F.authToken);if(f?.url&&Y2(f)&&await z1(f.url,{authToken:F.authToken}))return X({url:f.url,authToken:F.authToken})}let A=await V2(j);if(A?.url&&!Y2(A)){let f=uV(A,F,j);if(!await f4(f,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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((f)=>setTimeout(f,rT))}throw Error("Timed out waiting for detached hub startup.")}function _9(){return jO()==="production"?O1():V1()}function YO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function tV($){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((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return tV($.data);return String($)}function VO($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function nV($){let W=$,Z=VO(W.reason);return new b0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:e7,{closeCode:W.code,closeReason:Z||void 0})}function BO($,W){if($ instanceof b0)return $;if($ instanceof Error)return new b0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new b0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new b0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new b0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var HO=8000,GO=200,aV="*",oV=8000,KO="cline-hub-auth.",eV=new Map,$B=new Set,FO=3000,AO=3000,UO=100,e7="Hub connection closed",fO=250,DO=5000,sV=0.5;class b0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function Z3($){return $ instanceof b0}class N8 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function L9($,W){return $ instanceof N8&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function WB($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=Q3($.toString());return Z?eV.get(Z):void 0}function _O($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function Q3($){if(!_O($))return;let W=new URL(O$($));return W.search="",W.hash="",W.toString()}function $3($){let W=Q3($);return!!W&&$B.has(W)}function T$($,W){let Z=Q3($);if(Z){if($B.add(Z),W?.trim())eV.set(Z,W)}return $}class B1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new b0("hub_connection_closed",e7);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),W=this.options.authToken?.trim()||WB($);$.hash="";let Q=new(YO())($.toString(),W?[`${KO}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new b0("hub_connect_timeout",`Timed out connecting to hub after ${oV}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},oV);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=BO(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=nV(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(tV(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=nV(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.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($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=QO("hubreq_"),j=XO($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new N8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, 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(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===j2){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new d1(V,Y.error.message)}throw new N8($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!$3(this.currentUrl)||!Z3($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await B2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,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(fO*2**this.reconnectAttempt,DO),W=Math.round($*(1-sV)+Math.random()*$*sV);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!$3(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await B2({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 b0("hub_connection_closed",e7),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.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 b0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??aV}subscriptionSessionIdFromKey($){return $===aV?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function O$($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function z1($,W){let Z=new B1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function W3($,W){let Z=O$($),Q=await r1(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!JO(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await z1(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function LO($){let W=Date.now()+HO;while(Date.now()<W){let Z=await U0($.discoveryPath);if(Z?.url){let Q=await W3(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return T$(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,GO))}return}async function TO($){let W=Date.now()+AO;while(Date.now()<W){if(!(await r1($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,UO))}return!1}function OO($,W){try{return O$($)===O$(W)}catch{return!1}}function zO($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function qO($,W,Z){let Q=new B1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:FO});return!zO(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function _4($={}){if($.endpoint?.trim()){let J=await W3($.endpoint);return J.status==="compatible"?J.url:void 0}let W=_9(),Z=await U0(W.discoveryPath);if(!Z?.url)return;let Q=await W3(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return T$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await x0(W.discoveryPath).catch(()=>{return});return}async function B2($={}){let W=await _4($);if(W&&await z1(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=_9();return await R8($.workspaceRoot??process.cwd()),await LO(Z)}async function D4($,W){let Z=new URL($),Q=W?.trim()||WB(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function J3($=_9()){let W=await U0($.discoveryPath);if(!W?.url)return!1;try{if(await D4(W.url,W.authToken))return!0}catch{}return!1}async function T9($){if(!$3($.url))return;let W=_9(),Z=await U0(W.discoveryPath);if(!Z?.url||!OO(Z.url,$.url))return;if(!await qO(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await J3())return;if(!await TO(Z.url))return;return await x0(W.discoveryPath).catch(()=>{return}),await B2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as MO}from"@cline/shared";function RO($,W){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${W} (${Z} event before socket open).`:`Failed to connect to hub at ${W}.`)}var NO="cline-hub-auth.";function EO($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function wO($,W){let Z=new URL($),Q=new URL(W);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function ZB(){return MO()==="production"?O1():V1()}async function CO($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=ZB(),Q=await U0(Z.discoveryPath);if(Q?.url&&wO($.toString(),Q.url))return Q.authToken;return}async function j3($={}){let W=T1($);if(!EO($)){let Z=ZB(),Q=await U0(Z.discoveryPath);if(Q?.url)return Q.url}return Y1(W.host,W.port,W.pathname)}async function O9($){return await new Promise((W,Z)=>{(async()=>{let Q=new URL($),J=await CO(Q);Q.hash="";let j=new WebSocket(Q.toString(),J?[`${NO}${J}`]:void 0),X=new Map,Y=0;j.addEventListener("open",()=>{W({send(V){let B=V.requestId??`hub-client-${++Y}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};j.send(JSON.stringify(K))})},close(){j.close()}})}),j.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),j.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),j.addEventListener("error",(V)=>{Z(RO(V,$))})})().catch(Z)})}async function QB($){try{return(await O9($)).close(),!0}catch{return!1}}async function JB($,W){let Z=await j3($),Q=await O9(Z);try{return await Q.send({version:W.version??"v1",clientId:W.clientId??"hub-client",...W})}finally{Q.close()}}function X3($){return $?JSON.parse(JSON.stringify($)):{}}function z9($){let W=$?.session&&typeof $.session==="object"?$.session:void 0;if(!W)return;let Z=W.metadata&&typeof W.metadata==="object"?X3(W.metadata):void 0;return{sessionId:typeof W.sessionId==="string"?W.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function jB($,W){return $.error?.message??`hub command failed: ${W}`}function PO($){let W=X3($);if(typeof W.error==="string"&&W.error.trim())return{...W,error:W.error.trim()};let Z=W.result&&typeof W.result==="object"?W.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...W,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...W,error:Q.message.trim()};return W}function XB($){let W=$?.sessionId;return typeof W==="string"&&W.trim()?W.trim():void 0}function SO($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))throw Error("hub checkpoint restore returned no checkpoint");let Z=W;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function bO($){let W=X3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||XB(W)||"",eventType:"schedule.execution.completed",payload:W};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||XB(W)||"",eventType:"schedule.execution.failed",payload:W};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:W};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:W};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:W};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:W};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:W};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:W};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:W};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:W};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:W};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:PO($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:W};default:return}}class Y3{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new B1({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 W=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}),Z=z9(W.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,W,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:W.prompt,mode:W.config.mode,attachments:W.attachments,delivery:W.delivery,timeoutSeconds:W.config.timeoutSeconds},$,Z)).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 W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(l1(Z))return;throw Z}return z9(W.payload)}async readMessages($){let W=$.trim();if(!W)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Error(jB(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,J=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},W);if(!J.ok)throw Error(jB(J,"session.restore"));let j=z9(J.payload);if(Z&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,Y=SO(J.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:Y}}async listSessions($){await this.ensureMetadataApplied();let W=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(W.payload?.sessions)?W.payload?.sessions:[]).map((Q)=>z9({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,W=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:W})).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($,W){let Z=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let j=bO(J);if(!j)return;if(Z.size>0&&!Z.has(j.sessionId))return;W.onEvent?.(j)});return this.ensureMetadataApplied().catch((J)=>{W.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress($,W){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;W.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{W.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.list");return Array.isArray(W.payload?.schedules)?W.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,W){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...W})).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($,W){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:W});return Array.isArray(Z.payload?.executions)?Z.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 W=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(W.payload?.upcoming)?W.payload?.upcoming:[]}}class V3{client;constructor($){this.client=new B1({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 W=await this.client.command("session.list",{limit:$});return Array.isArray(W.payload?.sessions)?W.payload.sessions:[]}subscribeUI($){return this.client.subscribe((W)=>{switch(W.event){case"ui.notify":$.onNotify?.(W.payload);break;case"ui.show_window":$.onShowWindow?.(W.payload);break;case"hub.client.registered":$.onClientRegistered?.(W.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(W.payload??{});break;case"session.created":$.onSessionCreated?.(W.payload??{});break;case"session.updated":$.onSessionUpdated?.(W.payload??{});break;case"session.detached":$.onSessionDetached?.(W.payload??{});break}})}}import{normalizeProviderId as og}from"@cline/llms";var HD={};w(HD,{LocalRuntimeHost:()=>b1});import{readdirSync as cg}from"node:fs";import{homedir as ug}from"node:os";import{isAbsolute as dg,join as UY,resolve as fY}from"node:path";import{captureSdkError as o$,createSessionId as lg,isLikelyAuthError as pg,normalizeUserInput as rg}from"@cline/shared";import{setHomeDirIfUnset as ig}from"@cline/shared/storage";var IB={};w(IB,{saveProviderOAuthCredentials:()=>K2,resolveProviderApiKeyFromSettings:()=>q3,loginAndSaveProviderOAuthCredentials:()=>E4,isOAuthProvider:()=>G2,getProviderOAuthCredentialsFromSettings:()=>w4,getProviderAuthStorageId:()=>z3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>b8,formatProviderOAuthApiKey:()=>M3});import{decodeJwtPayload as Gz,getClineEnvironmentConfig as hB}from"@cline/shared";var DB={};w(DB,{startClineDeviceAuth:()=>f3,refreshClineToken:()=>N9,loginClineOAuth:()=>L4,getValidClineCredentials:()=>T4,completeClineDeviceAuth:()=>D3});import{getClineEnvironmentConfig as G3}from"@cline/shared";var YB={};w(YB,{setSdkLogger:()=>H3,sdkDebug:()=>Q0,hashSecret:()=>N0,getSdkLogger:()=>hO});import{createHash as yO}from"node:crypto";var B3;function H3($){B3=$}function hO(){return B3}function N0($){if(typeof $!=="string"||$.length===0)return"unset";return yO("sha256").update($).digest("hex").slice(0,8)}function Q0($){try{B3?.debug($)}catch{}}M0();var VB={};w(VB,{startLocalOAuthServer:()=>H1});function kO(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function H1($){let W=await import("node:http"),Z=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??IO,j=kO(),X=!1,Y=null,V=null,B=null,H=(F)=>{if(X)return;X=!0,j.resolve(F)},G=()=>{if(Y)clearTimeout(Y),Y=null;let F=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:F})).catch(()=>{})},K=async()=>{return Y=setTimeout(()=>{G(),H(null)},Q),j.promise};for(let F of $.ports){let A=W.createServer((U,_)=>{try{let D=new URL(U.url||"",`http://${Z}:${F}`);if(D.pathname!==$.callbackPath){_.statusCode=404,_.end("Not found");return}let M={url:D,code:D.searchParams.get("code")??void 0,state:D.searchParams.get("state")??void 0,provider:D.searchParams.get("provider")??void 0,error:D.searchParams.get("error")??void 0};if(M.error){_.statusCode=400,_.end(`Authentication failed: ${M.error}`),G(),H(M);return}if(!M.code){_.statusCode=400,_.end("Missing authorization code");return}if($.expectedState&&M.state!==$.expectedState){_.statusCode=400,_.end("State mismatch");return}_.statusCode=200,_.setHeader("Content-Type","text/html; charset=utf-8"),_.end(J),G(),H(M)}catch{_.statusCode=500,_.end("Internal error")}}),f=await new Promise((U)=>{let _=(D)=>{A.off("error",_),U({bound:!1,error:D})};A.once("error",_),A.listen(F,Z,()=>{A.off("error",_),V=A,U({bound:!0})})});if(f.error){if(f.error.code==="EADDRINUSE")continue;throw G(),f.error}if(f.bound){B=F;let U=`http://${Z}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:F,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var IO=`<!DOCTYPE html>
276
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}}function a9($){return $?new Date($).getTime():void 0}function LL($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function n9($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__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:a9($.nextRunAt),lastRunAt:a9($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:LL($)}}function TL($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function u7($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:a9($.startedAt),endedAt:a9($.completedAt),status:TL($.status),errorMessage:$.error}}class f8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath}),this.materializer=new e6({store:this.store}),this.runner=new Z4({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(g7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return n9(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?n9(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>n9(W))}updateSchedule($,W){if(W.cronPattern!==void 0)g7(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?n9(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 W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return u7(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),u7(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return u7(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}fW();import{createSessionId as HO,isHubProtocolCompatible as GO,resolveClineBuildEnv as KO,resolveHubCommandTimeoutMs as FO}from"@cline/shared";var vV={};w(vV,{splitCoreSessionConfig:()=>D4,isSessionNotFoundError:()=>p1,SessionNotFoundError:()=>l1,SESSION_NOT_FOUND_ERROR_CODE:()=>X2});var X2="session_not_found";class l1 extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function p1($){return $ instanceof l1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function D4($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}import{spawn as cT}from"node:child_process";import{closeSync as uT,mkdirSync as dT,openSync as lT}from"node:fs";import{basename as pT,dirname as rT,join as iT}from"node:path";import{fileURLToPath as nT}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as aT,isHubDaemonProcess as eV,isHubProtocolCompatible as oT,resolveClineBuildEnv as $B,withResolvedClineBuildEnv as sT}from"@cline/shared";import{createHash as _T,randomBytes as fT}from"node:crypto";import{existsSync as LT}from"node:fs";import{chmod as TT,mkdir as n7,readFile as lV,rm as a7,writeFile as pV}from"node:fs/promises";import{dirname as rV,join as o7}from"node:path";import{resolveClineDataDir as Y2,resolveClineDir as iV}from"@cline/shared/storage";var R8="0.0.62";var _4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:R8,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 OT="CLINE_HUB_DISCOVERY_PATH",zT="CLINE_HUB_BUILD_ID",uV=30000,qT=15000,MT=100;function RT($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ET($){return _T("sha256").update($).digest("hex").slice(0,12)}function NT($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function LW(){return fT(32).toString("hex")}function wT($){return new Promise((W)=>setTimeout(W,$))}function CT($){return`${$}.lock`}async function PT($){try{let W=JSON.parse(await lV(o7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function dV($){await a7($,{recursive:!0,force:!0}).catch(()=>{return})}function TW(){return process.env[zT]?.trim()||String(_4.version)}function r1($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${ET($)}`,Z=process.env[OT]?.trim()||o7(Y2(),"locks","hub","owners",`${RT(W)}.json`);return{ownerId:W,discoveryPath:Z}}function nV($=`hub-${Date.now().toString(36)}`){return r1($)}async function D0($){try{let W=JSON.parse(await lV($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function OW($,W){await n7(rV($),{recursive:!0}),await a7($,{force:!0}).catch(()=>{return}),await pV($,`${JSON.stringify(W,null,2)}
277
+ `,{encoding:"utf8",mode:384}),await TT($,384)}async function g0($){await a7($,{force:!0}).catch(()=>{return})}async function zW($,W){let Z=CT($);await n7(rV(Z),{recursive:!0});let Q=Date.now()+qT;while(!0)try{await n7(Z,{recursive:!1}),await pV(o7(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
278
+ `,"utf8");try{return await W()}finally{await dV(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await PT(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):uV+1;if(!X||!NT(X.pid)||Y>uV){await dV(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await wT(MT)}}async function i1($,W){try{let Z=await fetch(W?.authToken?s7($):qW($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function Y1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function qW($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function s7($){let W=new URL(qW($));return W.pathname="/status",W.toString()}function aV($){return LT($)}import{CLINE_HUB_DEV_PORT as ST,CLINE_HUB_PORT as bT,resolveClineBuildEnv as yT}from"@cline/shared";var hT="CLINE_HUB_HOST",kT="CLINE_HUB_PORT",IT="CLINE_HUB_PATHNAME",t7="127.0.0.1",e7=bT,$3="/hub";function oV($){return yT($)==="development"?ST:e7}function W3($={}){return($.env??process.env)[hT]?.trim()||t7}function E8($={}){let Z=($.env??process.env)[kT]?.trim();if(!Z)return oV($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return oV($);return Q}function Z3($={}){return($.env??process.env)[IT]?.trim()||$3}function T1($={},W={}){return{host:$.host??W3(W),port:$.port??E8(W),pathname:$.pathname??Z3(W)}}import{join as xT}from"node:path";var gT="shared:cline",mT="CLINE_HUB_DISCOVERY_PATH",vT="hub-production";function sV($){let W=_1($.trim());return r1(`workspace:${W||$.trim()}`)}function V1($=gT){return r1($)}function O1(){return{ownerId:vT,discoveryPath:process.env[mT]?.trim()||xT(Y2(),"locks","hub","production.json")}}var tT=8000,eT=200,$O=3000,WO=100,ZO=[100,250,500,1000,2000],QO="--cline-hub-daemon";function JO($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function jO(){try{let $=iT(Y2(),"logs","hub-daemon.log");return dT(rT($),{recursive:!0}),{fd:lT($,"a"),logPath:$}}catch{return}}function WB(){return $B()==="production"?O1():V1()}function V2($){return oT($).compatible}function tV($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function B2($,W){try{return await i1($,{authToken:W})}catch{return}}async function XO($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await B2($))?.url)return!0;await new Promise((J)=>setTimeout(J,WO))}return!1}async function MW($,W){if(await L4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await XO($.url,$O);return await g0(W).catch(()=>{return}),Z}async function f4($,W){if(V2($))return!0;return MW($,W)}async function ZB($){if($B()!=="production")return;let W=V1();if(W.discoveryPath===$.discoveryPath)return;let Z=await D0(W.discoveryPath);if(Z?.url)await MW(Z,W.discoveryPath);else await g0(W.discoveryPath).catch(()=>{return})}function YO(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return nT(new URL(`./entry.${$}`,import.meta.url))}function VO($,W){let Z=YO(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=pT(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[QO]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...JO(W)],cwd:$,env:{...sT(process.env),CLINE_NO_INTERACTIVE:"1",[aT]:"1"}}}function BO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function Q3($,W={}){if(eV())return;let Z=VO($,W),Q=jO();try{cT(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)uT(Q.fd)}}async function N8($,W={}){for(let Z=0;;Z++)try{Q3($,W);return}catch(Q){let J=ZO[Z];if(!BO(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function RW($,W={}){if(eV())return;let Z=WB(),Q=T1(W),J=Y1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;ZB(Z).catch(()=>{return}).then(()=>D0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await MW(X,Z.discoveryPath)&&!j)return}else{let H=await B2(X.url,X.authToken);if(H?.url&&V2(H)&&await z1(H.url,{authToken:X.authToken}))return;if(H?.url)await f4({...H,authToken:X.authToken},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}let V=await B2(J);if(V?.url){if(V2(V)){if(!j||!Y)return}else if(!await f4({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await N8($,B)}).catch(()=>{})}async function QB($,W={}){let Z=WB(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=T1(W),j=Y1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)O$(F.url,F.authToken);return F};await ZB(Z).catch(()=>{return});let Y=await D0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await MW(Y,Z.discoveryPath);else{let A=await B2(Y.url,F);if(A?.url&&V2(A)&&await z1(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await f4({...A,authToken:F},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}}let B=await B2(j);if(B?.url){let F=tV(B,Y,j);if(V2(B))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.${V?" 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 f4(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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 G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await N8($,G);let K=Date.now()+tT;while(Date.now()<K){let F=await D0(Z.discoveryPath);if(F?.url&&F.authToken){let D=await B2(F.url,F.authToken);if(D?.url&&V2(D)&&await z1(D.url,{authToken:F.authToken}))return X({url:D.url,authToken:F.authToken})}let A=await B2(j);if(A?.url&&!V2(A)){let D=tV(A,F,j);if(!await f4(D,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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((D)=>setTimeout(D,eT))}throw Error("Timed out waiting for detached hub startup.")}function EW(){return KO()==="production"?O1():V1()}function AO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function VB($){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((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return VB($.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 JB($){let W=$,Z=UO(W.reason);return new y0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:J3,{closeCode:W.code,closeReason:Z||void 0})}function DO($,W){if($ instanceof y0)return $;if($ instanceof Error)return new y0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new y0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new y0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new y0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var _O=8000,fO=200,jB="*",XB=8000,LO="cline-hub-auth.",BB=new Map,HB=new Set,TO=3000,OO=3000,zO=100,J3="Hub connection closed",qO=250,MO=5000,YB=0.5;class y0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function Y3($){return $ instanceof y0}class w8 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function NW($,W){return $ instanceof w8&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function GB($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=V3($.toString());return Z?BB.get(Z):void 0}function RO($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function V3($){if(!RO($))return;let W=new URL(z$($));return W.search="",W.hash="",W.toString()}function j3($){let W=V3($);return!!W&&HB.has(W)}function O$($,W){let Z=V3($);if(Z){if(HB.add(Z),W?.trim())BB.set(Z,W)}return $}class B1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new y0("hub_connection_closed",J3);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),W=this.options.authToken?.trim()||GB($);$.hash="";let Q=new(AO())($.toString(),W?[`${LO}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new y0("hub_connect_timeout",`Timed out connecting to hub after ${XB}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},XB);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=DO(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=JB(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(VB(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=JB(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.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($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=HO("hubreq_"),j=FO($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new w8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, 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(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===X2){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new l1(V,Y.error.message)}throw new w8($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!j3(this.currentUrl)||!Y3($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await H2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,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(qO*2**this.reconnectAttempt,MO),W=Math.round($*(1-YB)+Math.random()*$*YB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!j3(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await H2({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 y0("hub_connection_closed",J3),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.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 y0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??jB}subscriptionSessionIdFromKey($){return $===jB?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function z$($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function z1($,W){let Z=new B1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function X3($,W){let Z=z$($),Q=await i1(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!GO(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await z1(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function EO($){let W=Date.now()+_O;while(Date.now()<W){let Z=await D0($.discoveryPath);if(Z?.url){let Q=await X3(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,fO))}return}async function NO($){let W=Date.now()+OO;while(Date.now()<W){if(!(await i1($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,zO))}return!1}function wO($,W){try{return z$($)===z$(W)}catch{return!1}}function CO($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function PO($,W,Z){let Q=new B1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:TO});return!CO(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function T4($={}){if($.endpoint?.trim()){let J=await X3($.endpoint);return J.status==="compatible"?J.url:void 0}let W=EW(),Z=await D0(W.discoveryPath);if(!Z?.url)return;let Q=await X3(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await g0(W.discoveryPath).catch(()=>{return});return}async function H2($={}){let W=await T4($);if(W&&await z1(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=EW();return await N8($.workspaceRoot??process.cwd()),await EO(Z)}async function L4($,W){let Z=new URL($),Q=W?.trim()||GB(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function B3($=EW()){let W=await D0($.discoveryPath);if(!W?.url)return!1;try{if(await L4(W.url,W.authToken))return!0}catch{}return!1}async function wW($){if(!j3($.url))return;let W=EW(),Z=await D0(W.discoveryPath);if(!Z?.url||!wO(Z.url,$.url))return;if(!await PO(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await B3())return;if(!await NO(Z.url))return;return await g0(W.discoveryPath).catch(()=>{return}),await H2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as SO}from"@cline/shared";function bO($,W){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${W} (${Z} event before socket open).`:`Failed to connect to hub at ${W}.`)}var yO="cline-hub-auth.";function hO($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function kO($,W){let Z=new URL($),Q=new URL(W);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function KB(){return SO()==="production"?O1():V1()}async function IO($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=KB(),Q=await D0(Z.discoveryPath);if(Q?.url&&kO($.toString(),Q.url))return Q.authToken;return}async function H3($={}){let W=T1($);if(!hO($)){let Z=KB(),Q=await D0(Z.discoveryPath);if(Q?.url)return Q.url}return Y1(W.host,W.port,W.pathname)}async function CW($){return await new Promise((W,Z)=>{(async()=>{let Q=new URL($),J=await IO(Q);Q.hash="";let j=new WebSocket(Q.toString(),J?[`${yO}${J}`]:void 0),X=new Map,Y=0;j.addEventListener("open",()=>{W({send(V){let B=V.requestId??`hub-client-${++Y}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};j.send(JSON.stringify(K))})},close(){j.close()}})}),j.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),j.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),j.addEventListener("error",(V)=>{Z(bO(V,$))})})().catch(Z)})}async function FB($){try{return(await CW($)).close(),!0}catch{return!1}}async function AB($,W){let Z=await H3($),Q=await CW(Z);try{return await Q.send({version:W.version??"v1",clientId:W.clientId??"hub-client",...W})}finally{Q.close()}}function G3($){return $?JSON.parse(JSON.stringify($)):{}}function PW($){let W=$?.session&&typeof $.session==="object"?$.session:void 0;if(!W)return;let Z=W.metadata&&typeof W.metadata==="object"?G3(W.metadata):void 0;return{sessionId:typeof W.sessionId==="string"?W.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function UB($,W){return $.error?.message??`hub command failed: ${W}`}function xO($){let W=G3($);if(typeof W.error==="string"&&W.error.trim())return{...W,error:W.error.trim()};let Z=W.result&&typeof W.result==="object"?W.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...W,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...W,error:Q.message.trim()};return W}function DB($){let W=$?.sessionId;return typeof W==="string"&&W.trim()?W.trim():void 0}function gO($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))throw Error("hub checkpoint restore returned no checkpoint");let Z=W;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function mO($){let W=G3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||DB(W)||"",eventType:"schedule.execution.completed",payload:W};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||DB(W)||"",eventType:"schedule.execution.failed",payload:W};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:W};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:W};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:W};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:W};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:W};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:W};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:W};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:W};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:W};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:xO($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:W};default:return}}class K3{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new B1({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 W=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}),Z=PW(W.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,W,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:W.prompt,mode:W.config.mode,attachments:W.attachments,delivery:W.delivery,timeoutSeconds:W.config.timeoutSeconds},$,Z)).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 W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(p1(Z))return;throw Z}return PW(W.payload)}async readMessages($){let W=$.trim();if(!W)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Error(UB(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,J=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},W);if(!J.ok)throw Error(UB(J,"session.restore"));let j=PW(J.payload);if(Z&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,Y=gO(J.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:Y}}async listSessions($){await this.ensureMetadataApplied();let W=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(W.payload?.sessions)?W.payload?.sessions:[]).map((Q)=>PW({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,W=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:W})).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($,W){let Z=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let j=mO(J);if(!j)return;if(Z.size>0&&!Z.has(j.sessionId))return;W.onEvent?.(j)});return this.ensureMetadataApplied().catch((J)=>{W.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress($,W){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;W.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{W.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.list");return Array.isArray(W.payload?.schedules)?W.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,W){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...W})).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($,W){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:W});return Array.isArray(Z.payload?.executions)?Z.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 W=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(W.payload?.upcoming)?W.payload?.upcoming:[]}}class F3{client;constructor($){this.client=new B1({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 W=await this.client.command("session.list",{limit:$});return Array.isArray(W.payload?.sessions)?W.payload.sessions:[]}subscribeUI($){return this.client.subscribe((W)=>{switch(W.event){case"ui.notify":$.onNotify?.(W.payload);break;case"ui.show_window":$.onShowWindow?.(W.payload);break;case"hub.client.registered":$.onClientRegistered?.(W.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(W.payload??{});break;case"session.created":$.onSessionCreated?.(W.payload??{});break;case"session.updated":$.onSessionUpdated?.(W.payload??{});break;case"session.detached":$.onSessionDetached?.(W.payload??{});break}})}}import{normalizeProviderId as Xm}from"@cline/llms";var D_={};w(D_,{LocalRuntimeHost:()=>b1});import{readdirSync as sg}from"node:fs";import{homedir as tg}from"node:os";import{isAbsolute as eg,join as RY,resolve as EY}from"node:path";import{captureSdkError as s$,createSessionId as $m,isLikelyAuthError as Wm,normalizeUserInput as Zm}from"@cline/shared";import{setHomeDirIfUnset as Qm}from"@cline/shared/storage";var rB={};w(rB,{saveProviderOAuthCredentials:()=>F2,resolveProviderApiKeyFromSettings:()=>w3,loginAndSaveProviderOAuthCredentials:()=>C4,isOAuthProvider:()=>K2,getProviderOAuthCredentialsFromSettings:()=>P4,getProviderAuthStorageId:()=>N3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>h8,formatProviderOAuthApiKey:()=>C3});import{decodeJwtPayload as fz,getClineEnvironmentConfig as lB}from"@cline/shared";var NB={};w(NB,{startClineDeviceAuth:()=>O3,refreshClineToken:()=>hW,loginClineOAuth:()=>O4,getValidClineCredentials:()=>z4,completeClineDeviceAuth:()=>z3});import{getClineEnvironmentConfig as D3}from"@cline/shared";var _B={};w(_B,{setSdkLogger:()=>U3,sdkDebug:()=>s,hashSecret:()=>N0,getSdkLogger:()=>cO});import{createHash as vO}from"node:crypto";var A3;function U3($){A3=$}function cO(){return A3}function N0($){if(typeof $!=="string"||$.length===0)return"unset";return vO("sha256").update($).digest("hex").slice(0,8)}function s($){try{A3?.debug($)}catch{}}R0();var fB={};w(fB,{startLocalOAuthServer:()=>H1});function uO(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function H1($){let W=await import("node:http"),Z=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??dO,j=uO(),X=!1,Y=null,V=null,B=null,H=(F)=>{if(X)return;X=!0,j.resolve(F)},G=()=>{if(Y)clearTimeout(Y),Y=null;let F=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:F})).catch(()=>{})},K=async()=>{return Y=setTimeout(()=>{G(),H(null)},Q),j.promise};for(let F of $.ports){let A=W.createServer((U,f)=>{try{let _=new URL(U.url||"",`http://${Z}:${F}`);if(_.pathname!==$.callbackPath){f.statusCode=404,f.end("Not found");return}let R={url:_,code:_.searchParams.get("code")??void 0,state:_.searchParams.get("state")??void 0,provider:_.searchParams.get("provider")??void 0,error:_.searchParams.get("error")??void 0};if(R.error){f.statusCode=400,f.end(`Authentication failed: ${R.error}`),G(),H(R);return}if(!R.code){f.statusCode=400,f.end("Missing authorization code");return}if($.expectedState&&R.state!==$.expectedState){f.statusCode=400,f.end("State mismatch");return}f.statusCode=200,f.setHeader("Content-Type","text/html; charset=utf-8"),f.end(J),G(),H(R)}catch{f.statusCode=500,f.end("Internal error")}}),D=await new Promise((U)=>{let f=(_)=>{A.off("error",f),U({bound:!1,error:_})};A.once("error",f),A.listen(F,Z,()=>{A.off("error",f),V=A,U({bound:!0})})});if(D.error){if(D.error.code==="EADDRINUSE")continue;throw G(),D.error}if(D.bound){B=F;let U=`http://${Z}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:F,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var dO=`<!DOCTYPE html>
279
279
  <html lang="en">
280
280
  <head>
281
281
  <meta charset="utf-8">
@@ -316,27 +316,27 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
316
316
  </div>
317
317
  <script>setTimeout(() => window.close(), 3000);</script>
318
318
  </body>
319
- </html>`;function BB($){let W="";for(let Z=0;Z<$.length;Z+=1)W+=String.fromCharCode($[Z]??0);return btoa(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function xO($){let Z=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",Z);return new Uint8Array(Q)}function gO($=32){let W=new Uint8Array($);return crypto.getRandomValues(W),BB(W)}async function q9(){let $=gO(),W=BB(await xO($));return{verifier:$,challenge:W}}function M9($){return $.endsWith("/")?$.slice(0,-1):$}function H2($,W){return new URL(W,`${M9($)}/`).toString()}function E8($,W={}){let Z=$.trim();if(!Z)return{};try{let Q=new URL(Z);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:W.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(W.allowHashCodeState&&Z.includes("#")){let[Q,J]=Z.split("#",2);return{code:Q||void 0,state:J||void 0}}if(Z.includes("code=")){let Q=new URLSearchParams(Z);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:W.includeProvider?Q.get("provider")??void 0:void 0}}return{code:Z}}function w8($){try{let W=JSON.parse($),Z=W.error,Q=typeof Z==="string"?Z:Z&&typeof Z==="object"&&typeof Z.type==="string"?Z.type:void 0,J=typeof W.error_description==="string"?W.error_description:typeof W.message==="string"?W.message:Z&&typeof Z==="object"&&typeof Z.message==="string"?Z.message:void 0;return{code:Q,message:J}}catch{return{}}}function C8($,W){return Date.now()>=$.expires-W}async function P8($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let W,Z,Q=$.onManualCodeInput().then((j)=>{W=j,$.cancelWait()}).catch((j)=>{Z=j instanceof Error?j:Error(String(j)),$.cancelWait()}),J=await $.waitForCallback();if(Z)throw Z;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(W)return E8(W,$.parseOptions);if(await Q,Z)throw Z;if(W)return E8(W,$.parseOptions);return{}}var R9={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},FB={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},K3="https://api.workos.com",mO="/auth",HB=Array.from({length:11},($,W)=>48801+W),vO=300000,cO=30000,S8=30000,uO=300,dO=5;class q1 extends Error{status;errorCode;constructor($,W){super($);this.name="ClineOAuthTokenError",this.status=W?.status,this.errorCode=W?.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 lO($){let W=Date.parse($);if(Number.isNaN(W))throw Error(`Invalid expiresAt value: ${$}`);return W}function F3($,W,Z={}){let Q=$.userInfo.clineUserId??Z.accountId,J=$.refreshToken??Z.refresh;if(!J)throw Error("Token response did not include a refresh token");let j={...Z.metadata??{},provider:W,tokenType:$.tokenType,userInfo:$.userInfo};return delete j.startedAt,{access:$.accessToken,refresh:J,expires:lO($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||Z.email,metadata:j}}async function A3($){if(!$)return{};return typeof $==="function"?await $():$}function GB($,W){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return W;return Math.floor($)}async function KB($){await new Promise((W)=>setTimeout(W,$))}function U3($,W){if(!$.success||!$.data?.accessToken)throw Error(W);return $.data}async function AB($,W){let Z=await fetch(H2(K3,FB.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(W?.requestTimeoutMs??S8)}),Q=await Z.json().catch(()=>({}));if(!Z.ok)throw new q1(`Device authorization failed: ${Z.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:Z.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:GB(Q.expires_in,uO),pollIntervalSeconds:GB(Q.interval,dO)}}async function UB($){let W=Date.now()+$.expiresInSeconds*1000,Z=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=W){let Q=await fetch(H2($.workosApiBaseUrl,FB.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)}),J=await Q.json().catch(()=>({}));if(Q.ok){if(!J.access_token||!J.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:J.access_token,refreshToken:J.refresh_token,tokenType:J.token_type??"Bearer"}}switch(J.error){case"authorization_pending":{await KB(Z*1000);break}case"slow_down":{Z+=1,await KB(Z*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new q1(J.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:J.error});default:throw new q1(`WorkOS token polling failed: ${Q.status}${J.error_description?` - ${J.error_description}`:""}`,{status:Q.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function fB($,W,Z){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(H2(W.apiBaseUrl,R9.register),{method:"POST",headers:{"Content-Type":"application/json",...await A3(W.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(W.requestTimeoutMs??S8)});if(!J.ok){let X=await J.text().catch(()=>""),Y=w8(X);throw new q1(`Token registration failed: ${J.status}${Y.message?` - ${Y.message}`:""}`,{status:J.status,errorCode:Y.code})}let j=await J.json();return F3(U3(j,"Invalid token exchange response"),Z??W.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function pO($,W,Z,Q){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:W,provider:Q??Z.provider},j=await fetch(H2(Z.apiBaseUrl,R9.token),{method:"POST",headers:{"Content-Type":"application/json",...await A3(Z.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Z.requestTimeoutMs??S8)});if(!j.ok){let Y=await j.text().catch(()=>""),V=w8(Y);throw new q1(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let X=await j.json();return F3(U3(X,"Invalid token exchange response"),Q??Z.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function L4($){x1($.telemetry,$.provider??"cline");let W=$.useWorkOSDeviceAuth??!0,Z=$.callbackPorts?.length?$.callbackPorts:HB,Q=$.callbackPath??mO,J=W?null:await H1({ports:Z,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=J?.callbackUrl||`http://127.0.0.1:${Z[0]??HB[0]}${Q}`;try{let X;if(W){let Y=G3().workOsClientId,V=await AB(Y,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let B=await UB({clientId:Y,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??S8,workosApiBaseUrl:K3,onProgress:$.callbacks.onProgress});X=await fB(B,$,$.provider)}else{let Y=new URL(H2($.apiBaseUrl,R9.authorize));Y.searchParams.set("client_type","extension"),Y.searchParams.set("callback_url",j),Y.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:Y.toString(),instructions:"Continue the authentication process in your browser."});let V,B=$.provider,H=await P8({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(V=H.code,B=H.provider??B,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=E8(G,{includeProvider:!0});V=K.code,B=K.provider??B}if(!V)throw Error("Missing authorization code");X=await pO(V,j,$,B)}return g1($.telemetry,$.provider??"cline"),v1($.telemetry,{id:X.accountId,email:X.email,provider:$.provider??"cline"}),X}catch(X){throw m1($.telemetry,$.provider??"cline",X instanceof Error?X.message:String(X)),X}finally{J?.close()}}async function f3($){return await AB(G3().workOsClientId,$)}async function D3($){let W=$.provider??"cline";x1($.telemetry,W);try{let Z=await UB({clientId:G3().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??S8,workosApiBaseUrl:K3}),Q=await fB(Z,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return g1($.telemetry,W),v1($.telemetry,{id:Q.accountId,email:Q.email,provider:W}),Q}catch(Z){throw m1($.telemetry,W,Z instanceof Error?Z.message:String(Z)),Z}}async function N9($,W){let Z=H2(W.apiBaseUrl,R9.refresh);Q0(`cline.refresh.request url=${Z} refreshTokenHash=${N0($.refresh)}`);let Q=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/json",...await A3(W.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(W.requestTimeoutMs??S8)});if(!Q.ok){let Y=await Q.text().catch(()=>""),V=w8(Y);throw Q0(`cline.refresh.error status=${Q.status} errorCode=${V.code??"none"} message=${V.message??"none"}`),new q1(`Token refresh failed: ${Q.status}${V.message?` - ${V.message}`:""}`,{status:Q.status,errorCode:V.code})}let J=await Q.json(),j=$.metadata?.provider??W.provider,X=F3(U3(J,"Invalid token refresh response"),j,$);return Q0(`cline.refresh.success newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} expires=${X.expires}`),X}async function T4($,W,Z){if(!$)return Q0("cline.getCredentials outcome=no_current_credentials"),null;let Q=Z?.refreshBufferMs??vO,J=Z?.retryableTokenGraceMs??cO,j=Z?.forceRefresh===!0;if(!j&&!C8($,Q))return Q0(`cline.getCredentials outcome=still_valid forceRefresh=${j}`),$;Q0(`cline.getCredentials outcome=needs_refresh forceRefresh=${j} accessTokenHash=${N0($.access)}`);try{return await N9($,W)}catch(X){let Y={status:X instanceof q1?X.status:void 0,errorCode:X instanceof q1?X.errorCode:void 0,errorName:X instanceof Error?X.name:void 0};if(X instanceof q1&&X.isLikelyInvalidGrant())return Q0(`cline.getCredentials outcome=invalid_grant status=${X.status} errorCode=${X.errorCode??"none"}`),_$(W.telemetry,W.provider??"cline","invalid_grant",{status:X.status,errorCode:X.errorCode}),null;if($.expires-Date.now()>J)return Q0(`cline.getCredentials outcome=transient_failure_kept_current error=${X instanceof Error?X.message:String(X)}`),g7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!1}),$;throw Q0(`cline.getCredentials outcome=transient_failure_rethrown error=${X instanceof Error?X.message:String(X)}`),g7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!0}),X}}M0();var LB={};w(LB,{refreshOpenAICodexToken:()=>w9,loginOpenAICodex:()=>O4,getValidOpenAICodexCredentials:()=>z4,OPENAI_CODEX_OAUTH_CONFIG:()=>Y0});import{decodeJwtPayload as _3}from"@cline/shared";import{nanoid as rO}from"nanoid";var Y0={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 E9 extends Error{status;errorCode;constructor($,W){super($);this.name="OpenAICodexOAuthTokenError",this.status=W?.status,this.errorCode=W?.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 iO($,W,Z=Y0.redirectUri){let Q=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:Y0.clientId,code:$,code_verifier:W,redirect_uri:Z}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let J=await Q.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}async function nO($){try{let W=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:Y0.clientId}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!W.ok){let Q=await W.text().catch(()=>""),J=w8(Q);throw new E9(`Token refresh failed: ${W.status}${J.message?` - ${J.message}`:""}`,{status:W.status,errorCode:J.code})}let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}catch(W){if(W instanceof E9)throw W;return{type:"failed"}}}async function aO($="pi"){let{verifier:W,challenge:Z}=await q9(),Q=rO(32),J=new URL(Y0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",Y0.clientId),J.searchParams.set("redirect_uri",Y0.redirectUri),J.searchParams.set("scope",Y0.scopes),J.searchParams.set("code_challenge",Z),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",Q),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:W,state:Q,url:J.toString()}}function oO(){try{let $=new URL(Y0.redirectUri),W=$.port.length>0?Number.parseInt($.port,10):Y0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(W)?W:Y0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:Y0.callbackPort,callbackPath:"/auth/callback",redirectUri:Y0.redirectUri}}}function sO($,W){let Z=W?_3(W):_3($),Q=Z?Z:_3($),j=Q?.[Y0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let X=Q?.organizations;if(Array.isArray(X)&&X.length>0){let V=X[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let Y=Q?.chatgpt_account_id;if(typeof Y==="string"&&Y.length>0)return Y;return null}function _B($,W){let Z=sO($.access,$.idToken)??W?.accountId;if(!Z)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||W?.refresh||"",expires:$.expires,accountId:Z,email:$.email??W?.email,metadata:{...W?.metadata??{},provider:"openai-codex"}}}async function O4($){x1($.telemetry,"openai-codex");let W=oO(),{verifier:Z,state:Q,url:J}=await aO($.originator),j=await H1({host:W.host,ports:[W.port],callbackPath:W.callbackPath,expectedState:Q});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let X;try{let Y=await P8({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(Y.state&&Y.state!==Q)throw Error("State mismatch");if(X=Y.code,!X){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=E8(H,{allowHashCodeState:!0});if(G.state&&G.state!==Q)throw Error("State mismatch");X=G.code}if(!X)throw Error("Missing authorization code");let V=await iO(X,Z,W.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let B=_B(V);return g1($.telemetry,"openai-codex"),v1($.telemetry,{id:B.accountId,email:B.email,provider:"openai-codex"}),B}catch(Y){throw m1($.telemetry,"openai-codex",Y instanceof Error?Y.message:String(Y)),Y}finally{j.close()}}async function w9($,W){let Z=await nO($);if(Z.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=_B(Z,W);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function z4($,W){if(!$)return null;let Z=W?.refreshBufferMs??Y0.refreshBufferMs,Q=W?.retryableTokenGraceMs??Y0.retryableTokenGraceMs;if(W?.forceRefresh!==!0&&!C8($,Z))return $;try{return await w9($.refresh,$)}catch(j){if(j instanceof E9&&j.isLikelyInvalidGrant())return _$(W?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}M0();var yB={};w(yB,{refreshOcaToken:()=>b9,loginOcaOAuth:()=>R4,getValidOcaCredentials:()=>N4,OCI_HEADER_OPC_REQUEST_ID:()=>tO,DEFAULT_INTERNAL_OCA_BASE_URL:()=>C9,DEFAULT_INTERNAL_IDCS_URL:()=>zB,DEFAULT_INTERNAL_IDCS_SCOPES:()=>qB,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>OB,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>P9,DEFAULT_EXTERNAL_IDCS_URL:()=>RB,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>NB,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>MB});import{decodeJwtPayload as q4}from"@cline/shared";import{nanoid as TB}from"nanoid";class L3{ttlMs;maxEntries;entries=new Map;constructor($,W){this.ttlMs=$;this.maxEntries=W}get($,W=Date.now()){this.pruneExpired(W);let Z=this.entries.get($);if(!Z)return;return this.entries.delete($),this.entries.set($,Z),Z.value}set($,W,Z=Date.now(),Q=this.ttlMs){this.pruneExpired(Z),this.entries.delete($);while(this.entries.size>=this.maxEntries){let J=this.entries.keys().next().value;if(J===void 0)break;this.entries.delete(J)}this.entries.set($,{value:W,expiresAt:Z+Q})}pruneExpired($){for(let[W,Z]of this.entries)if(Z.expiresAt<=$)this.entries.delete(W)}}var OB="a8331954c0cf48ba99b5dd223a14c6ea",zB="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",qB="openid offline_access",C9="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",MB="c1aba3deed5740659981a752714eba33",RB="https://login-ext.identity.oraclecloud.com",NB="openid offline_access",P9="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",tO="opc-request-id",eO="/auth/oca",$z=Array.from({length:11},($,W)=>48801+W),Wz=300000,Zz=30000,EB=30000,Qz=600000;class S9 extends Error{status;errorCode;constructor($,W){super($);this.name="OcaOAuthTokenError",this.status=W?.status,this.errorCode=W?.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 z$={internal:{clientId:OB,idcsUrl:zB,scopes:qB,baseUrl:C9},external:{clientId:MB,idcsUrl:RB,scopes:NB,baseUrl:P9}},M4=new Map,Jz=86400000,jz=300000,Xz=32,T3=new L3(Jz,Xz);function wB($){if(typeof $==="function")return $();return $??"internal"}function CB($){return{internal:{clientId:$?.internal?.clientId??z$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??z$.internal.idcsUrl,scopes:$?.internal?.scopes??z$.internal.scopes,baseUrl:$?.internal?.baseUrl??z$.internal.baseUrl},external:{clientId:$?.external?.clientId??z$.external.clientId,idcsUrl:$?.external?.idcsUrl??z$.external.idcsUrl,scopes:$?.external?.scopes??z$.external.scopes,baseUrl:$?.external?.baseUrl??z$.external.baseUrl}}}function Yz($=Date.now()){let W=$-Qz;for(let[Z,Q]of M4.entries())if(Q.createdAt<W)M4.delete(Z)}function Vz($,W,Z){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=q4(W)?.exp;if(typeof J==="number"&&J>0)return J*1000;let X=q4(Z)?.exp;if(typeof X==="number"&&X>0)return X*1000;return Date.now()+3600000}function PB($,W,Z){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let J=$.refresh_token??Z?.refresh;if(!J)throw Error("Token response did not include a refresh token");let j=q4($.id_token),X=q4(Q),Y=j?.sub??X?.sub,V=j?.email??X?.email;return{access:Q,refresh:J,expires:Vz($,Q,$.id_token),accountId:Y??Z?.accountId,email:V??Z?.email,metadata:{...Z?.metadata??{},provider:"oca",mode:W,subject:Y,idToken:$.id_token}}}async function SB($,W){let Z=M9($),Q=T3.get(Z);if(Q)return Q;let J=`${Z}/.well-known/openid-configuration`,j=await fetch(J,{method:"GET",signal:AbortSignal.timeout(W)});if(!j.ok){let V=`${Z}/oauth2/v1/token`;return T3.set(Z,V,Date.now(),jz),V}let Y=(await j.json()).token_endpoint||`${Z}/oauth2/v1/token`;return T3.set(Z,Y),Y}function bB($){return{code:$.error,message:$.error_description}}async function Bz($){let W=M4.get($.state);if(!W)throw Error("No PKCE verifier found for this state");M4.delete($.state);let Z=$.mode==="external"?$.config.external:$.config.internal,Q=await SB(Z.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:W.redirectUri,client_id:Z.clientId,code_verifier:W.verifier}),j=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),X=await j.json();if(!j.ok){let V=bB(X);throw new S9(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let Y=q4(X.id_token);if(!X.id_token||!Y)throw Error("No ID token received from OCA");if(Y.nonce!==W.nonce)throw Error("OIDC nonce verification failed");return PB(X,$.mode)}function Hz($){let W=$.mode==="external"?$.config.external:$.config.internal,Z=new URL(`${M9(W.idcsUrl)}/oauth2/v1/authorize`);return Z.searchParams.set("client_id",W.clientId),Z.searchParams.set("response_type","code"),Z.searchParams.set("scope",W.scopes),Z.searchParams.set("code_challenge",$.challenge),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("redirect_uri",$.callbackUrl),Z.searchParams.set("state",$.state),Z.searchParams.set("nonce",$.nonce),Z.toString()}async function R4($){x1($.telemetry,"oca");let W=CB($.config),Z=wB($.mode),Q=$.callbackPorts?.length?$.callbackPorts:$z,J=$.callbackPath??eO,j=$.requestTimeoutMs??EB,X=await H1({ports:Q,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Y=X.callbackUrl;if(!Y)throw Error("Unable to bind local OAuth callback server");let V=TB(16),B=TB(16),{verifier:H,challenge:G}=await q9();Yz(),M4.set(V,{verifier:H,nonce:B,mode:Z,redirectUri:Y,createdAt:Date.now()});let K=Hz({callbackUrl:Y,mode:Z,state:V,nonce:B,challenge:G,config:W});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await P8({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,f=F.state;if(F.error)throw Error(`OAuth error: ${F.error}`);if(!A){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!f||f!==V)throw Error("State mismatch");let U=await Bz({code:A,state:f,mode:Z,config:W,requestTimeoutMs:j});return g1($.telemetry,"oca"),v1($.telemetry,{id:U.accountId,email:U.email,provider:"oca"}),U}catch(F){throw m1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{X.close()}}async function b9($,W={}){let Z=CB(W.config),Q=W.requestTimeoutMs??EB,J=$.metadata?.mode,j=J==="internal"||J==="external"?J:wB(W.mode),X=j==="external"?Z.external:Z.internal,Y=await SB(X.idcsUrl,Q),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:X.clientId}),B=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(Q)}),H=await B.json();if(!B.ok){let G=bB(H);throw new S9(`Token refresh failed: ${B.status}${G.message?` - ${G.message}`:""}`,{status:B.status,errorCode:G.code})}return PB(H,j,$)}async function N4($,W,Z){if(!$)return null;let Q=W?.refreshBufferMs??Z?.refreshBufferMs??Wz,J=W?.retryableTokenGraceMs??Z?.retryableTokenGraceMs??Zz;if(W?.forceRefresh!==!0&&!C8($,Q))return $;try{return await b9($,Z)}catch(X){if(X instanceof S9&&X.isLikelyInvalidGrant())return _$(Z?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}var y9="workos:";function Kz($){let W=$.trim();return W.toLowerCase().startsWith(y9)?W:`${y9}${W}`}function Fz($){let W=$.trim();return W.toLowerCase().startsWith(y9)?W.slice(y9.length):W}function Az($){let Z=Gz($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return null}function Uz($,W){let Z=$.auth?.expiresAt;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>0)return Z;let Q=Az(W);if(Q)return Q;return Date.now()-1}function fz($,W){let Z=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!Z||!Q)return null;let J=W?.normalizeAccessToken?.(Z)??Z;if(!J)return null;return{access:J,refresh:Q,expires:Uz($,J),accountId:$.auth?.accountId,metadata:$.auth?.metadata}}function Dz($){let W=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Z={...$.settings?.auth??{},accessToken:W,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q=Object.fromEntries(Object.entries($.credentials.metadata??{}).filter(([,X])=>X!==void 0)),J={...$.settings?.auth?.metadata??{},...Q};if(Object.keys(J).length>0)Z.metadata=J;let j={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Z};if($.save!==!1)$.manager.saveProviderSettings(j,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return j}function O3($){let W=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:W,getApiKey(Z){let Q=Z?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Z){return Dz({...Z,storageProviderId:W,formatAccessToken:$.formatAccessToken})},isConfigured(Z){return!!Z?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function kB($){return O3({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:Kz,normalizeStoredAccessToken:Fz,login:({settings:W,callbacks:Z,telemetry:Q})=>L4({apiBaseUrl:W?.baseUrl?.trim()||hB().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q}),refresh:({settings:W,credentials:Z,forceRefresh:Q,telemetry:J})=>T4(Z,{apiBaseUrl:W.baseUrl?.trim()||hB().apiBaseUrl,telemetry:J},{forceRefresh:Q})})}var _z=[kB({providerId:"cline"}),kB({providerId:"cline-pass",storageProviderId:"cline"}),O3({providerId:"oca",login:({settings:$,callbacks:W,telemetry:Z})=>R4({mode:$?.oca?.mode,callbacks:W,telemetry:Z}),refresh:({settings:$,credentials:W,forceRefresh:Z,telemetry:Q})=>N4(W,{forceRefresh:Z,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),O3({providerId:"openai-codex",login:({callbacks:$,telemetry:W})=>O4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:W}),refresh:({credentials:$,forceRefresh:W,telemetry:Z})=>z4($,{forceRefresh:W,telemetry:Z})})],Lz=new Map(_z.map(($)=>[$.providerId,$]));function H0($){return Lz.get($.trim().toLowerCase())}function G2($){return H0($)!==void 0}function z3($){return H0($)?.storageProviderId}function q3($,W){let Z=H0(W),Q=Z?.storageProviderId??W,J=$.getProviderSettings(Q);return Z?.getApiKey(J)??b8(W,J)}async function E4($,W,Z){let Q=H0(W);if(!Q)throw Error(`Provider "${W}" does not support OAuth login`);let J=$.getProviderSettings(Q.storageProviderId),j=await Q.login({settings:J,callbacks:Z.callbacks,telemetry:Z.telemetry});return Q.saveCredentials({manager:$,settings:J,credentials:j})}function w4($,W){let Z=H0($);if(!Z)return null;return fz(W,{normalizeAccessToken:Z.normalizeStoredAccessToken})}function K2($){let W=H0($.providerId);if(!W)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return W.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function b8($,W){let Z=H0($);if(Z)return Z.getApiKey(W);return W?.auth?.accessToken?.trim()||W?.apiKey?.trim()||W?.auth?.apiKey?.trim()||void 0}function M3($,W){let Z=H0($);if(!Z)return W.access;return Z.getApiKey({provider:Z.storageProviderId,auth:{accessToken:W.access}})??W.access}M0();var OH={};w(OH,{createContextCompactionPrepareTurn:()=>x4,createCompactionStateAwarePrepareTurn:()=>g4});import{estimateRequestInputTokens as Qq}from"@cline/shared";var uB={};w(uB,{projectSessionCompactionState:()=>F2,parseSessionCompactionState:()=>G1,createSessionCompactionState:()=>y8,SessionCompactionStateSchema:()=>C4});import{createHash as Tz}from"node:crypto";import{formatDisplayUserInput as xB}from"@cline/shared";import{z as M1}from"zod";function Oz($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let W=$;if(W.role!=="user"&&W.role!=="assistant")return!1;return typeof W.content==="string"||Array.isArray(W.content)}var zz=M1.custom(Oz),C4=M1.object({version:M1.literal(1),updated_at:M1.string().datetime(),conversation_id:M1.string().min(1).optional(),source_message_count:M1.number().int().nonnegative(),source_prefix_hash:M1.string().min(1).optional(),source_last_message_key:M1.string().min(1).optional(),messages:M1.array(zz),system_prompt:M1.string().optional()});function R3($){return JSON.parse(JSON.stringify($))}function gB($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:xB($.content)};return{...$,content:$.content.map((W)=>W.type==="text"?{...W,text:xB(W.text)}:W)}}function mB($){if($.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function qz($){let W=gB($);return mB(W.role),[["role",W.role],["content",W.content],["id",W.id??null],["agent",W.agent??null],["sessionId",W.sessionId??null],["metadata",W.metadata??null],["modelInfo",W.modelInfo??null],["metrics",W.metrics??null],["ts",W.ts??null]]}function vB($){if(!$)return"";let W=gB($);if(typeof W.id==="string"&&W.id.trim())return`id:${W.id.trim()}`;if(mB(W.role),typeof W.ts==="number"&&Number.isFinite(W.ts))return`ts:${W.role}:${W.ts}`;return`content:${W.role}:${JSON.stringify(W.content)}`}function cB($,W=$.length){let Z=Tz("sha256");Z.update(`cline-session-compaction-source-v1
319
+ </html>`;function LB($){let W="";for(let Z=0;Z<$.length;Z+=1)W+=String.fromCharCode($[Z]??0);return btoa(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function lO($){let Z=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",Z);return new Uint8Array(Q)}function pO($=32){let W=new Uint8Array($);return crypto.getRandomValues(W),LB(W)}async function SW(){let $=pO(),W=LB(await lO($));return{verifier:$,challenge:W}}function bW($){return $.endsWith("/")?$.slice(0,-1):$}function G2($,W){return new URL(W,`${bW($)}/`).toString()}function C8($,W={}){let Z=$.trim();if(!Z)return{};try{let Q=new URL(Z);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:W.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(W.allowHashCodeState&&Z.includes("#")){let[Q,J]=Z.split("#",2);return{code:Q||void 0,state:J||void 0}}if(Z.includes("code=")){let Q=new URLSearchParams(Z);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:W.includeProvider?Q.get("provider")??void 0:void 0}}return{code:Z}}function P8($){try{let W=JSON.parse($),Z=W.error,Q=typeof Z==="string"?Z:Z&&typeof Z==="object"&&typeof Z.type==="string"?Z.type:void 0,J=typeof W.error_description==="string"?W.error_description:typeof W.message==="string"?W.message:Z&&typeof Z==="object"&&typeof Z.message==="string"?Z.message:void 0;return{code:Q,message:J}}catch{return{}}}function S8($,W){return Date.now()>=$.expires-W}async function b8($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let W,Z,Q=$.onManualCodeInput().then((j)=>{W=j,$.cancelWait()}).catch((j)=>{Z=j instanceof Error?j:Error(String(j)),$.cancelWait()}),J=await $.waitForCallback();if(Z)throw Z;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(W)return C8(W,$.parseOptions);if(await Q,Z)throw Z;if(W)return C8(W,$.parseOptions);return{}}var yW={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},qB={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},_3="https://api.workos.com",rO="/auth",TB=Array.from({length:11},($,W)=>48801+W),iO=300000,nO=30000,y8=30000,aO=300,oO=5;class q1 extends Error{status;errorCode;constructor($,W){super($);this.name="ClineOAuthTokenError",this.status=W?.status,this.errorCode=W?.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 sO($){let W=Date.parse($);if(Number.isNaN(W))throw Error(`Invalid expiresAt value: ${$}`);return W}function f3($,W,Z={}){let Q=$.userInfo.clineUserId??Z.accountId,J=$.refreshToken??Z.refresh;if(!J)throw Error("Token response did not include a refresh token");let j={...Z.metadata??{},provider:W,tokenType:$.tokenType,userInfo:$.userInfo};return delete j.startedAt,{access:$.accessToken,refresh:J,expires:sO($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||Z.email,metadata:j}}async function L3($){if(!$)return{};return typeof $==="function"?await $():$}function OB($,W){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return W;return Math.floor($)}async function zB($){await new Promise((W)=>setTimeout(W,$))}function T3($,W){if(!$.success||!$.data?.accessToken)throw Error(W);return $.data}async function MB($,W){let Z=await fetch(G2(_3,qB.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(W?.requestTimeoutMs??y8)}),Q=await Z.json().catch(()=>({}));if(!Z.ok)throw new q1(`Device authorization failed: ${Z.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:Z.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:OB(Q.expires_in,aO),pollIntervalSeconds:OB(Q.interval,oO)}}async function RB($){let W=Date.now()+$.expiresInSeconds*1000,Z=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=W){let Q=await fetch(G2($.workosApiBaseUrl,qB.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)}),J=await Q.json().catch(()=>({}));if(Q.ok){if(!J.access_token||!J.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:J.access_token,refreshToken:J.refresh_token,tokenType:J.token_type??"Bearer"}}switch(J.error){case"authorization_pending":{await zB(Z*1000);break}case"slow_down":{Z+=1,await zB(Z*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new q1(J.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:J.error});default:throw new q1(`WorkOS token polling failed: ${Q.status}${J.error_description?` - ${J.error_description}`:""}`,{status:Q.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function EB($,W,Z){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(G2(W.apiBaseUrl,yW.register),{method:"POST",headers:{"Content-Type":"application/json",...await L3(W.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(W.requestTimeoutMs??y8)});if(!J.ok){let X=await J.text().catch(()=>""),Y=P8(X);throw new q1(`Token registration failed: ${J.status}${Y.message?` - ${Y.message}`:""}`,{status:J.status,errorCode:Y.code})}let j=await J.json();return f3(T3(j,"Invalid token exchange response"),Z??W.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function tO($,W,Z,Q){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:W,provider:Q??Z.provider},j=await fetch(G2(Z.apiBaseUrl,yW.token),{method:"POST",headers:{"Content-Type":"application/json",...await L3(Z.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Z.requestTimeoutMs??y8)});if(!j.ok){let Y=await j.text().catch(()=>""),V=P8(Y);throw new q1(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let X=await j.json();return f3(T3(X,"Invalid token exchange response"),Q??Z.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function O4($){g1($.telemetry,$.provider??"cline");let W=$.useWorkOSDeviceAuth??!0,Z=$.callbackPorts?.length?$.callbackPorts:TB,Q=$.callbackPath??rO,J=W?null:await H1({ports:Z,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=J?.callbackUrl||`http://127.0.0.1:${Z[0]??TB[0]}${Q}`;try{let X;if(W){let Y=D3().workOsClientId,V=await MB(Y,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let B=await RB({clientId:Y,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??y8,workosApiBaseUrl:_3,onProgress:$.callbacks.onProgress});X=await EB(B,$,$.provider)}else{let Y=new URL(G2($.apiBaseUrl,yW.authorize));Y.searchParams.set("client_type","extension"),Y.searchParams.set("callback_url",j),Y.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:Y.toString(),instructions:"Continue the authentication process in your browser."});let V,B=$.provider,H=await b8({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(V=H.code,B=H.provider??B,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=C8(G,{includeProvider:!0});V=K.code,B=K.provider??B}if(!V)throw Error("Missing authorization code");X=await tO(V,j,$,B)}return m1($.telemetry,$.provider??"cline"),c1($.telemetry,{id:X.accountId,email:X.email,provider:$.provider??"cline"}),X}catch(X){throw v1($.telemetry,$.provider??"cline",X instanceof Error?X.message:String(X)),X}finally{J?.close()}}async function O3($){return await MB(D3().workOsClientId,$)}async function z3($){let W=$.provider??"cline";g1($.telemetry,W);try{let Z=await RB({clientId:D3().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??y8,workosApiBaseUrl:_3}),Q=await EB(Z,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return m1($.telemetry,W),c1($.telemetry,{id:Q.accountId,email:Q.email,provider:W}),Q}catch(Z){throw v1($.telemetry,W,Z instanceof Error?Z.message:String(Z)),Z}}async function hW($,W){let Z=G2(W.apiBaseUrl,yW.refresh);s(`cline.refresh.request url=${Z} refreshTokenHash=${N0($.refresh)}`);let Q=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/json",...await L3(W.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(W.requestTimeoutMs??y8)});if(!Q.ok){let Y=await Q.text().catch(()=>""),V=P8(Y);throw s(`cline.refresh.error status=${Q.status} errorCode=${V.code??"none"} message=${V.message??"none"}`),new q1(`Token refresh failed: ${Q.status}${V.message?` - ${V.message}`:""}`,{status:Q.status,errorCode:V.code})}let J=await Q.json(),j=$.metadata?.provider??W.provider,X=f3(T3(J,"Invalid token refresh response"),j,$);return s(`cline.refresh.success newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} expires=${X.expires}`),X}async function z4($,W,Z){if(!$)return s("cline.getCredentials outcome=no_current_credentials"),null;let Q=Z?.refreshBufferMs??iO,J=Z?.retryableTokenGraceMs??nO,j=Z?.forceRefresh===!0;if(!j&&!S8($,Q))return s(`cline.getCredentials outcome=still_valid forceRefresh=${j}`),$;s(`cline.getCredentials outcome=needs_refresh forceRefresh=${j} accessTokenHash=${N0($.access)}`);try{return await hW($,W)}catch(X){let Y={status:X instanceof q1?X.status:void 0,errorCode:X instanceof q1?X.errorCode:void 0,errorName:X instanceof Error?X.name:void 0};if(X instanceof q1&&X.isLikelyInvalidGrant())return s(`cline.getCredentials outcome=invalid_grant status=${X.status} errorCode=${X.errorCode??"none"}`),L$(W.telemetry,W.provider??"cline","invalid_grant",{status:X.status,errorCode:X.errorCode}),null;if($.expires-Date.now()>J)return s(`cline.getCredentials outcome=transient_failure_kept_current error=${X instanceof Error?X.message:String(X)}`),d7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!1}),$;throw s(`cline.getCredentials outcome=transient_failure_rethrown error=${X instanceof Error?X.message:String(X)}`),d7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!0}),X}}R0();var CB={};w(CB,{refreshOpenAICodexToken:()=>IW,loginOpenAICodex:()=>q4,getValidOpenAICodexCredentials:()=>M4,OPENAI_CODEX_OAUTH_CONFIG:()=>Y0});import{decodeJwtPayload as q3}from"@cline/shared";import{nanoid as eO}from"nanoid";var Y0={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 kW extends Error{status;errorCode;constructor($,W){super($);this.name="OpenAICodexOAuthTokenError",this.status=W?.status,this.errorCode=W?.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 $z($,W,Z=Y0.redirectUri){let Q=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:Y0.clientId,code:$,code_verifier:W,redirect_uri:Z}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let J=await Q.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}async function Wz($){try{let W=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:Y0.clientId}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!W.ok){let Q=await W.text().catch(()=>""),J=P8(Q);throw new kW(`Token refresh failed: ${W.status}${J.message?` - ${J.message}`:""}`,{status:W.status,errorCode:J.code})}let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}catch(W){if(W instanceof kW)throw W;return{type:"failed"}}}async function Zz($="pi"){let{verifier:W,challenge:Z}=await SW(),Q=eO(32),J=new URL(Y0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",Y0.clientId),J.searchParams.set("redirect_uri",Y0.redirectUri),J.searchParams.set("scope",Y0.scopes),J.searchParams.set("code_challenge",Z),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",Q),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:W,state:Q,url:J.toString()}}function Qz(){try{let $=new URL(Y0.redirectUri),W=$.port.length>0?Number.parseInt($.port,10):Y0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(W)?W:Y0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:Y0.callbackPort,callbackPath:"/auth/callback",redirectUri:Y0.redirectUri}}}function Jz($,W){let Z=W?q3(W):q3($),Q=Z?Z:q3($),j=Q?.[Y0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let X=Q?.organizations;if(Array.isArray(X)&&X.length>0){let V=X[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let Y=Q?.chatgpt_account_id;if(typeof Y==="string"&&Y.length>0)return Y;return null}function wB($,W){let Z=Jz($.access,$.idToken)??W?.accountId;if(!Z)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||W?.refresh||"",expires:$.expires,accountId:Z,email:$.email??W?.email,metadata:{...W?.metadata??{},provider:"openai-codex"}}}async function q4($){g1($.telemetry,"openai-codex");let W=Qz(),{verifier:Z,state:Q,url:J}=await Zz($.originator),j=await H1({host:W.host,ports:[W.port],callbackPath:W.callbackPath,expectedState:Q});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let X;try{let Y=await b8({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(Y.state&&Y.state!==Q)throw Error("State mismatch");if(X=Y.code,!X){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=C8(H,{allowHashCodeState:!0});if(G.state&&G.state!==Q)throw Error("State mismatch");X=G.code}if(!X)throw Error("Missing authorization code");let V=await $z(X,Z,W.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let B=wB(V);return m1($.telemetry,"openai-codex"),c1($.telemetry,{id:B.accountId,email:B.email,provider:"openai-codex"}),B}catch(Y){throw v1($.telemetry,"openai-codex",Y instanceof Error?Y.message:String(Y)),Y}finally{j.close()}}async function IW($,W){let Z=await Wz($);if(Z.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=wB(Z,W);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function M4($,W){if(!$)return null;let Z=W?.refreshBufferMs??Y0.refreshBufferMs,Q=W?.retryableTokenGraceMs??Y0.retryableTokenGraceMs;if(W?.forceRefresh!==!0&&!S8($,Z))return $;try{return await IW($.refresh,$)}catch(j){if(j instanceof kW&&j.isLikelyInvalidGrant())return L$(W?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}R0();var dB={};w(dB,{refreshOcaToken:()=>vW,loginOcaOAuth:()=>N4,getValidOcaCredentials:()=>w4,OCI_HEADER_OPC_REQUEST_ID:()=>jz,DEFAULT_INTERNAL_OCA_BASE_URL:()=>xW,DEFAULT_INTERNAL_IDCS_URL:()=>bB,DEFAULT_INTERNAL_IDCS_SCOPES:()=>yB,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>SB,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>gW,DEFAULT_EXTERNAL_IDCS_URL:()=>kB,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>IB,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>hB});import{decodeJwtPayload as R4}from"@cline/shared";import{nanoid as PB}from"nanoid";class M3{ttlMs;maxEntries;entries=new Map;constructor($,W){this.ttlMs=$;this.maxEntries=W}get($,W=Date.now()){this.pruneExpired(W);let Z=this.entries.get($);if(!Z)return;return this.entries.delete($),this.entries.set($,Z),Z.value}set($,W,Z=Date.now(),Q=this.ttlMs){this.pruneExpired(Z),this.entries.delete($);while(this.entries.size>=this.maxEntries){let J=this.entries.keys().next().value;if(J===void 0)break;this.entries.delete(J)}this.entries.set($,{value:W,expiresAt:Z+Q})}pruneExpired($){for(let[W,Z]of this.entries)if(Z.expiresAt<=$)this.entries.delete(W)}}var SB="a8331954c0cf48ba99b5dd223a14c6ea",bB="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",yB="openid offline_access",xW="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",hB="c1aba3deed5740659981a752714eba33",kB="https://login-ext.identity.oraclecloud.com",IB="openid offline_access",gW="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",jz="opc-request-id",Xz="/auth/oca",Yz=Array.from({length:11},($,W)=>48801+W),Vz=300000,Bz=30000,xB=30000,Hz=600000;class mW extends Error{status;errorCode;constructor($,W){super($);this.name="OcaOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var q$={internal:{clientId:SB,idcsUrl:bB,scopes:yB,baseUrl:xW},external:{clientId:hB,idcsUrl:kB,scopes:IB,baseUrl:gW}},E4=new Map,Gz=86400000,Kz=300000,Fz=32,R3=new M3(Gz,Fz);function gB($){if(typeof $==="function")return $();return $??"internal"}function mB($){return{internal:{clientId:$?.internal?.clientId??q$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??q$.internal.idcsUrl,scopes:$?.internal?.scopes??q$.internal.scopes,baseUrl:$?.internal?.baseUrl??q$.internal.baseUrl},external:{clientId:$?.external?.clientId??q$.external.clientId,idcsUrl:$?.external?.idcsUrl??q$.external.idcsUrl,scopes:$?.external?.scopes??q$.external.scopes,baseUrl:$?.external?.baseUrl??q$.external.baseUrl}}}function Az($=Date.now()){let W=$-Hz;for(let[Z,Q]of E4.entries())if(Q.createdAt<W)E4.delete(Z)}function Uz($,W,Z){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=R4(W)?.exp;if(typeof J==="number"&&J>0)return J*1000;let X=R4(Z)?.exp;if(typeof X==="number"&&X>0)return X*1000;return Date.now()+3600000}function vB($,W,Z){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let J=$.refresh_token??Z?.refresh;if(!J)throw Error("Token response did not include a refresh token");let j=R4($.id_token),X=R4(Q),Y=j?.sub??X?.sub,V=j?.email??X?.email;return{access:Q,refresh:J,expires:Uz($,Q,$.id_token),accountId:Y??Z?.accountId,email:V??Z?.email,metadata:{...Z?.metadata??{},provider:"oca",mode:W,subject:Y,idToken:$.id_token}}}async function cB($,W){let Z=bW($),Q=R3.get(Z);if(Q)return Q;let J=`${Z}/.well-known/openid-configuration`,j=await fetch(J,{method:"GET",signal:AbortSignal.timeout(W)});if(!j.ok){let V=`${Z}/oauth2/v1/token`;return R3.set(Z,V,Date.now(),Kz),V}let Y=(await j.json()).token_endpoint||`${Z}/oauth2/v1/token`;return R3.set(Z,Y),Y}function uB($){return{code:$.error,message:$.error_description}}async function Dz($){let W=E4.get($.state);if(!W)throw Error("No PKCE verifier found for this state");E4.delete($.state);let Z=$.mode==="external"?$.config.external:$.config.internal,Q=await cB(Z.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:W.redirectUri,client_id:Z.clientId,code_verifier:W.verifier}),j=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),X=await j.json();if(!j.ok){let V=uB(X);throw new mW(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let Y=R4(X.id_token);if(!X.id_token||!Y)throw Error("No ID token received from OCA");if(Y.nonce!==W.nonce)throw Error("OIDC nonce verification failed");return vB(X,$.mode)}function _z($){let W=$.mode==="external"?$.config.external:$.config.internal,Z=new URL(`${bW(W.idcsUrl)}/oauth2/v1/authorize`);return Z.searchParams.set("client_id",W.clientId),Z.searchParams.set("response_type","code"),Z.searchParams.set("scope",W.scopes),Z.searchParams.set("code_challenge",$.challenge),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("redirect_uri",$.callbackUrl),Z.searchParams.set("state",$.state),Z.searchParams.set("nonce",$.nonce),Z.toString()}async function N4($){g1($.telemetry,"oca");let W=mB($.config),Z=gB($.mode),Q=$.callbackPorts?.length?$.callbackPorts:Yz,J=$.callbackPath??Xz,j=$.requestTimeoutMs??xB,X=await H1({ports:Q,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Y=X.callbackUrl;if(!Y)throw Error("Unable to bind local OAuth callback server");let V=PB(16),B=PB(16),{verifier:H,challenge:G}=await SW();Az(),E4.set(V,{verifier:H,nonce:B,mode:Z,redirectUri:Y,createdAt:Date.now()});let K=_z({callbackUrl:Y,mode:Z,state:V,nonce:B,challenge:G,config:W});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await b8({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,D=F.state;if(F.error)throw Error(`OAuth error: ${F.error}`);if(!A){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!D||D!==V)throw Error("State mismatch");let U=await Dz({code:A,state:D,mode:Z,config:W,requestTimeoutMs:j});return m1($.telemetry,"oca"),c1($.telemetry,{id:U.accountId,email:U.email,provider:"oca"}),U}catch(F){throw v1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{X.close()}}async function vW($,W={}){let Z=mB(W.config),Q=W.requestTimeoutMs??xB,J=$.metadata?.mode,j=J==="internal"||J==="external"?J:gB(W.mode),X=j==="external"?Z.external:Z.internal,Y=await cB(X.idcsUrl,Q),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:X.clientId}),B=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(Q)}),H=await B.json();if(!B.ok){let G=uB(H);throw new mW(`Token refresh failed: ${B.status}${G.message?` - ${G.message}`:""}`,{status:B.status,errorCode:G.code})}return vB(H,j,$)}async function w4($,W,Z){if(!$)return null;let Q=W?.refreshBufferMs??Z?.refreshBufferMs??Vz,J=W?.retryableTokenGraceMs??Z?.retryableTokenGraceMs??Bz;if(W?.forceRefresh!==!0&&!S8($,Q))return $;try{return await vW($,Z)}catch(X){if(X instanceof mW&&X.isLikelyInvalidGrant())return L$(Z?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}var cW="workos:";function Lz($){let W=$.trim();return W.toLowerCase().startsWith(cW)?W:`${cW}${W}`}function Tz($){let W=$.trim();return W.toLowerCase().startsWith(cW)?W.slice(cW.length):W}function Oz($){let Z=fz($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return null}function zz($,W){let Z=$.auth?.expiresAt;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>0)return Z;let Q=Oz(W);if(Q)return Q;return Date.now()-1}function qz($,W){let Z=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!Z||!Q)return null;let J=W?.normalizeAccessToken?.(Z)??Z;if(!J)return null;return{access:J,refresh:Q,expires:zz($,J),accountId:$.auth?.accountId,metadata:$.auth?.metadata}}function Mz($){let W=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Z={...$.settings?.auth??{},accessToken:W,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q=Object.fromEntries(Object.entries($.credentials.metadata??{}).filter(([,X])=>X!==void 0)),J={...$.settings?.auth?.metadata??{},...Q};if(Object.keys(J).length>0)Z.metadata=J;let j={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Z};if($.save!==!1)$.manager.saveProviderSettings(j,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return j}function E3($){let W=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:W,getApiKey(Z){let Q=Z?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Z){return Mz({...Z,storageProviderId:W,formatAccessToken:$.formatAccessToken})},isConfigured(Z){return!!Z?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function pB($){return E3({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:Lz,normalizeStoredAccessToken:Tz,login:({settings:W,callbacks:Z,telemetry:Q})=>O4({apiBaseUrl:W?.baseUrl?.trim()||lB().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q}),refresh:({settings:W,credentials:Z,forceRefresh:Q,telemetry:J})=>z4(Z,{apiBaseUrl:W.baseUrl?.trim()||lB().apiBaseUrl,telemetry:J},{forceRefresh:Q})})}var Rz=[pB({providerId:"cline"}),pB({providerId:"cline-pass",storageProviderId:"cline"}),E3({providerId:"oca",login:({settings:$,callbacks:W,telemetry:Z})=>N4({mode:$?.oca?.mode,callbacks:W,telemetry:Z}),refresh:({settings:$,credentials:W,forceRefresh:Z,telemetry:Q})=>w4(W,{forceRefresh:Z,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),E3({providerId:"openai-codex",login:({callbacks:$,telemetry:W})=>q4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:W}),refresh:({credentials:$,forceRefresh:W,telemetry:Z})=>M4($,{forceRefresh:W,telemetry:Z})})],Ez=new Map(Rz.map(($)=>[$.providerId,$]));function H0($){return Ez.get($.trim().toLowerCase())}function K2($){return H0($)!==void 0}function N3($){return H0($)?.storageProviderId}function w3($,W){let Z=H0(W),Q=Z?.storageProviderId??W,J=$.getProviderSettings(Q);return Z?.getApiKey(J)??h8(W,J)}async function C4($,W,Z){let Q=H0(W);if(!Q)throw Error(`Provider "${W}" does not support OAuth login`);let J=$.getProviderSettings(Q.storageProviderId),j=await Q.login({settings:J,callbacks:Z.callbacks,telemetry:Z.telemetry});return Q.saveCredentials({manager:$,settings:J,credentials:j})}function P4($,W){let Z=H0($);if(!Z)return null;return qz(W,{normalizeAccessToken:Z.normalizeStoredAccessToken})}function F2($){let W=H0($.providerId);if(!W)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return W.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function h8($,W){let Z=H0($);if(Z)return Z.getApiKey(W);return W?.auth?.accessToken?.trim()||W?.apiKey?.trim()||W?.auth?.apiKey?.trim()||void 0}function C3($,W){let Z=H0($);if(!Z)return W.access;return Z.getApiKey({provider:Z.storageProviderId,auth:{accessToken:W.access}})??W.access}R0();var SH={};w(SH,{createContextCompactionPrepareTurn:()=>m4,createCompactionStateAwarePrepareTurn:()=>v4});import{estimateRequestInputTokens as Hq}from"@cline/shared";var tB={};w(tB,{projectSessionCompactionState:()=>A2,parseSessionCompactionState:()=>G1,createSessionCompactionState:()=>k8,SessionCompactionStateSchema:()=>S4});import{createHash as Nz}from"node:crypto";import{formatDisplayUserInput as iB}from"@cline/shared";import{z as M1}from"zod";function wz($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let W=$;if(W.role!=="user"&&W.role!=="assistant")return!1;return typeof W.content==="string"||Array.isArray(W.content)}var Cz=M1.custom(wz),S4=M1.object({version:M1.literal(1),updated_at:M1.string().datetime(),conversation_id:M1.string().min(1).optional(),source_message_count:M1.number().int().nonnegative(),source_prefix_hash:M1.string().min(1).optional(),source_last_message_key:M1.string().min(1).optional(),messages:M1.array(Cz),system_prompt:M1.string().optional()});function P3($){return JSON.parse(JSON.stringify($))}function nB($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:iB($.content)};return{...$,content:$.content.map((W)=>W.type==="text"?{...W,text:iB(W.text)}:W)}}function aB($){if($.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function Pz($){let W=nB($);return aB(W.role),[["role",W.role],["content",W.content],["id",W.id??null],["agent",W.agent??null],["sessionId",W.sessionId??null],["metadata",W.metadata??null],["modelInfo",W.modelInfo??null],["metrics",W.metrics??null],["ts",W.ts??null]]}function oB($){if(!$)return"";let W=nB($);if(typeof W.id==="string"&&W.id.trim())return`id:${W.id.trim()}`;if(aB(W.role),typeof W.ts==="number"&&Number.isFinite(W.ts))return`ts:${W.role}:${W.ts}`;return`content:${W.role}:${JSON.stringify(W.content)}`}function sB($,W=$.length){let Z=Nz("sha256");Z.update(`cline-session-compaction-source-v1
320
320
  `),Z.update(`${W}
321
- `);for(let Q of $.slice(0,W))Z.update(JSON.stringify(qz(Q))),Z.update(`
322
- `);return`sha256:${Z.digest("hex")}`}function y8($){let W=$.sourceMessages.at(-1),Z=vB(W);return C4.parse({version:1,updated_at:$.updatedAt??new Date().toISOString(),...$.conversationId?.trim()?{conversation_id:$.conversationId.trim()}:{},source_message_count:$.sourceMessages.length,source_prefix_hash:cB($.sourceMessages),...Z?{source_last_message_key:Z}:{},messages:R3($.compactedMessages),...$.systemPrompt!==void 0?{system_prompt:$.systemPrompt}:{}})}function F2($,W){if(!($.source_message_count<=W.length))return;let Q=!!$.source_prefix_hash&&cB(W,$.source_message_count)===$.source_prefix_hash,J=W[$.source_message_count-1],j=!$.source_prefix_hash&&$.source_message_count>0&&!!$.source_last_message_key&&vB(J)===$.source_last_message_key;if(!(Q||j))return;return[...R3($.messages),...R3(W.slice($.source_message_count))]}function G1($){let W=C4.safeParse($);return W.success?W.data:void 0}import{createHandlerAsync as dz}from"@cline/llms";function Mz($){switch($){case"agentic_summary":case"basic_compaction_projection":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!0,dropThinkingBlocks:!0};case"normal_provider_request":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!1,dropThinkingBlocks:!1}}}function dB($){return $.map((W)=>({...W,content:Array.isArray(W.content)?W.content.map((Z)=>({...Z})):W.content,...W.metadata?{metadata:{...W.metadata}}:{}}))}function R1($){try{return JSON.stringify($).length}catch{return String($).length}}function h9($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function iB($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function k9($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z.role==="user"&&!iB(Z))return W}return-1}function Rz($){for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z.role==="user"&&!iB(Z))return W}return-1}function E3($){let W=new Set;if(!Array.isArray($.content))return W;for(let Z of $.content)if(Z.type==="tool_use")W.add(Z.id);else if(Z.type==="tool_result")W.add(Z.tool_use_id);return W}function Nz($){let W=new Map;for(let Z=0;Z<$.length;Z+=1)for(let Q of E3($[Z])){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function N3($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(!Array.isArray(Q.content))continue;if(Q.content.some((J)=>J.type==="tool_use"&&!W.has(J.id)))return Z}return $.length}function Ez($,W){let Z=Nz($),Q=new Set,J=[W];while(J.length>0){let j=J.shift();if(j===void 0||Q.has(j))continue;Q.add(j);for(let X of E3($[j]))for(let Y of Z.get(X)??[])if(!Q.has(Y))J.push(Y)}return Q}function wz($){return $.type==="image"||$.type==="redacted_thinking"}function Cz($){return $.type==="image"}function Pz($,W,Z){if(W.dropThinkingBlocks&&$.type==="thinking")return!0;return W.dropUnsafeOutsideLiveTail&&!Z&&wz($)}function lB($,W,Z,Q="over_budget"){let J=[],j=[];for(let X=0;X<$.length;X+=1){let Y=$[X];if(Array.isArray(Y.content)&&Y.content.length===0){Z.push({kind:"dropped_message",path:{messageIndex:W[X]},reason:Q,originalSize:R1(Y),finalSize:0});continue}J.push(Y),j.push(W[X])}return{messages:J,originalIndexes:j}}function Sz($,W,Z,Q,J,j){return $.map((X,Y)=>{if(!Array.isArray(X.content))return X;let V=!1,B=Y===Q||Y>=J,H=X.content.flatMap((G,K)=>{if(Pz(G,j,B))return V=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:0}),[];if(G.type==="tool_result"&&Array.isArray(G.content)){let F=G.content.filter((A)=>{if(j.dropUnsafeOutsideLiveTail&&!B&&Cz(A))return!1;return!0});if(F.length!==G.content.length){V=!0;let A={...G,content:F};return Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:R1(A)}),[A]}}return[G]});return V?{...X,content:H}:X})}function bz($,W,Z){return $.map((Q,J)=>{if(!Array.isArray(Q.content))return Q;let j=!1,X=Q.content.filter((Y,V)=>{if(Y.type!=="thinking")return!0;return j=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[J],blockIndex:V},reason:"unsafe_to_truncate",originalSize:R1(Y),finalSize:0}),!1});return j?{...Q,content:X}:Q})}function h8($,W){if(W<=0)return"";if($.length<=W)return $;if(W<=16)return $.slice(0,Math.max(1,W));let Z=`
321
+ `);for(let Q of $.slice(0,W))Z.update(JSON.stringify(Pz(Q))),Z.update(`
322
+ `);return`sha256:${Z.digest("hex")}`}function k8($){let W=$.sourceMessages.at(-1),Z=oB(W);return S4.parse({version:1,updated_at:$.updatedAt??new Date().toISOString(),...$.conversationId?.trim()?{conversation_id:$.conversationId.trim()}:{},source_message_count:$.sourceMessages.length,source_prefix_hash:sB($.sourceMessages),...Z?{source_last_message_key:Z}:{},messages:P3($.compactedMessages),...$.systemPrompt!==void 0?{system_prompt:$.systemPrompt}:{}})}function A2($,W){if(!($.source_message_count<=W.length))return;let Q=!!$.source_prefix_hash&&sB(W,$.source_message_count)===$.source_prefix_hash,J=W[$.source_message_count-1],j=!$.source_prefix_hash&&$.source_message_count>0&&!!$.source_last_message_key&&oB(J)===$.source_last_message_key;if(!(Q||j))return;return[...P3($.messages),...P3(W.slice($.source_message_count))]}function G1($){let W=S4.safeParse($);return W.success?W.data:void 0}import{createHandlerAsync as oz}from"@cline/llms";function Sz($){switch($){case"agentic_summary":case"basic_compaction_projection":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!0,dropThinkingBlocks:!0};case"normal_provider_request":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!1,dropThinkingBlocks:!1}}}function eB($){return $.map((W)=>({...W,content:Array.isArray(W.content)?W.content.map((Z)=>({...Z})):W.content,...W.metadata?{metadata:{...W.metadata}}:{}}))}function R1($){try{return JSON.stringify($).length}catch{return String($).length}}function uW($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function QH($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function dW($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z.role==="user"&&!QH(Z))return W}return-1}function bz($){for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z.role==="user"&&!QH(Z))return W}return-1}function b3($){let W=new Set;if(!Array.isArray($.content))return W;for(let Z of $.content)if(Z.type==="tool_use")W.add(Z.id);else if(Z.type==="tool_result")W.add(Z.tool_use_id);return W}function yz($){let W=new Map;for(let Z=0;Z<$.length;Z+=1)for(let Q of b3($[Z])){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function S3($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(!Array.isArray(Q.content))continue;if(Q.content.some((J)=>J.type==="tool_use"&&!W.has(J.id)))return Z}return $.length}function hz($,W){let Z=yz($),Q=new Set,J=[W];while(J.length>0){let j=J.shift();if(j===void 0||Q.has(j))continue;Q.add(j);for(let X of b3($[j]))for(let Y of Z.get(X)??[])if(!Q.has(Y))J.push(Y)}return Q}function kz($){return $.type==="image"||$.type==="redacted_thinking"}function Iz($){return $.type==="image"}function xz($,W,Z){if(W.dropThinkingBlocks&&$.type==="thinking")return!0;return W.dropUnsafeOutsideLiveTail&&!Z&&kz($)}function $H($,W,Z,Q="over_budget"){let J=[],j=[];for(let X=0;X<$.length;X+=1){let Y=$[X];if(Array.isArray(Y.content)&&Y.content.length===0){Z.push({kind:"dropped_message",path:{messageIndex:W[X]},reason:Q,originalSize:R1(Y),finalSize:0});continue}J.push(Y),j.push(W[X])}return{messages:J,originalIndexes:j}}function gz($,W,Z,Q,J,j){return $.map((X,Y)=>{if(!Array.isArray(X.content))return X;let V=!1,B=Y===Q||Y>=J,H=X.content.flatMap((G,K)=>{if(xz(G,j,B))return V=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:0}),[];if(G.type==="tool_result"&&Array.isArray(G.content)){let F=G.content.filter((A)=>{if(j.dropUnsafeOutsideLiveTail&&!B&&Iz(A))return!1;return!0});if(F.length!==G.content.length){V=!0;let A={...G,content:F};return Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:R1(A)}),[A]}}return[G]});return V?{...X,content:H}:X})}function mz($,W,Z){return $.map((Q,J)=>{if(!Array.isArray(Q.content))return Q;let j=!1,X=Q.content.filter((Y,V)=>{if(Y.type!=="thinking")return!0;return j=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[J],blockIndex:V},reason:"unsafe_to_truncate",originalSize:R1(Y),finalSize:0}),!1});return j?{...Q,content:X}:Q})}function I8($,W){if(W<=0)return"";if($.length<=W)return $;if(W<=16)return $.slice(0,Math.max(1,W));let Z=`
323
323
  ...[truncated ${$.length-W} chars]`,Q=Math.max(1,W-Z.length),J=`
324
- ...[truncated ${$.length-Q} chars]`;return`${$.slice(0,Q)}${J}`}function pB($,W){if(typeof $==="string")return h8($,W);let Z=W;return $.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};return Q}if(Q.type==="text"){let J=h8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=h8(Q.content,Z);return Z-=J.length,{...Q,content:J}}return Q})}function yz($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;if(Z.type==="file")return W+Z.content.length;return W},0)}function hz($,W){if(typeof $.content==="string")return{...$,content:h8($.content,W)};let Z=W;return{...$,content:$.content.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};if(Q.type==="tool_result")return{...Q,content:pB(Q.content,0)};return Q}if(Q.type==="text"){let J=h8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=h8(Q.content,Z);return Z-=J.length,{...Q,content:J}}if(Q.type==="tool_result"){let J=pB(Q.content,Z);return Z-=yz(J),{...Q,content:J}}return Q})}}function kz($){if(typeof $.content==="string")return $.content.length>0;return $.content.some((W)=>W.type==="text"||W.type==="file"||W.type==="tool_result")}function Iz($,W,Z){return{messages:$.filter((Q,J)=>!Z.has(J)),originalIndexes:W.filter((Q,J)=>!Z.has(J))}}function xz($,W){if(W<0)return!1;for(let Z of $)if(Z>=W)return!0;return!1}function rB($,W){return W>=0&&$.has(W)}function P4($){let W=[],Z=[],Q=Mz($.policyIntent);if($.targetTokens<=0)return{status:"failed",messages:dB($.messages),actions:W,liveTailHandling:"preserved_out_of_band",estimatedTokens:h9($.messages,$.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let J=dB($.messages),j=J.map((B,H)=>H);if(Q.dropThinkingBlocks){let B=lB(bz(J,j,W),j,W,"unsafe_to_truncate");J=B.messages,j=B.originalIndexes}let X=Q.protectLatestTypedUser?k9(J):-1,Y=Q.protectLiveTailFromDrop?N3(J):J.length;if(Q.dropUnsafeOutsideLiveTail){let B=lB(Sz(J,j,W,X,Y,Q),j,W);J=B.messages,j=B.originalIndexes}let V=h9(J,$.estimateMessageTokens);if(V<=$.targetTokens)return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z};for(let B=J.length-1;B>=0&&V>$.targetTokens;B-=1){let H=k9(J);if(B===H)continue;if(Q.protectLiveTailFromDrop&&B>=N3(J))continue;if(!kz(J[B]))continue;let G=R1(J[B]),K=Math.max(1,G/Math.max(1,$.estimateMessageTokens(J[B]))),F=Math.max(16,Math.floor($.targetTokens*K/Math.max(1,J.length)));J[B]=hz(J[B],F),W.push({kind:"truncated_text",path:{messageIndex:j[B]},reason:"over_budget",originalSize:G,finalSize:R1(J[B])}),V=h9(J,$.estimateMessageTokens)}for(let B=0;B<J.length&&V>$.targetTokens;){let H=Rz(J),G=k9(J),K=Q.protectLiveTailFromDrop?N3(J):J.length;if(B===H||B===G){W.push({kind:"preserved",path:{messageIndex:j[B]},reason:"protected_live_tail",originalSize:R1(J[B]),finalSize:R1(J[B])}),B+=1;continue}let F=Ez(J,B);if(rB(F,H)){B+=1;continue}if(rB(F,G)){B+=1;continue}if(xz(F,K)){B+=1;continue}for(let f of F)W.push({kind:"dropped_message",path:{messageIndex:j[f]},reason:F.size>1||E3(J[f]).size>0?"tool_pair_boundary":"over_budget",originalSize:R1(J[f]),finalSize:0});let A=Iz(J,j,F);J=A.messages,j=A.originalIndexes,V=h9(J,$.estimateMessageTokens)}if(V>$.targetTokens)return Z.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:J,actions:W,liveTailHandling:"included_degraded",estimatedTokens:V,warnings:Z};return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z}}import{CHARS_PER_TOKEN as Wd,estimateTokens as I9}from"@cline/shared";var sB=128000,gz=0.9,A2=0.9,tB=0.7,eB=20000,nB=1024,aB=2000,$H=2000,WH=8;function oB($){return typeof $==="number"&&Number.isFinite($)&&$>0}function h4($){let W=oB($.contextWindow)?$.contextWindow:void 0,Z=oB($.maxInputTokens)?$.maxInputTokens:void 0;if(Z!==void 0)return W===void 0?Z:Math.min(Z,W);return W===void 0?void 0:W*gz}function y4($,W){if($.length<=W)return $;return`${$.slice(0,W)}
325
- ...[truncated ${$.length-W} chars]`}function mz($){let W=w3($);if(typeof W==="string")return W;return W.map((Z)=>{switch(Z.type){case"text":return Z.text;case"file":return`<file path="${Z.path}">
324
+ ...[truncated ${$.length-Q} chars]`;return`${$.slice(0,Q)}${J}`}function WH($,W){if(typeof $==="string")return I8($,W);let Z=W;return $.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};return Q}if(Q.type==="text"){let J=I8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=I8(Q.content,Z);return Z-=J.length,{...Q,content:J}}return Q})}function vz($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;if(Z.type==="file")return W+Z.content.length;return W},0)}function cz($,W){if(typeof $.content==="string")return{...$,content:I8($.content,W)};let Z=W;return{...$,content:$.content.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};if(Q.type==="tool_result")return{...Q,content:WH(Q.content,0)};return Q}if(Q.type==="text"){let J=I8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=I8(Q.content,Z);return Z-=J.length,{...Q,content:J}}if(Q.type==="tool_result"){let J=WH(Q.content,Z);return Z-=vz(J),{...Q,content:J}}return Q})}}function uz($){if(typeof $.content==="string")return $.content.length>0;return $.content.some((W)=>W.type==="text"||W.type==="file"||W.type==="tool_result")}function dz($,W,Z){return{messages:$.filter((Q,J)=>!Z.has(J)),originalIndexes:W.filter((Q,J)=>!Z.has(J))}}function lz($,W){if(W<0)return!1;for(let Z of $)if(Z>=W)return!0;return!1}function ZH($,W){return W>=0&&$.has(W)}function b4($){let W=[],Z=[],Q=Sz($.policyIntent);if($.targetTokens<=0)return{status:"failed",messages:eB($.messages),actions:W,liveTailHandling:"preserved_out_of_band",estimatedTokens:uW($.messages,$.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let J=eB($.messages),j=J.map((B,H)=>H);if(Q.dropThinkingBlocks){let B=$H(mz(J,j,W),j,W,"unsafe_to_truncate");J=B.messages,j=B.originalIndexes}let X=Q.protectLatestTypedUser?dW(J):-1,Y=Q.protectLiveTailFromDrop?S3(J):J.length;if(Q.dropUnsafeOutsideLiveTail){let B=$H(gz(J,j,W,X,Y,Q),j,W);J=B.messages,j=B.originalIndexes}let V=uW(J,$.estimateMessageTokens);if(V<=$.targetTokens)return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z};for(let B=J.length-1;B>=0&&V>$.targetTokens;B-=1){let H=dW(J);if(B===H)continue;if(Q.protectLiveTailFromDrop&&B>=S3(J))continue;if(!uz(J[B]))continue;let G=R1(J[B]),K=Math.max(1,G/Math.max(1,$.estimateMessageTokens(J[B]))),F=Math.max(16,Math.floor($.targetTokens*K/Math.max(1,J.length)));J[B]=cz(J[B],F),W.push({kind:"truncated_text",path:{messageIndex:j[B]},reason:"over_budget",originalSize:G,finalSize:R1(J[B])}),V=uW(J,$.estimateMessageTokens)}for(let B=0;B<J.length&&V>$.targetTokens;){let H=bz(J),G=dW(J),K=Q.protectLiveTailFromDrop?S3(J):J.length;if(B===H||B===G){W.push({kind:"preserved",path:{messageIndex:j[B]},reason:"protected_live_tail",originalSize:R1(J[B]),finalSize:R1(J[B])}),B+=1;continue}let F=hz(J,B);if(ZH(F,H)){B+=1;continue}if(ZH(F,G)){B+=1;continue}if(lz(F,K)){B+=1;continue}for(let D of F)W.push({kind:"dropped_message",path:{messageIndex:j[D]},reason:F.size>1||b3(J[D]).size>0?"tool_pair_boundary":"over_budget",originalSize:R1(J[D]),finalSize:0});let A=dz(J,j,F);J=A.messages,j=A.originalIndexes,V=uW(J,$.estimateMessageTokens)}if(V>$.targetTokens)return Z.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:J,actions:W,liveTailHandling:"included_degraded",estimatedTokens:V,warnings:Z};return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z}}import{CHARS_PER_TOKEN as Gd,estimateTokens as lW}from"@cline/shared";var YH=128000,pz=0.9,U2=0.9,VH=0.7,BH=20000,JH=1024,jH=2000,HH=2000,GH=8;function XH($){return typeof $==="number"&&Number.isFinite($)&&$>0}function I4($){let W=XH($.contextWindow)?$.contextWindow:void 0,Z=XH($.maxInputTokens)?$.maxInputTokens:void 0;if(Z!==void 0)return W===void 0?Z:Math.min(Z,W);return W===void 0?void 0:W*pz}function k4($,W){if($.length<=W)return $;return`${$.slice(0,W)}
325
+ ...[truncated ${$.length-W} chars]`}function rz($){let W=y3($);if(typeof W==="string")return W;return W.map((Z)=>{switch(Z.type){case"text":return Z.text;case"file":return`<file path="${Z.path}">
326
326
  ${Z.content}
327
327
  </file>`;case"image":return`[image:${Z.mediaType}]`;default:return""}}).join(`
328
- `)}function w3($){if(typeof $==="string")return y4($,aB);return $.map((W)=>{switch(W.type){case"text":return{...W,text:y4(W.text,aB)};case"file":return{...W,content:y4(W.content,$H)};case"image":return W;default:return W}})}function vz($){return Object.entries($).map(([W,Z])=>`${W}=${JSON.stringify(Z)}`).join(", ")}function ZH($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let W=[];for(let Z of $.content)switch(Z.type){case"text":W.push(`[${$.role==="user"?"User":"Bot"}]: ${Z.text}`);break;case"thinking":W.push(`[Bot thinking]: ${y4(Z.thinking,2000)}`);break;case"redacted_thinking":W.push("[Bot thinking]: [redacted]");break;case"tool_use":W.push(`[Bot tool calls]: ${Z.name}(${vz(Z.input)})`);break;case"tool_result":W.push(`[Tool result]: ${mz(Z.content)}`);break;case"file":W.push(`[${$.role==="user"?"User":"Bot"} file ${Z.path}]: ${y4(Z.content,$H)}`);break;case"image":W.push(`[${$.role==="user"?"User":"Bot"} image]: ${Z.mediaType}`);break}return W.join(`
329
- `)}function QH($){return $.map(ZH).join(`
328
+ `)}function y3($){if(typeof $==="string")return k4($,jH);return $.map((W)=>{switch(W.type){case"text":return{...W,text:k4(W.text,jH)};case"file":return{...W,content:k4(W.content,HH)};case"image":return W;default:return W}})}function iz($){return Object.entries($).map(([W,Z])=>`${W}=${JSON.stringify(Z)}`).join(", ")}function KH($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let W=[];for(let Z of $.content)switch(Z.type){case"text":W.push(`[${$.role==="user"?"User":"Bot"}]: ${Z.text}`);break;case"thinking":W.push(`[Bot thinking]: ${k4(Z.thinking,2000)}`);break;case"redacted_thinking":W.push("[Bot thinking]: [redacted]");break;case"tool_use":W.push(`[Bot tool calls]: ${Z.name}(${iz(Z.input)})`);break;case"tool_result":W.push(`[Tool result]: ${rz(Z.content)}`);break;case"file":W.push(`[${$.role==="user"?"User":"Bot"} file ${Z.path}]: ${k4(Z.content,HH)}`);break;case"image":W.push(`[${$.role==="user"?"User":"Bot"} image]: ${Z.mediaType}`);break}return W.join(`
329
+ `)}function FH($){return $.map(KH).join(`
330
330
 
331
- `).trim()}function JH(){let $=new WeakMap;return(W)=>{let Z=W,Q=$.get(Z);if(typeof Q==="number")return Q;let J;try{J=JSON.stringify(W)}catch{J=ZH(W)}let j=I9(J.length);return $.set(Z,j),j}}function k4($){return $.metadata?.kind==="compaction_summary"}function C3($){if(!k4($))return;let W=$.metadata;if(!W)return;let Z=W.details;return{kind:"compaction_summary",summary:String(W.summary??""),details:{readFiles:Array.isArray(Z?.readFiles)?Z.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(Z?.modifiedFiles)?Z.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(W.tokensBefore??0),generatedAt:Number(W.generatedAt??0)}}function cz($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function I4($){return $.role==="user"&&!cz($)&&!k4($)}function jH($){for(let W=0;W<$.length;W+=1)if(I4($[W]))return W;return-1}function x9($){for(let W=$.length-1;W>=0;W-=1)if(I4($[W]))return W;return 0}function XH($){for(let W=$.length-1;W>=0;W-=1)if($[W].role==="assistant")return W;return-1}function YH($){for(let W=$.length-1;W>=0;W-=1)if(k4($[W]))return W;return-1}function VH($,W,Z){let Q=x9($);if(Q<=0)return 0;let J=0,j=$.length;for(let Y=$.length-1;Y>=0;Y-=1)if(J+=Z($[Y]),j=Y,J>=W)break;if(j<=0)return 0;let X=Math.min(j,Q);while(X>0&&!I4($[X]))X-=1;return X}function b4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((W)=>b4(W));if($&&typeof $==="object"){let W=$,Z=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])Z.push(...b4(W[Q]));if(Array.isArray(W.files)){for(let Q of W.files)if(Q&&typeof Q==="object")Z.push(...b4(Q.path))}if(Array.isArray(W.file_paths))Z.push(...b4(W.file_paths));return Z}return[]}function S4($,W){let Z=new Set($);for(let Q of W){let J=Q.trim();if(!J)continue;Z.add(J)}return[...Z].sort((Q,J)=>Q.localeCompare(J))}function P3($){let W=[],Z=[];for(let Q of $){let J=C3(Q);if(J){W=S4(W,J.details.readFiles),Z=S4(Z,J.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let j of Q.content){if(j.type==="file"){W=S4(W,[j.path]);continue}if(j.type!=="tool_use")continue;let X=b4(j.input);if(j.name==="read_files"){W=S4(W,X);continue}if(j.name==="editor"||j.name==="apply_patch")Z=S4(Z,X)}}return{readFiles:W,modifiedFiles:Z}}function uz($){let W=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
331
+ `).trim()}function AH(){let $=new WeakMap;return(W)=>{let Z=W,Q=$.get(Z);if(typeof Q==="number")return Q;let J;try{J=JSON.stringify(W)}catch{J=KH(W)}let j=lW(J.length);return $.set(Z,j),j}}function x4($){return $.metadata?.kind==="compaction_summary"}function h3($){if(!x4($))return;let W=$.metadata;if(!W)return;let Z=W.details;return{kind:"compaction_summary",summary:String(W.summary??""),details:{readFiles:Array.isArray(Z?.readFiles)?Z.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(Z?.modifiedFiles)?Z.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(W.tokensBefore??0),generatedAt:Number(W.generatedAt??0)}}function nz($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function g4($){return $.role==="user"&&!nz($)&&!x4($)}function UH($){for(let W=0;W<$.length;W+=1)if(g4($[W]))return W;return-1}function pW($){for(let W=$.length-1;W>=0;W-=1)if(g4($[W]))return W;return 0}function DH($){for(let W=$.length-1;W>=0;W-=1)if($[W].role==="assistant")return W;return-1}function _H($){for(let W=$.length-1;W>=0;W-=1)if(x4($[W]))return W;return-1}function fH($,W,Z){let Q=pW($);if(Q<=0)return 0;let J=0,j=$.length;for(let Y=$.length-1;Y>=0;Y-=1)if(J+=Z($[Y]),j=Y,J>=W)break;if(j<=0)return 0;let X=Math.min(j,Q);while(X>0&&!g4($[X]))X-=1;return X}function h4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((W)=>h4(W));if($&&typeof $==="object"){let W=$,Z=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])Z.push(...h4(W[Q]));if(Array.isArray(W.files)){for(let Q of W.files)if(Q&&typeof Q==="object")Z.push(...h4(Q.path))}if(Array.isArray(W.file_paths))Z.push(...h4(W.file_paths));return Z}return[]}function y4($,W){let Z=new Set($);for(let Q of W){let J=Q.trim();if(!J)continue;Z.add(J)}return[...Z].sort((Q,J)=>Q.localeCompare(J))}function k3($){let W=[],Z=[];for(let Q of $){let J=h3(Q);if(J){W=y4(W,J.details.readFiles),Z=y4(Z,J.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let j of Q.content){if(j.type==="file"){W=y4(W,[j.path]);continue}if(j.type!=="tool_use")continue;let X=h4(j.input);if(j.name==="read_files"){W=y4(W,X);continue}if(j.name==="editor"||j.name==="apply_patch")Z=y4(Z,X)}}return{readFiles:W,modifiedFiles:Z}}function az($){let W=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
332
332
  `):"- none",Z=$.modifiedFiles.length>0?$.modifiedFiles.map((Q)=>`- ${Q}`).join(`
333
333
  `):"- none";return`## Files
334
334
  Read:
335
335
  ${W}
336
336
  Modified:
337
- ${Z}`}function BH($,W){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
337
+ ${Z}`}function LH($,W){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
338
338
 
339
- ${uz(W)}`.trim()}function S3($){let W=[`Summarize this session for continuation. Be concise and factual.
339
+ ${az(W)}`.trim()}function I3($){let W=[`Summarize this session for continuation. Be concise and factual.
340
340
 
341
341
  ## Goal
342
342
  One sentence: what is being built or fixed.
@@ -358,20 +358,20 @@ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.tr
358
358
  ${$.previousSummary.trim()}`);return W.push(`Conversation:
359
359
  ${$.conversationText||"(empty)"}`),W.join(`
360
360
 
361
- `)}function HH($){let W=$.summarizer,Z=(J)=>{if(J.providerId==="openai-codex"){let{maxOutputTokens:j,...X}=J;return{...X,thinking:!1}}return{...J,maxOutputTokens:J.maxOutputTokens??nB,thinking:!1}};if(!W)return Z($.activeProviderConfig);let Q=W.providerConfig?.providerId===W.providerId?W.providerConfig:void 0;return Z({...Q??{},providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey??Q?.apiKey,baseUrl:W.baseUrl??Q?.baseUrl,headers:W.headers??Q?.headers,modelInfo:W.modelInfo??Q?.modelInfo,knownModels:W.knownModels??Q?.knownModels,maxOutputTokens:W.maxOutputTokens??nB})}function GH($){return{role:"user",content:`Context summary:
361
+ `)}function TH($){let W=$.summarizer,Z=(J)=>{if(J.providerId==="openai-codex"){let{maxOutputTokens:j,...X}=J;return{...X,thinking:!1}}return{...J,maxOutputTokens:J.maxOutputTokens??JH,thinking:!1}};if(!W)return Z($.activeProviderConfig);let Q=W.providerConfig?.providerId===W.providerId?W.providerConfig:void 0;return Z({...Q??{},providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey??Q?.apiKey,baseUrl:W.baseUrl??Q?.baseUrl,headers:W.headers??Q?.headers,modelInfo:W.modelInfo??Q?.modelInfo,knownModels:W.knownModels??Q?.knownModels,maxOutputTokens:W.maxOutputTokens??JH})}function OH($){return{role:"user",content:`Context summary:
362
362
 
363
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}var b3=1024;function lz($){let W=h4({maxInputTokens:$.maxInputTokens??$.modelInfo?.maxInputTokens,contextWindow:$.modelInfo?.contextWindow});if(W!==void 0)return W;let Z=$.knownModels?.[$.modelId];return h4({maxInputTokens:Z?.maxInputTokens,contextWindow:Z?.contextWindow})}function pz($){return P4({messages:$.messages,targetTokens:Math.max(1,$.targetTokens),policyIntent:"agentic_summary",estimateMessageTokens:$.estimateMessageTokens})}async function rz($){let W=await dz($.providerConfig),Z="";for await(let Q of W.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){Z+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Z.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Z.trim()}function iz($){try{return JSON.stringify($).length}catch{return String($).length}}async function KH($){let W=$.context.messages;if(W.length<2)return;let Z=VH(W,$.preserveRecentTokens,$.estimateMessageTokens);if(Z<=0||Z>=W.length)return;let Q=W.slice(0,Z),J=YH(Q),j=J>=0?C3(Q[J])?.summary:void 0,X=J>=0?Q.slice(J+1):Q;if(X.length===0)return;let Y=P3(Q),V=HH({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),B=lz(V),H=$.summarizer===void 0,G=Math.max($.context.budget.request.maxInputTokens,$.context.budget.request.triggerTokens,b3);if(B===void 0&&!H)$.logger?.log("Agentic compaction summarizer has no known input limit; using conservative summary budget",{severity:"warn",summarizerProviderId:V.providerId,summarizerModelId:V.modelId,fallbackInputLimit:b3});let K=B??(H?G:b3),F=I9(S3({previousSummary:j,conversationText:"",fileOps:Y}).length),A=K-F;if(A<=0){$.logger?.debug("Skipped agentic compaction: summarizer budget exhausted",{summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,summaryRequestOverheadTokens:F});return}let f=pz({messages:X,targetTokens:A,estimateMessageTokens:$.estimateMessageTokens});if(f.status==="failed"){$.logger?.log("Skipped agentic compaction: summary input budget failed",{severity:"warn",budgetWarnings:f.warnings.map((p)=>p.code),summaryInputEstimatedTokens:f.estimatedTokens,targetTokens:A,summarizerProviderId:V.providerId,summarizerModelId:V.modelId});return}let U=P3(f.messages),_=QH(f.messages),D=S3({previousSummary:j,conversationText:_,fileOps:U});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:X.length,preservedMessages:W.length-Z,previousSummaryChars:j?.length??0,conversationTextChars:_.length,summaryRequestChars:D.length,summaryRequestEstimatedTokens:I9(D.length),newMessagesJsonChars:iz(X),summaryInputEstimatedTokens:f.estimatedTokens,summaryInputActions:f.actions.length,summaryInputWarnings:f.warnings.map((p)=>p.code),summaryRequestOverheadTokens:F,summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,maxInputTokens:$.context.budget.request.maxInputTokens,triggerTokens:$.context.budget.request.triggerTokens});let M=await rz({providerConfig:V,request:D,logger:$.logger});if(!M.trim())return;let O=BH(M,U),T=W.reduce((p,x)=>p+$.estimateMessageTokens(x),0),L=[GH({summary:O,fileOps:U,tokensBefore:T}),...W.slice(Z)],C=L.reduce((p,x)=>p+$.estimateMessageTokens(x),0);$.logger?.debug("Performed agentic compaction",{messagesBefore:W.length,messagesAfter:L.length,messagesSummarized:Z,messagesPreserved:W.length-Z,tokensBefore:T,tokensAfter:C,maxInputTokens:$.context.budget.request.maxInputTokens});let N=f.actions.filter((p)=>p.reason==="over_budget"||p.reason==="tool_pair_boundary").length;return{messages:L,budget:{policyIntent:"agentic_summary",actionCount:N,warningCount:f.warnings.length,liveTailHandling:f.liveTailHandling}}}import{CHARS_PER_TOKEN as nz}from"@cline/shared";function az($){if(k4($))return;if(typeof $.content==="string"){let Z=$.content.trim();return Z?{...$,content:Z}:void 0}let W=$.content.filter((Z)=>Z.type!=="text"||Z.text.trim());if(W.length===0)return;return{...$,content:W.map((Z)=>Z.type==="text"?{...Z,text:Z.text.trim()}:Z.type==="tool_result"?{...Z,content:w3(Z.content)}:Z)}}function FH($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function AH($,W){if($.length<=W)return $;let Z=`
364
- ...`,Q=Math.max(1,W-Z.length);return`${$.slice(0,Q)}${Z}`}function UH($,W){let Z=Number.isFinite(W)?Math.max(1,W):1,Q=Math.max(16,Z*nz);if(typeof $.content==="string"){let X=AH($.content,Q).trim();return{...$,content:X||"..."}}let J=Q,j=$.content.map((X)=>{if(X.type!=="text"||J<=0)return X;let Y=AH(X.text,J).trim();return J-=Y.length,{...X,text:Y||"..."}});return{...$,content:j}}function oz($,W){let Z=jH($),Q=x9($),J=XH($),j=[],X=0;for(let Y=0;Y<$.length;Y+=1){let V=az($[Y]);if(!V)continue;let B=W(V);X+=B,j.push({index:Y,message:V,estimatedTokens:B,toolPairIds:DH(V),isFirstUser:Y===Z,isLastUser:Y===Q,isLastAssistant:Y===J})}return{candidates:j,totalTokens:X}}function fH($,W,Z,Q){let J=$[W],j=J.estimatedTokens;return J.message=Z,J.estimatedTokens=Q(Z),J.toolPairIds=DH(Z),J.estimatedTokens-j}function DH($){if(!Array.isArray($.content))return[];let W=[];for(let Z of $.content)if(Z.type==="tool_use")W.push(Z.id);else if(Z.type==="tool_result")W.push(Z.tool_use_id);return W}function sz($){let W=new Map;for(let Z of $)for(let Q of Z.toolPairIds){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function tz($,W,Z){let Q=new Set,J=[Z],j=0;while(j<J.length){let X=J[j];if(j+=1,X===void 0||!$.has(X)||Q.has(X))continue;Q.add(X);for(let Y of X.toolPairIds)for(let V of W.get(Y)??[])if(!Q.has(V))J.push(V)}return Q}function ez($,W){let Z=0;for(let Q of $){if(W.has(Q))continue;$[Z]=Q,Z+=1}$.length=Z}function g9($,W,Z,Q){let J=new Set($),j=sz($);for(let X=0;X<$.length&&Q>Z;){if(!W($[X])){X+=1;continue}let Y=tz(J,j,$[X]);if(Y.size===0){X+=1;continue}let V=0;for(let B of Y)V+=B.estimatedTokens,J.delete(B);Q-=V,ez($,Y)}return Q}function $q($,W,Z,Q,J){if(Z<=W)return Z;for(let X=$.length-1;X>=0&&Z>W;X-=1){let Y=$[X];if(Y.isFirstUser)continue;let V=Math.max(WH,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)continue;Z+=fH($,X,UH(Y.message,V),J)}if(Z<=W)return Z;let j=$.findIndex((X)=>X.isFirstUser);if(j>=0){if($[j].estimatedTokens<=Q)return Z;while(Z>W){let Y=$[j],V=Math.max(1,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)break;let B=Y.estimatedTokens;if(Z+=fH($,j,UH(Y.message,V),J),Y.estimatedTokens>=B)break}}return Z}function Wq($,W){return JSON.stringify($)!==JSON.stringify(W)}function Zq($){let W=x9($);if(W<0||W===0&&!I4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,W),protectedTail:$.slice(W)}}function _H($){let W=Math.max(1,Math.min($.context.budget.messages.targetTokens,$.context.budget.messages.triggerTokens)),{compactable:Z,protectedTail:Q}=Zq($.context.messages);if(Z.length===0)return;let J=FH(Q,$.estimateMessageTokens),j=Math.max(1,W-J),X=oz(Z,$.estimateMessageTokens),{candidates:Y}=X;if(Y.length===0)return;let V=X.totalTokens,B=V;B=g9(Y,(U)=>U.message.role==="assistant"&&!U.isLastAssistant,j,B),B=g9(Y,(U)=>U.message.role==="user"&&!U.isFirstUser&&!U.isLastUser,j,B),B=g9(Y,(U)=>U.message.role==="assistant"&&U.isLastAssistant,j,B),B=g9(Y,(U)=>U.message.role==="user"&&U.isLastUser&&!U.isFirstUser,j,B),B=$q(Y,j,B,$.context.budget.messages.triggerTokens,$.estimateMessageTokens);let H=[...Y.map((U)=>U.message),...Q],G=P4({messages:H,targetTokens:W,policyIntent:"basic_compaction_projection",estimateMessageTokens:$.estimateMessageTokens});if(G.status==="failed")$.logger?.debug("Basic compaction returned best-effort projection",{budgetWarnings:G.warnings.map((U)=>U.code),projectedTokens:G.estimatedTokens,targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens});let K=G.messages;if(!Wq($.context.messages,K))return;let F=V+J,A=FH(K,$.estimateMessageTokens),f=G.actions.filter((U)=>U.reason==="over_budget"||U.reason==="tool_pair_boundary").length;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:K.length,messagesRemoved:$.context.messages.length-K.length,tokensBefore:F,tokensAfter:A,budgetStatus:G.status,budgetActions:f,budgetWarnings:G.warnings.map((U)=>U.code),targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens}),{messages:K,budget:{policyIntent:"basic_compaction_projection",actionCount:f,warningCount:G.warnings.length,liveTailHandling:G.liveTailHandling}}}var Jq=0.5;function TH($){try{return JSON.stringify($).length}catch{return String($).length}}function jq($){let W=0,Z=0,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result")continue;let X=TH(j.content);W+=1,Z+=X,Q=Math.max(Q,X)}}return{toolResultCount:W,toolResultSerializedChars:Z,maxToolResultSerializedChars:Q}}var Xq={basic:({context:$,estimateMessageTokens:W,logger:Z})=>_H({context:$,estimateMessageTokens:W,logger:Z}),agentic:({context:$,providerConfig:W,compaction:Z,estimateMessageTokens:Q,logger:J})=>KH({context:$,providerConfig:W,summarizer:Z?.summarizer,preserveRecentTokens:Math.min(Z?.preserveRecentTokens??eB,$.budget.messages.targetTokens),estimateMessageTokens:Q,logger:J})};function Yq($){let W=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Z=Math.min(0.95,Math.max(0.05,W));return Math.max(1,Math.floor(Math.min($.messageTriggerTokens,$.messageInputTokens*Z)))}function Vq($){let W=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*Jq):Math.floor($.triggerTokens*tB),Z=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(W,$.maxInputTokens,Z))}function LH($,W){return Math.max(1,Math.floor($-W))}function Bq($){let W=0,Z=!1;for(let Q of $)if(Q.role==="user")Z=!0;else if(Q.role==="assistant"&&Z)W+=1,Z=!1;return W}function x4($,W={}){let Z=$.compaction;if(Z?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=JH(),j=Z?.strategy??"basic",X=Xq[j],Y=W.mode??"auto",V=Z?.compact?"custom":j;return async(B)=>{let H=B.apiMessages.reduce((r,d)=>r+J(d),0),G=Qq({systemPrompt:B.systemPrompt,messages:B.apiMessages,tools:B.tools}),K=B.messages.reduce((r,d)=>r+J(d),0),F=Math.max(0,G-H),A=h4({maxInputTokens:B.model.info?.maxInputTokens,contextWindow:B.model.info?.contextWindow})??sB,f=A*A2,U=LH(f,F),_=G>=f;if($.logger?.debug("Context compaction diagnostics",{mode:Y,strategy:j,iteration:B.iteration,providerId:$.providerId,modelId:$.modelId,requestInputTokens:G,apiMessageTokens:H,messageInputTokens:K,requestOverheadTokens:F,maxInputTokens:A,requestTriggerTokens:f,messageTriggerTokens:U,thresholdRatio:A2,shouldCompact:_,messageCount:B.messages.length,apiMessageCount:B.apiMessages.length,apiMessagesJsonChars:TH(B.apiMessages),...jq(B.apiMessages)}),Y==="auto"&&!_)return;let D,M;if(Y==="auto")D=Vq({maxInputTokens:A,modelMaxTokens:B.model.info?.maxTokens,triggerTokens:f,messagePairCount:Bq(B.messages)}),M=LH(D,F);else M=Yq({messageInputTokens:K,messageTriggerTokens:U,manualTargetRatio:W.manualTargetRatio}),D=F+M;let O={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId,iteration:B.iteration,messages:B.messages,model:B.model,mode:Y,budget:{request:{inputTokens:G,maxInputTokens:A,triggerTokens:f,targetTokens:D,overheadTokens:F,thresholdRatio:A2,utilizationRatio:A>0?G/A:0},messages:{inputTokens:K,triggerTokens:U,targetTokens:M}}},T=Y==="manual"?"manual_compaction":"auto_compaction";B.emitStatusNotice?.(Y==="manual"?"compacting":"auto-compacting",{kind:T,reason:T,phase:"started",iteration:B.iteration,triggerTokens:f,targetTokens:D,maxInputTokens:A,messageTargetTokens:M});let L=B.messages.length,C=Date.now(),N=Z?.compact?await Z.compact(O):await X({context:O,providerConfig:{...Q,abortSignal:B.abortSignal},compaction:Z,estimateMessageTokens:J,logger:$.logger}),p=Date.now()-C,x=$.sessionId??B.conversationId,P={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId??void 0};if(N?.messages){let r=N.messages.reduce((k1,e$)=>k1+J(e$),0),d=F+r;if($.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:A,messageInputTokens:K,apiInputTokens:H,requestInputTokens:G,requestOverheadTokens:F,afterMessageTokens:r,afterRequestTokens:d,tokensSaved:G-d,utilizationBefore:`${(G/A*100).toFixed(1)}%`,utilizationAfter:`${(d/A*100).toFixed(1)}%`,thresholdTrigger:`${(A2*100).toFixed(1)}%`,messagesBefore:L,messagesAfter:N.messages.length,messagesRemoved:L-N.messages.length}),B.emitStatusNotice?.(Y==="manual"?"compacted":"auto-compacted",{kind:T,reason:T,phase:"completed",iteration:B.iteration,tokensBefore:G,tokensAfter:d,messagesBefore:L,messagesAfter:N.messages.length,maxInputTokens:A}),Z9($.telemetry,{ulid:x,strategy:V,mode:Y,messagesBefore:L,messagesAfter:N.messages.length,messagesRemoved:L-N.messages.length,tokensBefore:G,tokensAfter:d,tokensSaved:G-d,triggerTokens:f,maxInputTokens:A,thresholdRatio:A2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P}),N.budget&&(N.budget.actionCount>0||N.budget.warningCount>0))fV($.telemetry,{ulid:x,strategy:V,mode:Y,policyIntent:N.budget.policyIntent,actionCount:N.budget.actionCount,warningCount:N.budget.warningCount,liveTailHandling:N.budget.liveTailHandling,provider:$.providerId,modelId:$.modelId,...P}),B.emitStatusNotice?.("compaction-budget-adjusted",{kind:"compaction_budget_emergency",reason:"compaction_budget_emergency",iteration:B.iteration,policyIntent:N.budget.policyIntent,actionCount:N.budget.actionCount,warningCount:N.budget.warningCount})}else B.emitStatusNotice?.(Y==="manual"?"compaction-skipped":"auto-compaction-skipped",{kind:T,reason:T,phase:"skipped",iteration:B.iteration,maxInputTokens:A}),Q9($.telemetry,{ulid:x,strategy:V,mode:Y,reason:"no_result",tokensBefore:G,triggerTokens:f,maxInputTokens:A,thresholdRatio:A2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P});return N}}function g4($){return async(W)=>{let Z=$.getState?.(),Q=Z?F2(Z,W.messages):void 0;if(Z&&Q){let j=$.compact?await $.compact({...W,messages:Q,apiMessages:Q}):void 0;if(j?.messages){let X=j.systemPrompt??Z.system_prompt,Y=y8({sourceMessages:W.messages,compactedMessages:j.messages,conversationId:W.conversationId,systemPrompt:X});return await $.saveState?.(Y),{...j,...X!==void 0?{systemPrompt:X}:{}}}return{messages:Q,...j?.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:Z.system_prompt!==void 0?{systemPrompt:Z.system_prompt}:{}}}let J=$.compact?await $.compact(W):void 0;if(J?.messages){let j=y8({sourceMessages:W.messages,compactedMessages:J.messages,conversationId:W.conversationId,systemPrompt:J.systemPrompt});await $.saveState?.(j)}return J}}var sG={};w(sG,{zodToJsonSchema:()=>HN,validateWithZod:()=>BN,truncateCommandOutput:()=>_2,resolveToolRoutingConfig:()=>l8,resolveToolPresetName:()=>t1,resolveCoreSelectedToolIds:()=>JZ,getCoreHeadlessToolNames:()=>Q5,getCoreDefaultEnabledToolIds:()=>QZ,getCoreBuiltinToolCatalog:()=>S2,getCoreAcpToolNames:()=>jZ,createWebFetchTool:()=>g3,createWebFetchExecutor:()=>s4,createToolPoliciesWithPreset:()=>n9,createSubmitAndExitTool:()=>u3,createSkillsTool:()=>T2,createShellTool:()=>n4,createShellExecutor:()=>L2,createSearchTool:()=>x3,createSearchExecutor:()=>o4,createReadFilesTool:()=>I3,createFileReadExecutor:()=>a4,createEditorTool:()=>v3,createEditorExecutor:()=>q2,createDefaultToolsWithPreset:()=>a9,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>t4,createDefaultExecutors:()=>u8,createBuiltinTools:()=>b2,createAskQuestionTool:()=>c3,createApplyPatchTool:()=>m3,createApplyPatchExecutor:()=>z2,computePatchChanges:()=>m8,WebFetchRequestSchema:()=>y3,ToolPresets:()=>a0,TEAM_TOOL_NAMES:()=>i8,SubmitInputSchema:()=>i4,StructuredCommandInputSchema:()=>f2,SkillsInputSchema:()=>p4,SearchCodebaseInputSchema:()=>v4,RunCommandsInputSchema:()=>c4,ReadFilesInputSchema:()=>m4,ReadFileRequestSchema:()=>c9,PatchActionType:()=>O2,MAX_COMMAND_OUTPUT_CHARS:()=>n1,FetchWebContentInputSchema:()=>u4,EditFileInputSchema:()=>d4,DefaultToolNames:()=>T0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>d8,CommandExitError:()=>a1,AskQuestionInputSchema:()=>r4,ApplyPatchInputSchema:()=>l4,ALL_DEFAULT_TOOL_NAMES:()=>U$});import{validateWithZod as BN,zodToJsonSchema as HN}from"@cline/shared";M0();import{createTool as M$,validateWithZod as R$,zodToJsonSchema as o1}from"@cline/shared";var zH="__clineInternalTelemetry";function qH($){let W=$?.__clineInternalTelemetry;return W&&typeof W==="object"&&"capture"in W&&typeof W.capture==="function"?W:void 0}import{spawn as IH}from"node:child_process";import{StringDecoder as Uq}from"node:string_decoder";import{getDefaultShell as fq,getShellArgs as Dq}from"@cline/shared";import{validateWithZod as Gq}from"@cline/shared";import{z}from"zod";var q$=6000,U2=z.string().describe("The absolute path of a text file to read content from"),m9=z.object({start_line:z.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:z.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"),c9=z.object({path:U2,start_line:m9.shape.start_line,end_line:m9.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds. Always include path; start_line/end_line must be on the same object as the path they apply to, never in a separate array element"),m4=z.object({files:z.array(c9).describe("Array of file read requests; each element is one file and must include path. Omit start_line/end_line or set them to null to read from the start; provide integers on the same object as the path to return only that inclusive one-based line range — never emit a range as its own array element. 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.")}),MH={start_line:m9.shape.start_line,end_line:m9.shape.end_line},k8=z.union([c9,z.object({file_path:U2,...MH}).transform(({file_path:$,...W})=>({path:$,...W})),z.object({filePath:U2,...MH}).transform(({filePath:$,...W})=>({path:$,...W}))]),RH=z.union([m4,k8,z.array(k8),z.array(z.string()),z.string(),z.object({files:z.array(z.union([U2,k8]))}),z.object({files:k8}),z.object({files:U2}),z.object({file_paths:z.array(U2)}),z.object({file_paths:z.string()}),z.object({paths:z.array(z.union([U2,k8]))}),z.object({paths:k8}),z.object({paths:z.string()})]),v4=z.object({queries:z.array(z.string()).describe("Array of regex search queries to execute")}),NH=z.union([v4,z.array(z.string()),z.string(),z.object({queries:z.string()})]),v9=z.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${q$*2} characters) to avoid timeouts.`),f2=z.object({command:z.string().min(1).describe("The executable to run directly without shell parsing."),args:z.array(z.string()).optional().describe("Optional argv list passed directly to the executable.")}),EH=z.union([v9,f2]),c4=z.object({commands:z.array(v9).describe("Array of complete shell command strings to execute.")}),Hq=z.object({commands:z.array(EH)}),wH=z.union([c4,Hq,z.object({commands:EH}),z.array(f2),f2,z.object({command:v9}),z.object({cmd:v9}),z.array(z.string()),z.string()]),y3=z.object({url:z.string().describe("The URL to fetch"),prompt:z.string().min(2).describe("Analysis prompt for the fetched content")}),u4=z.object({requests:z.array(y3).describe("Array of the URLs for the web fetch requests")}),d4=z.object({path:z.string().min(1).describe("The absolute path for the action to be performed on"),old_text:z.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 ${q$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:z.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 ${q$} 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:z.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."),l4=z.object({input:z.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."),CH=z.union([l4,z.string()]),p4=z.object({skill:z.string().min(1).describe("Name of the skill to execute."),args:z.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),r4=z.object({question:z.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:z.array(z.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),i4=z.object({summary:z.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:z.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.
363
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}var x3=1024;function sz($){let W=I4({maxInputTokens:$.maxInputTokens??$.modelInfo?.maxInputTokens,contextWindow:$.modelInfo?.contextWindow});if(W!==void 0)return W;let Z=$.knownModels?.[$.modelId];return I4({maxInputTokens:Z?.maxInputTokens,contextWindow:Z?.contextWindow})}function tz($){return b4({messages:$.messages,targetTokens:Math.max(1,$.targetTokens),policyIntent:"agentic_summary",estimateMessageTokens:$.estimateMessageTokens})}async function ez($){let W=await oz($.providerConfig),Z="";for await(let Q of W.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){Z+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Z.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Z.trim()}function $q($){try{return JSON.stringify($).length}catch{return String($).length}}async function zH($){let W=$.context.messages;if(W.length<2)return;let Z=fH(W,$.preserveRecentTokens,$.estimateMessageTokens);if(Z<=0||Z>=W.length)return;let Q=W.slice(0,Z),J=_H(Q),j=J>=0?h3(Q[J])?.summary:void 0,X=J>=0?Q.slice(J+1):Q;if(X.length===0)return;let Y=k3(Q),V=TH({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),B=sz(V),H=$.summarizer===void 0,G=Math.max($.context.budget.request.maxInputTokens,$.context.budget.request.triggerTokens,x3);if(B===void 0&&!H)$.logger?.log("Agentic compaction summarizer has no known input limit; using conservative summary budget",{severity:"warn",summarizerProviderId:V.providerId,summarizerModelId:V.modelId,fallbackInputLimit:x3});let K=B??(H?G:x3),F=lW(I3({previousSummary:j,conversationText:"",fileOps:Y}).length),A=K-F;if(A<=0){$.logger?.debug("Skipped agentic compaction: summarizer budget exhausted",{summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,summaryRequestOverheadTokens:F});return}let D=tz({messages:X,targetTokens:A,estimateMessageTokens:$.estimateMessageTokens});if(D.status==="failed"){$.logger?.log("Skipped agentic compaction: summary input budget failed",{severity:"warn",budgetWarnings:D.warnings.map((p)=>p.code),summaryInputEstimatedTokens:D.estimatedTokens,targetTokens:A,summarizerProviderId:V.providerId,summarizerModelId:V.modelId});return}let U=k3(D.messages),f=FH(D.messages),_=I3({previousSummary:j,conversationText:f,fileOps:U});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:X.length,preservedMessages:W.length-Z,previousSummaryChars:j?.length??0,conversationTextChars:f.length,summaryRequestChars:_.length,summaryRequestEstimatedTokens:lW(_.length),newMessagesJsonChars:$q(X),summaryInputEstimatedTokens:D.estimatedTokens,summaryInputActions:D.actions.length,summaryInputWarnings:D.warnings.map((p)=>p.code),summaryRequestOverheadTokens:F,summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,maxInputTokens:$.context.budget.request.maxInputTokens,triggerTokens:$.context.budget.request.triggerTokens});let R=await ez({providerConfig:V,request:_,logger:$.logger});if(!R.trim())return;let O=LH(R,U),T=W.reduce((p,x)=>p+$.estimateMessageTokens(x),0),L=[OH({summary:O,fileOps:U,tokensBefore:T}),...W.slice(Z)],C=L.reduce((p,x)=>p+$.estimateMessageTokens(x),0);$.logger?.debug("Performed agentic compaction",{messagesBefore:W.length,messagesAfter:L.length,messagesSummarized:Z,messagesPreserved:W.length-Z,tokensBefore:T,tokensAfter:C,maxInputTokens:$.context.budget.request.maxInputTokens});let E=D.actions.filter((p)=>p.reason==="over_budget"||p.reason==="tool_pair_boundary").length;return{messages:L,budget:{policyIntent:"agentic_summary",actionCount:E,warningCount:D.warnings.length,liveTailHandling:D.liveTailHandling}}}import{CHARS_PER_TOKEN as Wq}from"@cline/shared";function Zq($){if(x4($))return;if(typeof $.content==="string"){let Z=$.content.trim();return Z?{...$,content:Z}:void 0}let W=$.content.filter((Z)=>Z.type!=="text"||Z.text.trim());if(W.length===0)return;return{...$,content:W.map((Z)=>Z.type==="text"?{...Z,text:Z.text.trim()}:Z.type==="tool_result"?{...Z,content:y3(Z.content)}:Z)}}function qH($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function MH($,W){if($.length<=W)return $;let Z=`
364
+ ...`,Q=Math.max(1,W-Z.length);return`${$.slice(0,Q)}${Z}`}function RH($,W){let Z=Number.isFinite(W)?Math.max(1,W):1,Q=Math.max(16,Z*Wq);if(typeof $.content==="string"){let X=MH($.content,Q).trim();return{...$,content:X||"..."}}let J=Q,j=$.content.map((X)=>{if(X.type!=="text"||J<=0)return X;let Y=MH(X.text,J).trim();return J-=Y.length,{...X,text:Y||"..."}});return{...$,content:j}}function Qq($,W){let Z=UH($),Q=pW($),J=DH($),j=[],X=0;for(let Y=0;Y<$.length;Y+=1){let V=Zq($[Y]);if(!V)continue;let B=W(V);X+=B,j.push({index:Y,message:V,estimatedTokens:B,toolPairIds:NH(V),isFirstUser:Y===Z,isLastUser:Y===Q,isLastAssistant:Y===J})}return{candidates:j,totalTokens:X}}function EH($,W,Z,Q){let J=$[W],j=J.estimatedTokens;return J.message=Z,J.estimatedTokens=Q(Z),J.toolPairIds=NH(Z),J.estimatedTokens-j}function NH($){if(!Array.isArray($.content))return[];let W=[];for(let Z of $.content)if(Z.type==="tool_use")W.push(Z.id);else if(Z.type==="tool_result")W.push(Z.tool_use_id);return W}function Jq($){let W=new Map;for(let Z of $)for(let Q of Z.toolPairIds){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function jq($,W,Z){let Q=new Set,J=[Z],j=0;while(j<J.length){let X=J[j];if(j+=1,X===void 0||!$.has(X)||Q.has(X))continue;Q.add(X);for(let Y of X.toolPairIds)for(let V of W.get(Y)??[])if(!Q.has(V))J.push(V)}return Q}function Xq($,W){let Z=0;for(let Q of $){if(W.has(Q))continue;$[Z]=Q,Z+=1}$.length=Z}function rW($,W,Z,Q){let J=new Set($),j=Jq($);for(let X=0;X<$.length&&Q>Z;){if(!W($[X])){X+=1;continue}let Y=jq(J,j,$[X]);if(Y.size===0){X+=1;continue}let V=0;for(let B of Y)V+=B.estimatedTokens,J.delete(B);Q-=V,Xq($,Y)}return Q}function Yq($,W,Z,Q,J){if(Z<=W)return Z;for(let X=$.length-1;X>=0&&Z>W;X-=1){let Y=$[X];if(Y.isFirstUser)continue;let V=Math.max(GH,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)continue;Z+=EH($,X,RH(Y.message,V),J)}if(Z<=W)return Z;let j=$.findIndex((X)=>X.isFirstUser);if(j>=0){if($[j].estimatedTokens<=Q)return Z;while(Z>W){let Y=$[j],V=Math.max(1,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)break;let B=Y.estimatedTokens;if(Z+=EH($,j,RH(Y.message,V),J),Y.estimatedTokens>=B)break}}return Z}function Vq($,W){return JSON.stringify($)!==JSON.stringify(W)}function Bq($){let W=pW($);if(W<0||W===0&&!g4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,W),protectedTail:$.slice(W)}}function wH($){let W=Math.max(1,Math.min($.context.budget.messages.targetTokens,$.context.budget.messages.triggerTokens)),{compactable:Z,protectedTail:Q}=Bq($.context.messages);if(Z.length===0)return;let J=qH(Q,$.estimateMessageTokens),j=Math.max(1,W-J),X=Qq(Z,$.estimateMessageTokens),{candidates:Y}=X;if(Y.length===0)return;let V=X.totalTokens,B=V;B=rW(Y,(U)=>U.message.role==="assistant"&&!U.isLastAssistant,j,B),B=rW(Y,(U)=>U.message.role==="user"&&!U.isFirstUser&&!U.isLastUser,j,B),B=rW(Y,(U)=>U.message.role==="assistant"&&U.isLastAssistant,j,B),B=rW(Y,(U)=>U.message.role==="user"&&U.isLastUser&&!U.isFirstUser,j,B),B=Yq(Y,j,B,$.context.budget.messages.triggerTokens,$.estimateMessageTokens);let H=[...Y.map((U)=>U.message),...Q],G=b4({messages:H,targetTokens:W,policyIntent:"basic_compaction_projection",estimateMessageTokens:$.estimateMessageTokens});if(G.status==="failed")$.logger?.debug("Basic compaction returned best-effort projection",{budgetWarnings:G.warnings.map((U)=>U.code),projectedTokens:G.estimatedTokens,targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens});let K=G.messages;if(!Vq($.context.messages,K))return;let F=V+J,A=qH(K,$.estimateMessageTokens),D=G.actions.filter((U)=>U.reason==="over_budget"||U.reason==="tool_pair_boundary").length;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:K.length,messagesRemoved:$.context.messages.length-K.length,tokensBefore:F,tokensAfter:A,budgetStatus:G.status,budgetActions:D,budgetWarnings:G.warnings.map((U)=>U.code),targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens}),{messages:K,budget:{policyIntent:"basic_compaction_projection",actionCount:D,warningCount:G.warnings.length,liveTailHandling:G.liveTailHandling}}}var Gq=0.5;function PH($){try{return JSON.stringify($).length}catch{return String($).length}}function Kq($){let W=0,Z=0,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result")continue;let X=PH(j.content);W+=1,Z+=X,Q=Math.max(Q,X)}}return{toolResultCount:W,toolResultSerializedChars:Z,maxToolResultSerializedChars:Q}}var Fq={basic:({context:$,estimateMessageTokens:W,logger:Z})=>wH({context:$,estimateMessageTokens:W,logger:Z}),agentic:({context:$,providerConfig:W,compaction:Z,estimateMessageTokens:Q,logger:J})=>zH({context:$,providerConfig:W,summarizer:Z?.summarizer,preserveRecentTokens:Math.min(Z?.preserveRecentTokens??BH,$.budget.messages.targetTokens),estimateMessageTokens:Q,logger:J})};function Aq($){let W=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Z=Math.min(0.95,Math.max(0.05,W));return Math.max(1,Math.floor(Math.min($.messageTriggerTokens,$.messageInputTokens*Z)))}function Uq($){let W=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*Gq):Math.floor($.triggerTokens*VH),Z=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(W,$.maxInputTokens,Z))}function CH($,W){return Math.max(1,Math.floor($-W))}function Dq($){let W=0,Z=!1;for(let Q of $)if(Q.role==="user")Z=!0;else if(Q.role==="assistant"&&Z)W+=1,Z=!1;return W}function m4($,W={}){let Z=$.compaction;if(Z?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=AH(),j=Z?.strategy??"basic",X=Fq[j],Y=W.mode??"auto",V=Z?.compact?"custom":j;return async(B)=>{let H=B.apiMessages.reduce((r,d)=>r+J(d),0),G=Hq({systemPrompt:B.systemPrompt,messages:B.apiMessages,tools:B.tools}),K=B.messages.reduce((r,d)=>r+J(d),0),F=Math.max(0,G-H),A=I4({maxInputTokens:B.model.info?.maxInputTokens,contextWindow:B.model.info?.contextWindow})??YH,D=A*U2,U=CH(D,F),f=G>=D;if($.logger?.debug("Context compaction diagnostics",{mode:Y,strategy:j,iteration:B.iteration,providerId:$.providerId,modelId:$.modelId,requestInputTokens:G,apiMessageTokens:H,messageInputTokens:K,requestOverheadTokens:F,maxInputTokens:A,requestTriggerTokens:D,messageTriggerTokens:U,thresholdRatio:U2,shouldCompact:f,messageCount:B.messages.length,apiMessageCount:B.apiMessages.length,apiMessagesJsonChars:PH(B.apiMessages),...Kq(B.apiMessages)}),Y==="auto"&&!f)return;let _,R;if(Y==="auto")_=Uq({maxInputTokens:A,modelMaxTokens:B.model.info?.maxTokens,triggerTokens:D,messagePairCount:Dq(B.messages)}),R=CH(_,F);else R=Aq({messageInputTokens:K,messageTriggerTokens:U,manualTargetRatio:W.manualTargetRatio}),_=F+R;let O={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId,iteration:B.iteration,messages:B.messages,model:B.model,mode:Y,budget:{request:{inputTokens:G,maxInputTokens:A,triggerTokens:D,targetTokens:_,overheadTokens:F,thresholdRatio:U2,utilizationRatio:A>0?G/A:0},messages:{inputTokens:K,triggerTokens:U,targetTokens:R}}},T=Y==="manual"?"manual_compaction":"auto_compaction";B.emitStatusNotice?.(Y==="manual"?"compacting":"auto-compacting",{kind:T,reason:T,phase:"started",iteration:B.iteration,triggerTokens:D,targetTokens:_,maxInputTokens:A,messageTargetTokens:R});let L=B.messages.length,C=Date.now(),E=Z?.compact?await Z.compact(O):await X({context:O,providerConfig:{...Q,abortSignal:B.abortSignal},compaction:Z,estimateMessageTokens:J,logger:$.logger}),p=Date.now()-C,x=$.sessionId??B.conversationId,P={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId??void 0};if(E?.messages){let r=E.messages.reduce((I1,$2)=>I1+J($2),0),d=F+r;if($.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:A,messageInputTokens:K,apiInputTokens:H,requestInputTokens:G,requestOverheadTokens:F,afterMessageTokens:r,afterRequestTokens:d,tokensSaved:G-d,utilizationBefore:`${(G/A*100).toFixed(1)}%`,utilizationAfter:`${(d/A*100).toFixed(1)}%`,thresholdTrigger:`${(U2*100).toFixed(1)}%`,messagesBefore:L,messagesAfter:E.messages.length,messagesRemoved:L-E.messages.length}),B.emitStatusNotice?.(Y==="manual"?"compacted":"auto-compacted",{kind:T,reason:T,phase:"completed",iteration:B.iteration,tokensBefore:G,tokensAfter:d,messagesBefore:L,messagesAfter:E.messages.length,maxInputTokens:A}),HW($.telemetry,{ulid:x,strategy:V,mode:Y,messagesBefore:L,messagesAfter:E.messages.length,messagesRemoved:L-E.messages.length,tokensBefore:G,tokensAfter:d,tokensSaved:G-d,triggerTokens:D,maxInputTokens:A,thresholdRatio:U2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P}),E.budget&&(E.budget.actionCount>0||E.budget.warningCount>0))EV($.telemetry,{ulid:x,strategy:V,mode:Y,policyIntent:E.budget.policyIntent,actionCount:E.budget.actionCount,warningCount:E.budget.warningCount,liveTailHandling:E.budget.liveTailHandling,provider:$.providerId,modelId:$.modelId,...P}),B.emitStatusNotice?.("compaction-budget-adjusted",{kind:"compaction_budget_emergency",reason:"compaction_budget_emergency",iteration:B.iteration,policyIntent:E.budget.policyIntent,actionCount:E.budget.actionCount,warningCount:E.budget.warningCount})}else B.emitStatusNotice?.(Y==="manual"?"compaction-skipped":"auto-compaction-skipped",{kind:T,reason:T,phase:"skipped",iteration:B.iteration,maxInputTokens:A}),GW($.telemetry,{ulid:x,strategy:V,mode:Y,reason:"no_result",tokensBefore:G,triggerTokens:D,maxInputTokens:A,thresholdRatio:U2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P});return E}}function v4($){return async(W)=>{let Z=$.getState?.(),Q=Z?A2(Z,W.messages):void 0;if(Z&&Q){let j=$.compact?await $.compact({...W,messages:Q,apiMessages:Q}):void 0;if(j?.messages){let X=j.systemPrompt??Z.system_prompt,Y=k8({sourceMessages:W.messages,compactedMessages:j.messages,conversationId:W.conversationId,systemPrompt:X});return await $.saveState?.(Y),{...j,...X!==void 0?{systemPrompt:X}:{}}}return{messages:Q,...j?.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:Z.system_prompt!==void 0?{systemPrompt:Z.system_prompt}:{}}}let J=$.compact?await $.compact(W):void 0;if(J?.messages){let j=k8({sourceMessages:W.messages,compactedMessages:J.messages,conversationId:W.conversationId,systemPrompt:J.systemPrompt});await $.saveState?.(j)}return J}}var XK={};w(XK,{zodToJsonSchema:()=>fE,validateWithZod:()=>_E,truncateCommandOutput:()=>L2,resolveToolRoutingConfig:()=>r8,resolveToolPresetName:()=>e1,resolveCoreSelectedToolIds:()=>FZ,getCoreHeadlessToolNames:()=>j5,getCoreDefaultEnabledToolIds:()=>KZ,getCoreBuiltinToolCatalog:()=>b2,getCoreAcpToolNames:()=>AZ,createWebFetchTool:()=>d3,createWebFetchExecutor:()=>e4,createToolPoliciesWithPreset:()=>QZ,createSubmitAndExitTool:()=>i3,createSkillsTool:()=>O2,createShellTool:()=>o4,createShellExecutor:()=>T2,createSearchTool:()=>u3,createSearchExecutor:()=>t4,createReadFilesTool:()=>c3,createFileReadExecutor:()=>s4,createEditorTool:()=>p3,createEditorExecutor:()=>M2,createDefaultToolsWithPreset:()=>JZ,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>$5,createDefaultExecutors:()=>l8,createBuiltinTools:()=>y2,createAskQuestionTool:()=>r3,createApplyPatchTool:()=>l3,createApplyPatchExecutor:()=>q2,computePatchChanges:()=>c8,WebFetchRequestSchema:()=>g3,ToolPresets:()=>a0,TEAM_TOOL_NAMES:()=>a8,SubmitInputSchema:()=>a4,StructuredCommandInputSchema:()=>_2,SkillsInputSchema:()=>i4,SearchCodebaseInputSchema:()=>u4,RunCommandsInputSchema:()=>d4,ReadFilesInputSchema:()=>c4,ReadFileRequestSchema:()=>oW,PatchActionType:()=>z2,MAX_COMMAND_OUTPUT_CHARS:()=>a1,FetchWebContentInputSchema:()=>l4,EditFileInputSchema:()=>p4,DefaultToolNames:()=>O0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>p8,CommandExitError:()=>o1,AskQuestionInputSchema:()=>n4,ApplyPatchInputSchema:()=>r4,ALL_DEFAULT_TOOL_NAMES:()=>D$});import{validateWithZod as _E,zodToJsonSchema as fE}from"@cline/shared";R0();import{createTool as R$,validateWithZod as E$,zodToJsonSchema as s1}from"@cline/shared";var iW="__clineInternalTelemetry";function bH($){let W=$?.__clineInternalTelemetry;return W&&typeof W==="object"&&"capture"in W&&typeof W.capture==="function"?W:void 0}import{spawn as pH}from"node:child_process";import{StringDecoder as zq}from"node:string_decoder";import{getDefaultShell as qq,getShellArgs as Mq}from"@cline/shared";import{validateWithZod as fq}from"@cline/shared";import{z}from"zod";var M$=6000,D2=z.string().describe("The absolute path of a text file to read content from"),nW=z.object({start_line:z.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:z.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"),oW=z.object({path:D2,start_line:nW.shape.start_line,end_line:nW.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds. Always include path; start_line/end_line must be on the same object as the path they apply to, never in a separate array element"),c4=z.object({files:z.array(oW).describe("Array of file read requests; each element is one file and must include path. Omit start_line/end_line or set them to null to read from the start; provide integers on the same object as the path to return only that inclusive one-based line range — never emit a range as its own array element. 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.")}),yH={start_line:nW.shape.start_line,end_line:nW.shape.end_line},x8=z.union([oW,z.object({file_path:D2,...yH}).transform(({file_path:$,...W})=>({path:$,...W})),z.object({filePath:D2,...yH}).transform(({filePath:$,...W})=>({path:$,...W}))]),hH=z.union([c4,x8,z.array(x8),z.array(z.string()),z.string(),z.object({files:z.array(z.union([D2,x8]))}),z.object({files:x8}),z.object({files:D2}),z.object({file_paths:z.array(D2)}),z.object({file_paths:z.string()}),z.object({paths:z.array(z.union([D2,x8]))}),z.object({paths:x8}),z.object({paths:z.string()})]),u4=z.object({queries:z.array(z.string()).describe("Array of regex search queries to execute")}),kH=z.union([u4,z.array(z.string()),z.string(),z.object({queries:z.string()})]),aW=z.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${M$*2} characters) to avoid timeouts.`),_2=z.object({command:z.string().min(1).describe("The executable to run directly without shell parsing."),args:z.array(z.string()).optional().describe("Optional argv list passed directly to the executable.")}),IH=z.union([aW,_2]),d4=z.object({commands:z.array(aW).describe("Array of complete shell command strings to execute.")}),_q=z.object({commands:z.array(IH)}),xH=z.union([d4,_q,z.object({commands:IH}),z.array(_2),_2,z.object({command:aW}),z.object({cmd:aW}),z.array(z.string()),z.string()]),g3=z.object({url:z.string().describe("The URL to fetch"),prompt:z.string().min(2).describe("Analysis prompt for the fetched content")}),l4=z.object({requests:z.array(g3).describe("Array of the URLs for the web fetch requests")}),p4=z.object({path:z.string().min(1).describe("The absolute path for the action to be performed on"),old_text:z.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 ${M$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:z.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 ${M$} 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:z.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."),r4=z.object({input:z.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."),gH=z.union([r4,z.string()]),i4=z.object({skill:z.string().min(1).describe("Name of the skill to execute."),args:z.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),n4=z.object({question:z.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:z.array(z.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),a4=z.object({summary:z.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:z.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.
365
365
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
366
- 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 D2($){if($ instanceof Error)return $.message;return String($)}function SH($){if(typeof $.old_text==="string"&&$.old_text.length>q$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${q$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>q$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${q$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class I8 extends Error{timeoutMs;constructor($,W){super($);this.name="TimeoutError",this.timeoutMs=W}}function i1($,W,Z){return Promise.race([$,new Promise((Q,J)=>{setTimeout(()=>J(new I8(Z,W)),W)})])}function u9($){let{path:W,start_line:Z,end_line:Q}=$;if(Z==null&&Q==null)return W;return`${W}:${Z??1}-${Q??"EOF"}`}function bH($){let{start_line:W,end_line:Z}=$;if(W==null||Z==null||W<=Z)return null;return`start_line must be less than or equal to end_line (received start_line: ${W}, end_line: ${Z})`}var Kq=new Set(["start_line","end_line"]);function Fq($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let W=Object.keys($);return W.length>0&&W.every((Z)=>Kq.has(Z))}function PH($){let W=[];for(let Z of $){if(Fq(Z)){let Q=W[W.length-1];if(typeof Q==="string"){W[W.length-1]={path:Q,...Z};continue}if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&"path"in Q&&Object.keys(Z).every((J)=>!(J in Q))){W[W.length-1]={...Q,...Z};continue}}W.push(Z)}return W}function yH($){if(Array.isArray($))return PH($);if($!==null&&typeof $==="object")for(let W of["files","paths"]){let Z=$[W];if(Array.isArray(Z))return{...$,[W]:PH(Z)}}return $}function hH($){let W=Gq(wH,$);if(typeof W==="string")return[W];if(Array.isArray(W))return W;if("commands"in W)return Array.isArray(W.commands)?W.commands:[W.commands];if("command"in W)return"args"in W?[W]:[W.command];if("cmd"in W)return[W.cmd];return[W]}function Aq($){if(typeof $==="string")return $;let W=$.args??[];if(W.length===0)return $.command;let Z=W.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${Z.join(" ")}`}var h3=200;function kH($){let W=Aq($);if(W.length<=h3)return W;let Z=W.length-h3;return`${W.slice(0,h3)} ... [command truncated: ${Z} more chars; full command is in the tool call input]`}var n1=48000;function _2($,W={}){let Z=W.maxChars??48000,Q=W.totalChars??$.length;if($.length<=Z&&Q<=Z)return $;let J=Math.ceil(Z/2),j=Math.max(1,Z-J);return`${$.slice(0,J)}
366
+ 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 f2($){if($ instanceof Error)return $.message;return String($)}function vH($){if(typeof $.old_text==="string"&&$.old_text.length>M$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${M$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>M$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${M$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class g8 extends Error{timeoutMs;constructor($,W){super($);this.name="TimeoutError",this.timeoutMs=W}}function n1($,W,Z){return Promise.race([$,new Promise((Q,J)=>{setTimeout(()=>J(new g8(Z,W)),W)})])}function sW($){let{path:W,start_line:Z,end_line:Q}=$;if(Z==null&&Q==null)return W;return`${W}:${Z??1}-${Q??"EOF"}`}function cH($){let{start_line:W,end_line:Z}=$;if(W==null||Z==null||W<=Z)return null;return`start_line must be less than or equal to end_line (received start_line: ${W}, end_line: ${Z})`}var Lq=new Set(["start_line","end_line"]);function Tq($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let W=Object.keys($);return W.length>0&&W.every((Z)=>Lq.has(Z))}function mH($){let W=[];for(let Z of $){if(Tq(Z)){let Q=W[W.length-1];if(typeof Q==="string"){W[W.length-1]={path:Q,...Z};continue}if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&"path"in Q&&Object.keys(Z).every((J)=>!(J in Q))){W[W.length-1]={...Q,...Z};continue}}W.push(Z)}return W}function uH($){if(Array.isArray($))return mH($);if($!==null&&typeof $==="object")for(let W of["files","paths"]){let Z=$[W];if(Array.isArray(Z))return{...$,[W]:mH(Z)}}return $}function dH($){let W=fq(xH,$);if(typeof W==="string")return[W];if(Array.isArray(W))return W;if("commands"in W)return Array.isArray(W.commands)?W.commands:[W.commands];if("command"in W)return"args"in W?[W]:[W.command];if("cmd"in W)return[W.cmd];return[W]}function Oq($){if(typeof $==="string")return $;let W=$.args??[];if(W.length===0)return $.command;let Z=W.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${Z.join(" ")}`}var m3=200;function lH($){let W=Oq($);if(W.length<=m3)return W;let Z=W.length-m3;return`${W.slice(0,m3)} ... [command truncated: ${Z} more chars; full command is in the tool call input]`}var a1=48000;function L2($,W={}){let Z=W.maxChars??48000,Q=W.totalChars??$.length;if($.length<=Z&&Q<=Z)return $;let J=Math.ceil(Z/2),j=Math.max(1,Z-J);return`${$.slice(0,J)}
367
367
  [... output truncated: ${Q} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
368
- `+$.slice(-j)}var x8=2000,k3=2000,d9=48000,g8=48000;class a1 extends Error{exitCode;output;constructor($,W){super(`Command exited with code ${$}`);this.exitCode=$;this.output=W;this.name="CommandExitError"}}function xH($){let W=Math.ceil($/2),Z=Math.max(1,$-W),Q=new Uq("utf8"),J="",j="",X=0,Y=(V)=>{if(!V)return;X+=V.length;let B=W-J.length;if(B>0){J+=V.slice(0,B),j=(j+V.slice(B)).slice(-Z);return}j=(j+V).slice(-Z)};return{append(V){Y(Q.write(V))},snapshot(){return Y(Q.end()),{text:J+j,totalChars:X,dropped:X>J.length+j.length}}}}function _q($,W,Z,Q,J){return new Promise((j,X)=>{let Y=process.platform==="win32",V=IH($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!Y,windowsHide:!0}),B=V.pid,H=xH(Q),G=xH(Q),K=!1,F=!1,A=(O)=>{if(F)return;F=!0,O()},f=()=>{if(!B)return;if(Y){IH("taskkill",["/pid",String(B),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-B,"SIGKILL")}catch{V.kill("SIGKILL")}},U=(O)=>{K=!0,f(),A(()=>X(O))},_=setTimeout(()=>U(new I8(`Command timed out after ${Z}ms`,Z)),Z),D=()=>U(Error("Command was aborted"));if(W.signal)W.signal.addEventListener("abort",D);let M=()=>{clearTimeout(_),W.signal?.removeEventListener("abort",D)};V.stdout?.on("data",(O)=>{H.append(O)}),V.stderr?.on("data",(O)=>{G.append(O)}),V.on("close",(O)=>{if(M(),K)return;let T=H.snapshot(),L=G.snapshot();if(O!==0){let C=O??1,N=J?T.text+(L.text?`
368
+ `+$.slice(-j)}var m8=2000,v3=2000,tW=48000,v8=48000;class o1 extends Error{exitCode;output;constructor($,W){super(`Command exited with code ${$}`);this.exitCode=$;this.output=W;this.name="CommandExitError"}}function rH($){let W=Math.ceil($/2),Z=Math.max(1,$-W),Q=new zq("utf8"),J="",j="",X=0,Y=(V)=>{if(!V)return;X+=V.length;let B=W-J.length;if(B>0){J+=V.slice(0,B),j=(j+V.slice(B)).slice(-Z);return}j=(j+V).slice(-Z)};return{append(V){Y(Q.write(V))},snapshot(){return Y(Q.end()),{text:J+j,totalChars:X,dropped:X>J.length+j.length}}}}function Rq($,W,Z,Q,J){return new Promise((j,X)=>{let Y=process.platform==="win32",V=pH($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!Y,windowsHide:!0}),B=V.pid,H=rH(Q),G=rH(Q),K=!1,F=!1,A=(O)=>{if(F)return;F=!0,O()},D=()=>{if(!B)return;if(Y){pH("taskkill",["/pid",String(B),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-B,"SIGKILL")}catch{V.kill("SIGKILL")}},U=(O)=>{K=!0,D(),A(()=>X(O))},f=setTimeout(()=>U(new g8(`Command timed out after ${Z}ms`,Z)),Z),_=()=>U(Error("Command was aborted"));if(W.signal)W.signal.addEventListener("abort",_);let R=()=>{clearTimeout(f),W.signal?.removeEventListener("abort",_)};V.stdout?.on("data",(O)=>{H.append(O)}),V.stderr?.on("data",(O)=>{G.append(O)}),V.on("close",(O)=>{if(R(),K)return;let T=H.snapshot(),L=G.snapshot();if(O!==0){let C=O??1,E=J?T.text+(L.text?`
369
369
  [stderr]
370
- ${L.text}`:""):T.text,p=T.dropped||J&&L.dropped,x=J?T.totalChars+L.totalChars:T.totalChars;if(p||N.length>Q)N=_2(N,{maxChars:Q,totalChars:x});let P=N.length>0?`[Command exited with code ${C}]
371
- ${N}`:`[Command exited with code ${C}]`;A(()=>X(new a1(C,P)))}else{let C=J?T.text+(L.text?`
370
+ ${L.text}`:""):T.text,p=T.dropped||J&&L.dropped,x=J?T.totalChars+L.totalChars:T.totalChars;if(p||E.length>Q)E=L2(E,{maxChars:Q,totalChars:x});let P=E.length>0?`[Command exited with code ${C}]
371
+ ${E}`:`[Command exited with code ${C}]`;A(()=>X(new o1(C,P)))}else{let C=J?T.text+(L.text?`
372
372
  [stderr]
373
- ${L.text}`:""):T.text;if(T.dropped||J&&L.dropped||C.length>Q){let p=J?T.totalChars+L.totalChars:T.totalChars;C=_2(C,{maxChars:Q,totalChars:p})}A(()=>j(C))}}),V.on("error",(O)=>{M(),A(()=>X(Error(`Failed to execute command: ${O.message}`)))})})}function L2($={}){let{shell:W=fq(process.platform),timeoutMs:Z=30000,env:Q={},combineOutput:J=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??n1;return(X,Y,V)=>{let B=typeof X!=="string";return _q({executable:B?X.command:W,args:B?X.args??[]:Dq(W,X),cwd:Y,env:Q},V,Z,j,J)}}function gH($,W){let Z=$.metadata?.[W];return typeof Z==="string"?Z:void 0}function Lq($,W){UV(qH($.metadata),{tool_name:"run_commands",effective_timeout_ms:W.effectiveTimeoutMs,timeout_source:W.timeoutSource,command_count:W.commandCount,duration_ms:W.durationMs,ulid:$.sessionId,mode:gH($,"mode"),source:gH($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function Tq($){let W=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return W?.[1]??W?.[2]??W?.[3]}function Oq($){let W=[];for(let Z=0;Z<$.length;Z+=1){let Q=$[Z],J=Tq(Q);if(!J){W.push(Q);continue}let j=$.findIndex((Y,V)=>V>Z&&Y.trim()===J);if(j===-1){W.push(Q);continue}let X=[Q];while(Z<j){Z+=1;let Y=$[Z];X.push(Y)}W.push(X.join(`
374
- `))}return W}function zq($){let W=[],Z=[],Q=()=>{if(Z.length>0)W.push(...Oq(Z)),Z=[]};for(let J of $){if(typeof J==="string"){Z.push(J);continue}Q(),W.push(J)}return Q(),W}async function qq($,W){let{executor:Z,cwd:Q,context:J,timeoutMs:j,timeoutSource:X}=W;return Promise.all($.map(async(Y)=>{let V=Date.now(),B=kH(Y);try{let H=await i1(Z(Y,Q,J),j,`Command timed out after ${j}ms`);return{query:B,result:H,success:!0}}catch(H){if(H instanceof I8)Lq(J,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:X,commandCount:$.length,durationMs:Date.now()-V});if(H instanceof a1)return{query:B,result:H.output,error:H.message,success:!1};let G=D2(H);return{query:B,result:"",error:`Command failed: ${G}`,success:!1}}}))}function I3($,W={}){let Z=W.fileReadTimeoutMs??1e4;return M$({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 on the same file entry as its path. 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 ${x8} lines / ~${Math.round(d9/1024)}k characters; longer files report their total line count, page through them with start_line/end_line on that file's entry. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:o1(m4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(Q,J)=>{let j=R$(RH,yH(Q)),X;if(typeof j==="string")X=[{path:j}];else if(Array.isArray(j))X=j.map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("files"in j)X=(Array.isArray(j.files)?j.files:[j.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in j)X=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((V)=>({path:V}));else if("paths"in j)X=(Array.isArray(j.paths)?j.paths:[j.paths]).map((V)=>typeof V==="string"?{path:V}:V);else X=[j];return Promise.all(X.map(async(Y)=>{let V=bH(Y);if(V)return{query:u9(Y),result:"",error:`Invalid file range: ${V}`,success:!1};try{let B=await i1($(Y,J),Z,`File read timed out after ${Z}ms`);return{query:u9(Y),result:B,success:!0}}catch(B){let H=D2(B);return{query:u9(Y),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function x3($,W={}){let Z=W.searchTimeoutMs??30000,Q=W.cwd??process.cwd();return M$({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(g8/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:o1(v4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(J,j)=>{let X=R$(NH,J),Y=Array.isArray(X)?X:typeof X==="object"?Array.isArray(X.queries)?X.queries:[X.queries]:[X];return Promise.all(Y.map(async(V)=>{try{let B=await i1($(V,Q,j),Z,`Search timed out after ${Z}ms`);return{query:V,result:B,success:!0}}catch(B){let H=D2(B);return{query:V,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}var mH="Use for listing files, checking git status, running builds, executing tests, etc. Commands must be non-interactive. Commands that require follow-up input like pagers should be skipped or used with supported flags/env (e.g. git --no-pager, --non-interactive) to bypass the interaction steps. ";function n4($,W={}){let Z=W.bashTimeoutMs??30000,Q=W.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=W.cwd??process.cwd(),j=process.platform==="win32";return M$({name:"run_commands",description:j?"Run non-interactive shell commands from the root of the workspace in Windows environment. "+mH+`Output beyond ~${Math.round(n1/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Commands run through PowerShell; quote paths and arguments for PowerShell and use ';' to sequence commands. Include multiple commands in the same call when they are independent and safe to run concurrently. When independent reads, searches, or edits are also needed, call those tools in the same response.`:"Run non-interactive shell commands from the root of the workspace. "+mH+`Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands in the same call when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. When independent reads, searches, or edits are also needed, call those tools in the same response. Output beyond ~${Math.round(n1/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:o1(c4),timeoutMs:Z*2,retryable:!1,maxRetries:0,execute:async(X,Y)=>{let V=zq(hH(X));return qq(V,{executor:$,cwd:J,context:Y,timeoutMs:Z,timeoutSource:Q})}})}function g3($,W={}){let Z=W.webFetchTimeoutMs??30000;return M$({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:o1(u4),timeoutMs:Z*2,retryable:!0,maxRetries:2,execute:async(Q,J)=>{let j=R$(u4,Q);return Promise.all(j.requests.map(async(X)=>{try{let Y=await i1($(X.url,X.prompt,J),Z,`Web fetch timed out after ${Z}ms`);return{query:X.url,result:Y,success:!0}}catch(Y){let V=D2(Y);return{query:X.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var Mq=`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:
373
+ ${L.text}`:""):T.text;if(T.dropped||J&&L.dropped||C.length>Q){let p=J?T.totalChars+L.totalChars:T.totalChars;C=L2(C,{maxChars:Q,totalChars:p})}A(()=>j(C))}}),V.on("error",(O)=>{R(),A(()=>X(Error(`Failed to execute command: ${O.message}`)))})})}function T2($={}){let{shell:W=qq(process.platform),timeoutMs:Z=30000,env:Q={},combineOutput:J=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??a1;return(X,Y,V)=>{let B=typeof X!=="string";return Rq({executable:B?X.command:W,args:B?X.args??[]:Mq(W,X),cwd:Y,env:Q},V,Z,j,J)}}function iH($,W){let Z=$.metadata?.[W];return typeof Z==="string"?Z:void 0}function Eq($,W){RV(bH($.metadata),{tool_name:"run_commands",effective_timeout_ms:W.effectiveTimeoutMs,timeout_source:W.timeoutSource,command_count:W.commandCount,duration_ms:W.durationMs,ulid:$.sessionId,mode:iH($,"mode"),source:iH($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function Nq($){let W=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return W?.[1]??W?.[2]??W?.[3]}function wq($){let W=[];for(let Z=0;Z<$.length;Z+=1){let Q=$[Z],J=Nq(Q);if(!J){W.push(Q);continue}let j=$.findIndex((Y,V)=>V>Z&&Y.trim()===J);if(j===-1){W.push(Q);continue}let X=[Q];while(Z<j){Z+=1;let Y=$[Z];X.push(Y)}W.push(X.join(`
374
+ `))}return W}function Cq($){let W=[],Z=[],Q=()=>{if(Z.length>0)W.push(...wq(Z)),Z=[]};for(let J of $){if(typeof J==="string"){Z.push(J);continue}Q(),W.push(J)}return Q(),W}async function Pq($,W){let{executor:Z,cwd:Q,context:J,timeoutMs:j,timeoutSource:X}=W;return Promise.all($.map(async(Y)=>{let V=Date.now(),B=lH(Y);try{let H=await n1(Z(Y,Q,J),j,`Command timed out after ${j}ms`);return{query:B,result:H,success:!0}}catch(H){if(H instanceof g8)Eq(J,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:X,commandCount:$.length,durationMs:Date.now()-V});if(H instanceof o1)return{query:B,result:H.output,error:H.message,success:!1};let G=f2(H);return{query:B,result:"",error:`Command failed: ${G}`,success:!1}}}))}function c3($,W={}){let Z=W.fileReadTimeoutMs??1e4;return R$({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 on the same file entry as its path. 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 ${m8} lines / ~${Math.round(tW/1024)}k characters; longer files report their total line count, page through them with start_line/end_line on that file's entry. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:s1(c4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(Q,J)=>{let j=E$(hH,uH(Q)),X;if(typeof j==="string")X=[{path:j}];else if(Array.isArray(j))X=j.map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("files"in j)X=(Array.isArray(j.files)?j.files:[j.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in j)X=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((V)=>({path:V}));else if("paths"in j)X=(Array.isArray(j.paths)?j.paths:[j.paths]).map((V)=>typeof V==="string"?{path:V}:V);else X=[j];return Promise.all(X.map(async(Y)=>{let V=cH(Y);if(V)return{query:sW(Y),result:"",error:`Invalid file range: ${V}`,success:!1};try{let B=await n1($(Y,J),Z,`File read timed out after ${Z}ms`);return{query:sW(Y),result:B,success:!0}}catch(B){let H=f2(B);return{query:sW(Y),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function u3($,W={}){let Z=W.searchTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({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(v8/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:s1(u4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(J,j)=>{let X=E$(kH,J),Y=Array.isArray(X)?X:typeof X==="object"?Array.isArray(X.queries)?X.queries:[X.queries]:[X];return Promise.all(Y.map(async(V)=>{try{let B=await n1($(V,Q,j),Z,`Search timed out after ${Z}ms`);return{query:V,result:B,success:!0}}catch(B){let H=f2(B);return{query:V,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}var nH="Use for listing files, checking git status, running builds, executing tests, etc. Commands must be non-interactive. Commands that require follow-up input like pagers should be skipped or used with supported flags/env (e.g. git --no-pager, --non-interactive) to bypass the interaction steps. ";function o4($,W={}){let Z=W.bashTimeoutMs??30000,Q=W.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=W.cwd??process.cwd(),j=process.platform==="win32";return R$({name:"run_commands",description:j?"Run non-interactive shell commands from the root of the workspace in Windows environment. "+nH+`Output beyond ~${Math.round(a1/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Commands run through PowerShell; quote paths and arguments for PowerShell and use ';' to sequence commands. Include multiple commands in the same call when they are independent and safe to run concurrently. When independent reads, searches, or edits are also needed, call those tools in the same response.`:"Run non-interactive shell commands from the root of the workspace. "+nH+`Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands in the same call when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. When independent reads, searches, or edits are also needed, call those tools in the same response. Output beyond ~${Math.round(a1/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:s1(d4),timeoutMs:Z*2,retryable:!1,maxRetries:0,execute:async(X,Y)=>{let V=Cq(dH(X));return Pq(V,{executor:$,cwd:J,context:Y,timeoutMs:Z,timeoutSource:Q})}})}function d3($,W={}){let Z=W.webFetchTimeoutMs??30000;return R$({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:s1(l4),timeoutMs:Z*2,retryable:!0,maxRetries:2,execute:async(Q,J)=>{let j=E$(l4,Q);return Promise.all(j.requests.map(async(X)=>{try{let Y=await n1($(X.url,X.prompt,J),Z,`Web fetch timed out after ${Z}ms`);return{query:X.url,result:Y,success:!0}}catch(Y){let V=f2(Y);return{query:X.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var Sq=`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:
375
375
 
376
376
  *** Begin Patch
377
377
  *** Update File: path/to/file.ts
@@ -407,134 +407,134 @@ Example:
407
407
  </div>
408
408
  );
409
409
  }
410
- *** End Patch`;function m3($,W={}){let Z=W.applyPatchTimeoutMs??30000,Q=W.cwd??process.cwd();return M$({name:"apply_patch",description:Mq,inputSchema:o1(l4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=R$(CH,J),Y=typeof X==="string"?X:X.input;try{return{query:"apply_patch",result:await i1($({input:Y},Q,j),Z,`apply_patch timed out after ${Z}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${D2(V)}`,success:!1}}}})}function v3($,W={}){let Z=W.editorTimeoutMs??30000,Q=W.cwd??process.cwd();return M$({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 tool for making small, precise edits to existing files or creating new files over shell commands. If several edits to different files or non-overlapping regions are already known, emit multiple editor tool calls in the same response instead of serializing them across turns.",inputSchema:o1(d4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=R$(d4,J),Y=X.insert_line==null?"edit":"insert",V=SH(X);if(V)return{query:`${Y}:${X.path}`,result:"",error:V,success:!1};try{let B=await i1($(X,Q,j),Z,`Editor operation timed out after ${Z}ms`);return{query:`${Y}:${X.path}`,result:B,success:!0}}catch(B){let H=D2(B);return{query:`${Y}:${X.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function T2($,W={}){let Z=W.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',J=M$({name:"skills",description:Q,inputSchema:o1(p4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(j,X)=>{let Y=R$(p4,j);return i1($(Y.skill,Y.args||void 0,X),Z,`Skills operation timed out after ${Z}ms`)}});return Object.defineProperty(J,"description",{get(){let j=$.configuredSkills?.filter((X)=>!X.disabled).map((X)=>X.name);if(j&&j.length>0)return`${Q} Available skills: ${j.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),J}function c3($){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:o1(r4),retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=R$(r4,W);return $(Q.question,Q.options,Z)}}}function u3($,W={}){let Z=W.submitTimeoutMs??15000;return M$({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:o1(i4),lifecycle:{completesRun:!0},timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let j=R$(i4,Q);return i1($(j.summary,j.verified,J),Z,`submit_and_exit timed out after ${Z}ms`)}})}function N$($){let{executors:W,enableReadFiles:Z=!0,enableSearch:Q=!0,enableBash:J=!0,enableWebFetch:j=!0,enableApplyPatch:X=!1,enableEditor:Y=!0,enableSkills:V=!0,enableAskQuestion:B=!0,enableSubmitAndExit:H=!1,...G}=$,K=[];if(Z&&W.readFile)K.push(I3(W.readFile,G));if(Q&&W.search)K.push(x3(W.search,G));if(J&&W.bash)K.push(n4(W.bash,G));if(j&&W.webFetch)K.push(g3(W.webFetch,G));if(Y&&W.editor)K.push(v3(W.editor,G));else if(X&&W.applyPatch)K.push(m3(W.applyPatch,G));if(V&&W.skills)K.push(T2(W.skills,G));let F=H?W.submit:void 0;if(B&&W.askQuestion&&!F)K.push(c3(W.askQuestion));if(F)K.push(u3(F,G));return K}import*as i0 from"node:fs/promises";import*as n0 from"node:path";var n={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},cH=["%%bash","apply_patch","EOF","```"],O2;((Q)=>{Q.ADD="add";Q.DELETE="delete";Q.UPDATE="update"})(O2||={});class G0 extends Error{constructor($){super($);this.name="DiffError"}}function r0($){let W={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Z)=>W[Z]??Z).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class d3{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,W){this.lines=$;this.currentFiles=W}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(n.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(n.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(n.UPDATE)){this.parseUpdate($.substring(n.UPDATE.length).trim());return}if($?.startsWith(n.DELETE)){this.parseDelete($.substring(n.DELETE.length).trim());return}if($?.startsWith(n.ADD)){this.parseAdd($.substring(n.ADD.length).trim());return}throw new G0(`Unknown line while parsing: ${$}`)}checkDuplicate($,W){if($ in this.patch.actions)throw new G0(`Duplicate ${W} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let W=this.lines[this.index]?.startsWith(n.MOVE)?(this.lines[this.index++]??"").substring(n.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new G0(`Update File Error: Missing File: ${$}`);let Z=this.currentFiles[$]??"",Q=this.parseUpdateFile(Z,$);Q.movePath=W,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,W){let Z={type:"update",chunks:[]},Q=$.split(`
410
+ *** End Patch`;function l3($,W={}){let Z=W.applyPatchTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({name:"apply_patch",description:Sq,inputSchema:s1(r4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=E$(gH,J),Y=typeof X==="string"?X:X.input;try{return{query:"apply_patch",result:await n1($({input:Y},Q,j),Z,`apply_patch timed out after ${Z}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${f2(V)}`,success:!1}}}})}function p3($,W={}){let Z=W.editorTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({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 tool for making small, precise edits to existing files or creating new files over shell commands. If several edits to different files or non-overlapping regions are already known, emit multiple editor tool calls in the same response instead of serializing them across turns.",inputSchema:s1(p4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=E$(p4,J),Y=X.insert_line==null?"edit":"insert",V=vH(X);if(V)return{query:`${Y}:${X.path}`,result:"",error:V,success:!1};try{let B=await n1($(X,Q,j),Z,`Editor operation timed out after ${Z}ms`);return{query:`${Y}:${X.path}`,result:B,success:!0}}catch(B){let H=f2(B);return{query:`${Y}:${X.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function O2($,W={}){let Z=W.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',J=R$({name:"skills",description:Q,inputSchema:s1(i4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(j,X)=>{let Y=E$(i4,j);return n1($(Y.skill,Y.args||void 0,X),Z,`Skills operation timed out after ${Z}ms`)}});return Object.defineProperty(J,"description",{get(){let j=$.configuredSkills?.filter((X)=>!X.disabled).map((X)=>X.name);if(j&&j.length>0)return`${Q} Available skills: ${j.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),J}function r3($){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:s1(n4),retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=E$(n4,W);return $(Q.question,Q.options,Z)}}}function i3($,W={}){let Z=W.submitTimeoutMs??15000;return R$({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:s1(a4),lifecycle:{completesRun:!0},timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let j=E$(a4,Q);return n1($(j.summary,j.verified,J),Z,`submit_and_exit timed out after ${Z}ms`)}})}function N$($){let{executors:W,enableReadFiles:Z=!0,enableSearch:Q=!0,enableBash:J=!0,enableWebFetch:j=!0,enableApplyPatch:X=!1,enableEditor:Y=!0,enableSkills:V=!0,enableAskQuestion:B=!0,enableSubmitAndExit:H=!1,...G}=$,K=[];if(Z&&W.readFile)K.push(c3(W.readFile,G));if(Q&&W.search)K.push(u3(W.search,G));if(J&&W.bash)K.push(o4(W.bash,G));if(j&&W.webFetch)K.push(d3(W.webFetch,G));if(Y&&W.editor)K.push(p3(W.editor,G));else if(X&&W.applyPatch)K.push(l3(W.applyPatch,G));if(V&&W.skills)K.push(O2(W.skills,G));let F=H?W.submit:void 0;if(B&&W.askQuestion&&!F)K.push(r3(W.askQuestion));if(F)K.push(i3(F,G));return K}import*as i0 from"node:fs/promises";import*as n0 from"node:path";var n={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},oH=["%%bash","apply_patch","EOF","```"],z2;((Q)=>{Q.ADD="add";Q.DELETE="delete";Q.UPDATE="update"})(z2||={});class G0 extends Error{constructor($){super($);this.name="DiffError"}}function r0($){let W={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Z)=>W[Z]??Z).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class n3{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,W){this.lines=$;this.currentFiles=W}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(n.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(n.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(n.UPDATE)){this.parseUpdate($.substring(n.UPDATE.length).trim());return}if($?.startsWith(n.DELETE)){this.parseDelete($.substring(n.DELETE.length).trim());return}if($?.startsWith(n.ADD)){this.parseAdd($.substring(n.ADD.length).trim());return}throw new G0(`Unknown line while parsing: ${$}`)}checkDuplicate($,W){if($ in this.patch.actions)throw new G0(`Duplicate ${W} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let W=this.lines[this.index]?.startsWith(n.MOVE)?(this.lines[this.index++]??"").substring(n.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new G0(`Update File Error: Missing File: ${$}`);let Z=this.currentFiles[$]??"",Q=this.parseUpdateFile(Z,$);Q.movePath=W,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,W){let Z={type:"update",chunks:[]},Q=$.split(`
411
411
  `),J=0,j=[n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(!j.some((X)=>this.lines[this.index]?.startsWith(X.trim()))){let X=this.lines[this.index],Y=X?.startsWith("@@ ")?X.substring(3):void 0;if(Y!==void 0||(X==="@@"?X:void 0)!==void 0)this.index++;else if(J!==0)throw new G0(`Invalid Line:
412
- ${this.lines[this.index]}`);if(Y?.trim()){let U=r0(Y.trim());for(let _=J;_<Q.length;_++){let D=Q[_];if(D&&(r0(D)===U||r0(D.trim())===U)){if(J=_+1,r0(D.trim())===U&&r0(D)!==U)this.fuzz++;break}}}let[B,H,G,K]=Eq(this.lines,this.index),[F,A,f]=Nq(Q,B,J,K);if(F===-1){let U=B.join(`
413
- `);this.addWarning({path:this.currentPath||W,chunkIndex:Z.chunks.length,message:`Could not find matching context (similarity: ${f.toFixed(2)}). Chunk skipped.`,context:U.length>200?`${U.substring(0,200)}...`:U}),this.index=G}else{this.fuzz+=A;for(let U of H)U.origIndex+=F,Z.chunks.push(U);J=F+B.length,this.index=G}}return Z}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new G0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new G0(`Add File Error: File already exists: ${$}`);this.index++;let W=[],Z=[n.END,n.UPDATE,n.DELETE,n.ADD];while(this.hasMoreLines()&&!Z.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new G0(`Invalid Add File line (missing '+'): ${Q}`);W.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:W.join(`
414
- `),chunks:[]}}}function vH($,W){let Z=$.length>W.length?$:W,Q=$.length>W.length?W:$;if(Z.length===0)return 1;let J=Rq(Q,Z);return(Z.length-J)/Z.length}function Rq($,W){let Z=W.length+1,Q=$.length+1,J=Array(Z*Q).fill(0),j=(Y,V)=>J[Y*Q+V]??0,X=(Y,V,B)=>{J[Y*Q+V]=B};for(let Y=0;Y<=W.length;Y++)X(Y,0,Y);for(let Y=0;Y<=$.length;Y++)X(0,Y,Y);for(let Y=1;Y<=W.length;Y++)for(let V=1;V<=$.length;V++)if(W[Y-1]===$[V-1])X(Y,V,j(Y-1,V-1));else X(Y,V,1+Math.min(j(Y-1,V-1),j(Y,V-1),j(Y-1,V)));return j(W.length,$.length)}function Nq($,W,Z,Q){if(W.length===0)return[Z,0,1];let J=0,j=(X)=>{let Y=r0(W.join(`
412
+ ${this.lines[this.index]}`);if(Y?.trim()){let U=r0(Y.trim());for(let f=J;f<Q.length;f++){let _=Q[f];if(_&&(r0(_)===U||r0(_.trim())===U)){if(J=f+1,r0(_.trim())===U&&r0(_)!==U)this.fuzz++;break}}}let[B,H,G,K]=hq(this.lines,this.index),[F,A,D]=yq(Q,B,J,K);if(F===-1){let U=B.join(`
413
+ `);this.addWarning({path:this.currentPath||W,chunkIndex:Z.chunks.length,message:`Could not find matching context (similarity: ${D.toFixed(2)}). Chunk skipped.`,context:U.length>200?`${U.substring(0,200)}...`:U}),this.index=G}else{this.fuzz+=A;for(let U of H)U.origIndex+=F,Z.chunks.push(U);J=F+B.length,this.index=G}}return Z}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new G0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new G0(`Add File Error: File already exists: ${$}`);this.index++;let W=[],Z=[n.END,n.UPDATE,n.DELETE,n.ADD];while(this.hasMoreLines()&&!Z.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new G0(`Invalid Add File line (missing '+'): ${Q}`);W.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:W.join(`
414
+ `),chunks:[]}}}function aH($,W){let Z=$.length>W.length?$:W,Q=$.length>W.length?W:$;if(Z.length===0)return 1;let J=bq(Q,Z);return(Z.length-J)/Z.length}function bq($,W){let Z=W.length+1,Q=$.length+1,J=Array(Z*Q).fill(0),j=(Y,V)=>J[Y*Q+V]??0,X=(Y,V,B)=>{J[Y*Q+V]=B};for(let Y=0;Y<=W.length;Y++)X(Y,0,Y);for(let Y=0;Y<=$.length;Y++)X(0,Y,Y);for(let Y=1;Y<=W.length;Y++)for(let V=1;V<=$.length;V++)if(W[Y-1]===$[V-1])X(Y,V,j(Y-1,V-1));else X(Y,V,1+Math.min(j(Y-1,V-1),j(Y,V-1),j(Y-1,V)));return j(W.length,$.length)}function yq($,W,Z,Q){if(W.length===0)return[Z,0,1];let J=0,j=(X)=>{let Y=r0(W.join(`
415
415
  `));for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).join(`
416
- `));if(H===Y)return[B,0,1];let G=vH(H,Y);if(G>J)J=G}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trimEnd()).join(`
416
+ `));if(H===Y)return[B,0,1];let G=aH(H,Y);if(G>J)J=G}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trimEnd()).join(`
417
417
  `)),G=r0(W.map((K)=>K.trimEnd()).join(`
418
418
  `));if(H===G)return[B,1,1]}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trim()).join(`
419
419
  `)),G=r0(W.map((K)=>K.trim()).join(`
420
420
  `));if(H===G)return[B,100,1]}let V=0.66;for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).join(`
421
- `)),G=vH(H,Y);if(G>=V)return[B,1000,G];if(G>J)J=G}return[-1,0,J]};if(Q){let[X,Y,V]=j($.length-W.length);if(X!==-1)return[X,Y,V];return[X,Y,V]=j(Z),[X,Y+1e4,V]}return j(Z)}function Eq($,W){let Z=W,Q=[],J=[],j=[],X=[],Y="keep",V=["@@",n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(Z<$.length){let B=$[Z];if(!B||V.some((K)=>B.startsWith(K.trim())))break;if(B==="***")break;if(B.startsWith("***"))throw new G0(`Invalid line: ${B}`);Z++;let H=Y,G=B;if(G[0]==="+")Y="add";else if(G[0]==="-")Y="delete";else if(G[0]===" ")Y="keep";else Y="keep",G=` ${G}`;if(G=G.slice(1),Y==="keep"&&H!==Y){if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});J=[],j=[]}if(Y==="delete")J.push(G),Q.push(G);else if(Y==="add")j.push(G);else Q.push(G)}if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});if(Z<$.length&&$[Z]===n.END_FILE)return Z++,[Q,X,Z,!0];return[Q,X,Z,!1]}function l3($,W,Z){let Q=n0.isAbsolute(W),J=Q?n0.normalize(W):n0.resolve($,W);if(!Z||Q)return J;let j=n0.relative($,J);if(j.startsWith("..")||n0.isAbsolute(j))throw new G0(`Path must stay within cwd: ${W}`);return J}function wq($){return $.split(`
422
- `).map((W)=>W.replace(/\r$/,""))}function uH($){if($.trim()==="")return!1;return cH.some((W)=>$.startsWith(W))}function Cq($){let W=0,Z=$.length;while(W<Z&&uH($[W]??""))W++;while(Z>W&&uH($[Z-1]??""))Z--;return $.slice(W,Z)}function Pq($){let W=wq($),Z=W.findIndex((X)=>X.startsWith(n.BEGIN)),Q=-1;for(let X=W.length-1;X>=0;X--)if(W[X]?.startsWith(n.END)){Q=X;break}if(Z!==-1||Q!==-1){if(Z===-1||Q===-1||Q<Z)throw new G0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:W.slice(Z,Q+1)}}let J=Cq(W);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[n.BEGIN,...J,n.END]}}function Sq($,W){let Z=new Set;for(let Q of $)for(let J of W)if(Q.startsWith(J)){Z.add(Q.substring(J.length).trim());break}return[...Z]}function bq($,W,Z){if(W.length===0)return $;let Q=$.split(`
421
+ `)),G=aH(H,Y);if(G>=V)return[B,1000,G];if(G>J)J=G}return[-1,0,J]};if(Q){let[X,Y,V]=j($.length-W.length);if(X!==-1)return[X,Y,V];return[X,Y,V]=j(Z),[X,Y+1e4,V]}return j(Z)}function hq($,W){let Z=W,Q=[],J=[],j=[],X=[],Y="keep",V=["@@",n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(Z<$.length){let B=$[Z];if(!B||V.some((K)=>B.startsWith(K.trim())))break;if(B==="***")break;if(B.startsWith("***"))throw new G0(`Invalid line: ${B}`);Z++;let H=Y,G=B;if(G[0]==="+")Y="add";else if(G[0]==="-")Y="delete";else if(G[0]===" ")Y="keep";else Y="keep",G=` ${G}`;if(G=G.slice(1),Y==="keep"&&H!==Y){if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});J=[],j=[]}if(Y==="delete")J.push(G),Q.push(G);else if(Y==="add")j.push(G);else Q.push(G)}if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});if(Z<$.length&&$[Z]===n.END_FILE)return Z++,[Q,X,Z,!0];return[Q,X,Z,!1]}function a3($,W,Z){let Q=n0.isAbsolute(W),J=Q?n0.normalize(W):n0.resolve($,W);if(!Z||Q)return J;let j=n0.relative($,J);if(j.startsWith("..")||n0.isAbsolute(j))throw new G0(`Path must stay within cwd: ${W}`);return J}function kq($){return $.split(`
422
+ `).map((W)=>W.replace(/\r$/,""))}function sH($){if($.trim()==="")return!1;return oH.some((W)=>$.startsWith(W))}function Iq($){let W=0,Z=$.length;while(W<Z&&sH($[W]??""))W++;while(Z>W&&sH($[Z-1]??""))Z--;return $.slice(W,Z)}function xq($){let W=kq($),Z=W.findIndex((X)=>X.startsWith(n.BEGIN)),Q=-1;for(let X=W.length-1;X>=0;X--)if(W[X]?.startsWith(n.END)){Q=X;break}if(Z!==-1||Q!==-1){if(Z===-1||Q===-1||Q<Z)throw new G0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:W.slice(Z,Q+1)}}let J=Iq(W);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[n.BEGIN,...J,n.END]}}function gq($,W){let Z=new Set;for(let Q of $)for(let J of W)if(Q.startsWith(J)){Z.add(Q.substring(J.length).trim());break}return[...Z]}function mq($,W,Z){if(W.length===0)return $;let Q=$.split(`
423
423
  `),J=[],j=0;for(let X of W){if(X.origIndex>Q.length)throw new G0(`${Z}: chunk.origIndex ${X.origIndex} > lines.length ${Q.length}`);if(j>X.origIndex)throw new G0(`${Z}: currentIndex ${j} > chunk.origIndex ${X.origIndex}`);J.push(...Q.slice(j,X.origIndex)),J.push(...X.insLines),j=X.origIndex+X.delLines.length}return J.push(...Q.slice(j)),J.join(`
424
- `)}async function yq($,W,Z,Q){let J=Sq($,[n.UPDATE,n.DELETE]),j={};for(let X of J){let Y=l3(W,X,Q),V;try{V=await i0.readFile(Y,Z)}catch{throw new G0(`File not found: ${X}`)}j[X]=V.replace(/\r\n/g,`
425
- `)}return j}function hq($,W){let Z={};for(let[Q,J]of Object.entries($.actions))switch(J.type){case"delete":Z[Q]={type:"delete",oldContent:W[Q]};break;case"add":if(J.newFile===void 0)throw new G0("ADD action without file content");Z[Q]={type:"add",newContent:J.newFile};break;case"update":Z[Q]={type:"update",oldContent:W[Q],newContent:bq(W[Q]??"",J.chunks,Q),movePath:J.movePath};break}return Z}function kq($){let W=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Z of $){let Q=Z.chunkIndex===void 0?"unknown":String(Z.chunkIndex+1);if(W.push(`${Z.path}: hunk ${Q}: ${Z.message}`),Z.context)W.push(`Context:
424
+ `)}async function vq($,W,Z,Q){let J=gq($,[n.UPDATE,n.DELETE]),j={};for(let X of J){let Y=a3(W,X,Q),V;try{V=await i0.readFile(Y,Z)}catch{throw new G0(`File not found: ${X}`)}j[X]=V.replace(/\r\n/g,`
425
+ `)}return j}function cq($,W){let Z={};for(let[Q,J]of Object.entries($.actions))switch(J.type){case"delete":Z[Q]={type:"delete",oldContent:W[Q]};break;case"add":if(J.newFile===void 0)throw new G0("ADD action without file content");Z[Q]={type:"add",newContent:J.newFile};break;case"update":Z[Q]={type:"update",oldContent:W[Q],newContent:mq(W[Q]??"",J.chunks,Q),movePath:J.movePath};break}return Z}function uq($){let W=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Z of $){let Q=Z.chunkIndex===void 0?"unknown":String(Z.chunkIndex+1);if(W.push(`${Z.path}: hunk ${Q}: ${Z.message}`),Z.context)W.push(`Context:
426
426
  ${Z.context}`)}return W.join(`
427
- `)}async function Iq($,W,Z,Q){let J=[];for(let[j,X]of Object.entries($)){let Y=l3(W,j,Q);switch(X.type){case"delete":await i0.rm(Y,{force:!0}),J.push(`${j}: [deleted]`);break;case"add":if(X.newContent===void 0)throw new G0(`Cannot create ${j} with no content`);await i0.mkdir(n0.dirname(Y),{recursive:!0}),await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break;case"update":{if(X.newContent===void 0)throw new G0(`UPDATE change for ${j} has no new content`);if(X.movePath){let V=l3(W,X.movePath,Q);await i0.mkdir(n0.dirname(V),{recursive:!0}),await i0.writeFile(V,X.newContent,{encoding:Z}),await i0.rm(Y,{force:!0}),J.push(`${j} -> ${X.movePath}`)}else await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break}}}return J}async function m8($,W,Z={}){let{encoding:Q="utf-8",restrictToCwd:J=!0}=Z,j=Pq($),X=await yq(j.lines,W,Q,J),Y=new d3(j.lines,X),{patch:V,fuzz:B}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new G0(kq(V.warnings));return{changes:hq(V,X),fuzz:B}}function z2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0}=$;return async(Q,J,j)=>{let{changes:X,fuzz:Y}=await m8(Q.input,J,{encoding:W,restrictToCwd:Z}),V=await Iq(X,J,W,Z),B=["Successfully applied patch to the following files:"];for(let H of V)B.push(H);if(Y>0)B.push(`Note: Patch applied with fuzz factor ${Y}`);return B.join(`
428
- `)}}import*as F1 from"node:fs/promises";import*as K1 from"node:path";function xq($,W,Z){let Q=K1.isAbsolute(W),J=Q?K1.normalize(W):K1.resolve($,W);if(!Z)return J;if(Q)return J;let j=K1.relative($,J);if(j.startsWith("..")||K1.isAbsolute(j))throw Error(`Path must stay within cwd: ${W}`);return J}function gq($,W){if(W.length===0)return 0;return $.split(W).length-1}function mq($,W,Z){let Q=$.split(`
427
+ `)}async function dq($,W,Z,Q){let J=[];for(let[j,X]of Object.entries($)){let Y=a3(W,j,Q);switch(X.type){case"delete":await i0.rm(Y,{force:!0}),J.push(`${j}: [deleted]`);break;case"add":if(X.newContent===void 0)throw new G0(`Cannot create ${j} with no content`);await i0.mkdir(n0.dirname(Y),{recursive:!0}),await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break;case"update":{if(X.newContent===void 0)throw new G0(`UPDATE change for ${j} has no new content`);if(X.movePath){let V=a3(W,X.movePath,Q);await i0.mkdir(n0.dirname(V),{recursive:!0}),await i0.writeFile(V,X.newContent,{encoding:Z}),await i0.rm(Y,{force:!0}),J.push(`${j} -> ${X.movePath}`)}else await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break}}}return J}async function c8($,W,Z={}){let{encoding:Q="utf-8",restrictToCwd:J=!0}=Z,j=xq($),X=await vq(j.lines,W,Q,J),Y=new n3(j.lines,X),{patch:V,fuzz:B}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new G0(uq(V.warnings));return{changes:cq(V,X),fuzz:B}}function q2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0}=$;return async(Q,J,j)=>{let{changes:X,fuzz:Y}=await c8(Q.input,J,{encoding:W,restrictToCwd:Z}),V=await dq(X,J,W,Z),B=["Successfully applied patch to the following files:"];for(let H of V)B.push(H);if(Y>0)B.push(`Note: Patch applied with fuzz factor ${Y}`);return B.join(`
428
+ `)}}import*as F1 from"node:fs/promises";import*as K1 from"node:path";function lq($,W,Z){let Q=K1.isAbsolute(W),J=Q?K1.normalize(W):K1.resolve($,W);if(!Z)return J;if(Q)return J;let j=K1.relative($,J);if(j.startsWith("..")||K1.isAbsolute(j))throw Error(`Path must stay within cwd: ${W}`);return J}function pq($,W){if(W.length===0)return 0;return $.split(W).length-1}function rq($,W,Z){let Q=$.split(`
429
429
  `),J=W.split(`
430
- `),j=0;while(j<Q.length&&j<J.length&&Q[j]===J[j])j++;let X=Q.length,Y=J.length;while(X>j&&Y>j&&Q[X-1]===J[Y-1])X--,Y--;let V=X-j,B=Y-j,H=V,G=B;if(V+B>Z)H=Math.min(V,Math.max(Math.ceil(Z/2),Z-B)),G=Math.min(B,Z-H);let K=["```diff"];for(let f=j;f<j+H;f++)K.push(`-${f+1}: ${Q[f]}`);for(let f=j;f<j+G;f++)K.push(`+${f+1}: ${J[f]}`);let F=V-H,A=B-G;if(F>0||A>0)K.push(`... diff truncated (${F} more removed, ${A} more added lines) ...`);return K.push("```"),K.join(`
431
- `)}async function vq($,W,Z){return await F1.mkdir(K1.dirname($),{recursive:!0}),await F1.writeFile($,W,{encoding:Z}),`File created successfully at: ${$}`}async function cq($){try{return await F1.access($),!0}catch{return!1}}async function uq($,W,Z,Q,J){let j=await F1.readFile($,Q),X=gq(j,W);if(X===0)throw Error(`No replacement performed: text not found in ${$}.`);if(X>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let Y=j.replace(W,Z??"");await F1.writeFile($,Y,{encoding:Q});let V=mq(j,Y,J);return`Edited ${$}
432
- ${V}`}async function dq($,W,Z,Q){let j=(await F1.readFile($,Q)).split(`
430
+ `),j=0;while(j<Q.length&&j<J.length&&Q[j]===J[j])j++;let X=Q.length,Y=J.length;while(X>j&&Y>j&&Q[X-1]===J[Y-1])X--,Y--;let V=X-j,B=Y-j,H=V,G=B;if(V+B>Z)H=Math.min(V,Math.max(Math.ceil(Z/2),Z-B)),G=Math.min(B,Z-H);let K=["```diff"];for(let D=j;D<j+H;D++)K.push(`-${D+1}: ${Q[D]}`);for(let D=j;D<j+G;D++)K.push(`+${D+1}: ${J[D]}`);let F=V-H,A=B-G;if(F>0||A>0)K.push(`... diff truncated (${F} more removed, ${A} more added lines) ...`);return K.push("```"),K.join(`
431
+ `)}async function iq($,W,Z){return await F1.mkdir(K1.dirname($),{recursive:!0}),await F1.writeFile($,W,{encoding:Z}),`File created successfully at: ${$}`}async function nq($){try{return await F1.access($),!0}catch{return!1}}async function aq($,W,Z,Q,J){let j=await F1.readFile($,Q),X=pq(j,W);if(X===0)throw Error(`No replacement performed: text not found in ${$}.`);if(X>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let Y=j.replace(W,Z??"");await F1.writeFile($,Y,{encoding:Q});let V=rq(j,Y,J);return`Edited ${$}
432
+ ${V}`}async function oq($,W,Z,Q){let j=(await F1.readFile($,Q)).split(`
433
433
  `),X=j.length+1;if(W<1||W>X)throw Error(`Invalid insert_line: ${W}. insert_line must be a positive one-based boundary line in the range 1-${X}. Use ${X} to append at EOF.`);let Y=W-1;return j.splice(Y,0,...Z.split(`
434
434
  `)),await F1.writeFile($,j.join(`
435
- `),{encoding:Q}),`Inserted content at line ${W} in ${$}.`}function q2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0,maxDiffLines:Q=200}=$;return async(J,j,X)=>{let Y=xq(j,J.path,Z);if(J.insert_line!=null)return dq(Y,J.insert_line,J.new_text,W);if(!await cq(Y))return vq(Y,J.new_text,W);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return uq(Y,J.old_text,J.new_text,W,Q)}}import{createReadStream as lq}from"node:fs";import*as l9 from"node:fs/promises";import*as E$ from"node:path";import{createInterface as pq}from"node:readline";import{resolveExistingFilePath as rq}from"@cline/shared/storage";var iq=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),nq={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},dH=1e8,aq=50000;function lH($){let{reason:W}=$;if(W instanceof Error)return W;if(W!==void 0)return Error(String(W));return Error("File read was aborted")}async function oq($,W,Z,Q,J,j){if(j?.aborted)throw lH(j);let X=Math.max(Q??1,1),Y=J??Number.POSITIVE_INFINITY,V=Number.isFinite(Y),B=V?Y:X+aq-1,H=[],G=0,K=0,F=!1,A=!1,f=Number.isFinite(Y)?Math.min(Y,X+x8-1):X+x8-1,U=Z?String(f).length+3:0,_=lq($,{encoding:W}),D=pq({input:_,crlfDelay:Number.POSITIVE_INFINITY}),M=j?()=>_.destroy(lH(j)):void 0;if(j&&M)j.addEventListener("abort",M,{once:!0});try{for await(let p of D){if(K+=1,K>Y){K=Y;break}if(!V&&F&&K>=B){A=!0;break}if(K<X||F)continue;if(H.length>=x8){F=!0;continue}let x=p;if(x.length>k3)x=`${x.slice(0,k3)} [line truncated]`;let P=G+x.length+U+1;if(P>d9&&H.length>0){F=!0;continue}H.push({lineNumber:K,text:x}),G=P}}finally{if(j&&M)j.removeEventListener("abort",M);D.close(),_.destroy()}let O=String(H[H.length-1]?.lineNumber??K).length,T=H.map(({lineNumber:p,text:x})=>Z?`${String(p).padStart(O," ")} | ${x}`:x).join(`
436
- `),L=H[H.length-1]?.lineNumber;if(L===void 0)return T;let C=Math.min(Y,K);if(L>=C)return T;let N=A?`${K}+ lines`:C;return`${T}
437
-
438
- [Showing lines ${X}-${L} of ${N}. Use start_line/end_line to read other sections.]`}function a4($={}){let{maxFileSizeBytes:W,encoding:Z,includeLineNumbers:Q}={...nq,...$};return async(J,j)=>{let{path:X,start_line:Y,end_line:V}=J,B=E$.isAbsolute(X)?E$.normalize(X):E$.resolve(process.cwd(),X),H=rq(B)??B,G=E$.extname(H).toLowerCase(),K=iq.get(G),F=await l9.stat(H);if(!F.isFile())throw Error(`Path is not a file: ${H}`);if(K){if(F.size>W)throw Error(`Image file too large: ${F.size} bytes (max: ${W} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await l9.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>dH)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${dH} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return oq(H,Z,Q,Y,V,j.signal)}}import{spawn as tH}from"node:child_process";import*as eH from"node:fs/promises";import*as i9 from"node:path";var oH={};w(oH,{prewarmFileIndex:()=>r9,getFileIndex:()=>s1,enrichPromptWithMentions:()=>c8});import{spawn as sq}from"node:child_process";import{readdir as tq}from"node:fs/promises";import r3 from"node:path";import{isMainThread as iH,parentPort as pH,Worker as eq}from"node:worker_threads";var $M=15000,WM=600000,ZM=1000,QM=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function rH($){let W=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return W==="EACCES"||W==="EPERM"||W==="ENOENT"}var v8=new Map;function JM(){if(!iH)return!1;return!0}function jM($){if(v8.size<=1)return;for(let[W,Z]of v8.entries()){if(Z.pending)continue;if($-Z.lastAccessedAt>WM)v8.delete(W)}}function XM($,W){return r3.relative($,W).split(r3.sep).join("/")}async function YM($){let Z=(await new Promise((Q,J)=>{let j=sq("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),X="",Y="";j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",(V)=>{Y+=V.toString()}),j.on("error",J),j.on("close",(V)=>{if(V===0){Q(X);return}J(Error(Y||`rg exited with code ${V}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(Z)}async function nH($,W,Z){let Q;try{Q=await tq(W,{withFileTypes:!0})}catch(J){if(rH(J))return;throw J}for(let J of Q){let j=r3.join(W,J.name);if(J.isDirectory()){if(QM.has(J.name))continue;try{await nH($,j,Z)}catch(X){if(rH(X))continue;throw X}continue}if(J.isFile())Z.add(XM($,j))}}async function VM($){let W=new Set;return await nH($,$,W),W}async function p9($){try{return await YM($)}catch{return VM($)}}function BM(){if(iH||!pH)return;let $=pH;$.on("message",(W)=>{if(W.type!=="index")return;p9(W.cwd).then((Z)=>{let Q={type:"indexResult",requestId:W.requestId,files:Array.from(Z)};$.postMessage(Q)}).catch((Z)=>{let Q={type:"indexResult",requestId:W.requestId,error:Z instanceof Error?Z.message:"Failed to build file index"};$.postMessage(Q)})})}class aH{worker=new eq(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let W=this.pending.get($.requestId);if(!W)return;if(this.pending.delete($.requestId),$.error){W.reject(Error($.error));return}W.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 W=++this.nextRequestId,Z=new Promise((J,j)=>{let X=setTimeout(()=>{this.pending.delete(W),J(null)},ZM);X.unref(),this.pending.set(W,{resolve:(Y)=>{clearTimeout(X),J(Y)},reject:(Y)=>{clearTimeout(X),j(Y)}})}),Q={type:"index",requestId:W,cwd:$};return this.worker.postMessage(Q),Z}flushPending($){for(let[W,Z]of this.pending.entries())Z.reject($),this.pending.delete(W)}}BM();var p3;function HM(){if(!JM())return null;if(p3===void 0)p3=new aH;return p3}async function GM($){let W=HM();if(!W)return p9($);try{let Z=await W.requestIndex($);if(Z===null)return p9($);return new Set(Z)}catch{return p9($)}}async function s1($,W={}){let Z=W.ttlMs??$M,Q=Date.now();jM(Q);let J=v8.get($);if(J&&Z>0&&Q-J.lastBuiltAt<=Z&&J.files.size>0)return J.lastAccessedAt=Q,J.files;if(J?.pending)return J.lastAccessedAt=Q,J.pending;let j=GM($).then((X)=>{return v8.set($,{files:X,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),X});return v8.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:Q,pending:j}),j}async function r9($,W={}){await s1($,{...W,ttlMs:0})}import{stat as KM}from"node:fs/promises";import M2 from"node:path";var FM=/[),.:;!?`'"]+$/,AM=/^[(`'"]+/;function UM($){let W=$.matchAll(/(^|[\s])@([^\s]+)/g),Z=[];for(let Q of W){let J=(Q[2]??"").trim();if(J.length===0)continue;let j=J.replace(AM,"").replace(FM,"");if(j.length===0||j.includes("@"))continue;Z.push(j)}return Array.from(new Set(Z))}function fM($,W){let Z=$.replace(/\\/g,"/"),Q=M2.isAbsolute(Z)?M2.resolve(Z):M2.resolve(W,Z),J=M2.relative(W,Q);if(J.startsWith("..")||M2.isAbsolute(J))return;return J.split(M2.sep).join("/")}async function c8($,W,Z={}){let Q=UM($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:j,maxTotalBytes:X}=Z,Y=await s1(W,{ttlMs:Z.ttlMs}),V=[],B=[],H=[],G=0;for(let K of Q){if(J&&H.length>=J){B.push(K);continue}let F=fM(K,W);if(!F||!Y.has(F)){B.push(K);continue}if(!j||!X){V.push(F);continue}let A=M2.join(W,F);try{if(!(await KM(A)).isFile()){B.push(K);continue}let U=G+j;if(U>X){B.push(K);continue}G=U,V.push(F)}catch{B.push(K)}}return{prompt:$,mentions:Q,matchedFiles:V,ignoredMentions:B}}var DM=["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"],_M=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],R2=null;function LM(){if(R2!==null)return Promise.resolve(R2);return new Promise(($)=>{let W=tH("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});W.on("close",(Z)=>{R2=Z===0,$(R2)}),W.on("error",()=>{R2=!1,$(!1)}),setTimeout(()=>{if(!W.killed)W.kill("SIGTERM");if(R2===null)R2=!1,$(!1)},1000)})}function TM($,W,Z,Q,J=5000,j){return new Promise((X)=>{let Y=tH("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:W,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",B=!1,H=()=>{if(!Y.killed)Y.kill("SIGTERM")},G=setTimeout(()=>{if(!B)B=!0,H(),X(null)},J),K=(F)=>{if(!B)B=!0,clearTimeout(G),H(),X(F)};if(j?.aborted){H(),X(null);return}j?.addEventListener("abort",()=>{K(null)}),Y.stdout.on("data",(F)=>{V+=F.toString()}),Y.stderr.on("data",()=>{}),Y.on("close",(F)=>{if(F===0||F===1){try{let A=[],f=V.split(`
439
- `).filter((U)=>U.trim());for(let U of f){if(A.length>=Z)break;let _=JSON.parse(U);if(_.type==="match"){let D=_.data,M=[];if(_.data.submatches&&_.data.submatches.length>0){let O=_.data.submatches[0];A.push({file:D.path.text,line:D.line_number,column:(O?.start??0)+1,match:O?.match?.text??"",context:M})}}else if(_.type==="context"&&A.length>0){let D=A[A.length-1],M=_.data.line_number===D.line?">":" ";D.context.push(`${M} ${_.data.line_number}: ${_.data.lines?.text??_.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),Y.on("error",()=>{K(null)})})}function OM($,W,Z,Q){let J=$.split("/"),j=J[J.length-1]??"";if(J.length-1>Q)return!1;for(let V=0;V<J.length-1;V++)if(W.has(J[V]??""))return!1;let Y=i9.posix.extname(j).slice(1).toLowerCase();return Z.has(Y)||!Y&&!j.startsWith(".")}function o4($={}){let{includeExtensions:W=DM,excludeDirs:Z=_M,maxResults:Q=100,contextLines:J=2,maxDepth:j=20}=$,X=new Set(Z),Y=new Set(W.map((V)=>V.toLowerCase()));return async(V,B,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let G=await LM(),K=null;if(G)K=await TM(V,B,Q,J,5000,H.signal);if(K){let D=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let M of K)D.push(`${M.file}:${M.line}:${M.column}`),D.push(...M.context),D.push("");if(K.length>=Q)D.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return sH(D.join(`
440
- `))}let F;try{F=new RegExp(V,"gim")}catch(D){throw Error(`Invalid regex pattern: ${V}. ${D instanceof Error?D.message:""}`)}let A=[],f=0,U=await s1(B);for(let D of U){if(H.signal?.aborted)throw Error("Search operation aborted");if(!OM(D,X,Y,j))continue;if(A.length>=Q)break;f++;let M=i9.join(B,D);try{let T=(await eH.readFile(M,"utf-8")).split(`
441
- `);for(let L=0;L<T.length;L++){let C=T[L];F.lastIndex=0;let N=F.exec(C);while(N!==null){if(A.length>=Q)break;let p=Math.max(0,L-J),x=Math.min(T.length-1,L+J),P=[];for(let r=p;r<=x;r++){let d=r===L?">":" ";P.push(`${d} ${r+1}: ${T[r]}`)}if(A.push({file:D,line:L+1,column:N.index+1,match:N[0],context:P}),N.index===F.lastIndex)F.lastIndex++;N=F.exec(C)}}}catch{}}if(A.length===0)return`No results found for pattern: ${V}
442
- Searched ${f} files.`;let _=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${V}`,`Searched ${f} files.`,""];for(let D of A)_.push(`${D.file}:${D.line}:${D.column}`),_.push(...D.context),_.push("");if(A.length>=Q)_.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return sH(_.join(`
443
- `))}}function sH($){if($.length<=g8)return $;let W=Math.ceil(g8/2),Z=Math.max(1,g8-W);return`${$.slice(0,W)}
435
+ `),{encoding:Q}),`Inserted content at line ${W} in ${$}.`}function M2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0,maxDiffLines:Q=200}=$;return async(J,j,X)=>{let Y=lq(j,J.path,Z);if(J.insert_line!=null)return oq(Y,J.insert_line,J.new_text,W);if(!await nq(Y))return iq(Y,J.new_text,W);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return aq(Y,J.old_text,J.new_text,W,Q)}}import{createReadStream as sq}from"node:fs";import*as eW from"node:fs/promises";import*as w$ from"node:path";import{createInterface as tq}from"node:readline";import{resolveExistingFilePath as eq}from"@cline/shared/storage";var $M=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),WM={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},tH=1e8,ZM=50000;function eH($){let{reason:W}=$;if(W instanceof Error)return W;if(W!==void 0)return Error(String(W));return Error("File read was aborted")}async function QM($,W,Z,Q,J,j){if(j?.aborted)throw eH(j);let X=Math.max(Q??1,1),Y=J??Number.POSITIVE_INFINITY,V=Number.isFinite(Y),B=V?Y:X+ZM-1,H=[],G=0,K=0,F=!1,A=!1,D=Number.isFinite(Y)?Math.min(Y,X+m8-1):X+m8-1,U=Z?String(D).length+3:0,f=sq($,{encoding:W}),_=tq({input:f,crlfDelay:Number.POSITIVE_INFINITY}),R=j?()=>f.destroy(eH(j)):void 0;if(j&&R)j.addEventListener("abort",R,{once:!0});try{for await(let p of _){if(K+=1,K>Y){K=Y;break}if(!V&&F&&K>=B){A=!0;break}if(K<X||F)continue;if(H.length>=m8){F=!0;continue}let x=p;if(x.length>v3)x=`${x.slice(0,v3)} [line truncated]`;let P=G+x.length+U+1;if(P>tW&&H.length>0){F=!0;continue}H.push({lineNumber:K,text:x}),G=P}}finally{if(j&&R)j.removeEventListener("abort",R);_.close(),f.destroy()}let O=String(H[H.length-1]?.lineNumber??K).length,T=H.map(({lineNumber:p,text:x})=>Z?`${String(p).padStart(O," ")} | ${x}`:x).join(`
436
+ `),L=H[H.length-1]?.lineNumber;if(L===void 0)return T;let C=Math.min(Y,K);if(L>=C)return T;let E=A?`${K}+ lines`:C;return`${T}
437
+
438
+ [Showing lines ${X}-${L} of ${E}. Use start_line/end_line to read other sections.]`}function s4($={}){let{maxFileSizeBytes:W,encoding:Z,includeLineNumbers:Q}={...WM,...$};return async(J,j)=>{let{path:X,start_line:Y,end_line:V}=J,B=w$.isAbsolute(X)?w$.normalize(X):w$.resolve(process.cwd(),X),H=eq(B)??B,G=w$.extname(H).toLowerCase(),K=$M.get(G),F=await eW.stat(H);if(!F.isFile())throw Error(`Path is not a file: ${H}`);if(K){if(F.size>W)throw Error(`Image file too large: ${F.size} bytes (max: ${W} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await eW.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>tH)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${tH} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return QM(H,Z,Q,Y,V,j.signal)}}import{spawn as YG}from"node:child_process";import*as VG from"node:fs/promises";import*as ZZ from"node:path";var jG={};w(jG,{prewarmFileIndex:()=>WZ,getFileIndex:()=>t1,enrichPromptWithMentions:()=>d8});import{spawn as JM}from"node:child_process";import{readdir as jM}from"node:fs/promises";import s3 from"node:path";import{isMainThread as ZG,parentPort as $G,Worker as XM}from"node:worker_threads";var YM=15000,VM=600000,BM=1000,HM=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function WG($){let W=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return W==="EACCES"||W==="EPERM"||W==="ENOENT"}var u8=new Map;function GM(){if(!ZG)return!1;return!0}function KM($){if(u8.size<=1)return;for(let[W,Z]of u8.entries()){if(Z.pending)continue;if($-Z.lastAccessedAt>VM)u8.delete(W)}}function FM($,W){return s3.relative($,W).split(s3.sep).join("/")}async function AM($){let Z=(await new Promise((Q,J)=>{let j=JM("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),X="",Y="";j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",(V)=>{Y+=V.toString()}),j.on("error",J),j.on("close",(V)=>{if(V===0){Q(X);return}J(Error(Y||`rg exited with code ${V}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(Z)}async function QG($,W,Z){let Q;try{Q=await jM(W,{withFileTypes:!0})}catch(J){if(WG(J))return;throw J}for(let J of Q){let j=s3.join(W,J.name);if(J.isDirectory()){if(HM.has(J.name))continue;try{await QG($,j,Z)}catch(X){if(WG(X))continue;throw X}continue}if(J.isFile())Z.add(FM($,j))}}async function UM($){let W=new Set;return await QG($,$,W),W}async function $Z($){try{return await AM($)}catch{return UM($)}}function DM(){if(ZG||!$G)return;let $=$G;$.on("message",(W)=>{if(W.type!=="index")return;$Z(W.cwd).then((Z)=>{let Q={type:"indexResult",requestId:W.requestId,files:Array.from(Z)};$.postMessage(Q)}).catch((Z)=>{let Q={type:"indexResult",requestId:W.requestId,error:Z instanceof Error?Z.message:"Failed to build file index"};$.postMessage(Q)})})}class JG{worker=new XM(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let W=this.pending.get($.requestId);if(!W)return;if(this.pending.delete($.requestId),$.error){W.reject(Error($.error));return}W.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 W=++this.nextRequestId,Z=new Promise((J,j)=>{let X=setTimeout(()=>{this.pending.delete(W),J(null)},BM);X.unref(),this.pending.set(W,{resolve:(Y)=>{clearTimeout(X),J(Y)},reject:(Y)=>{clearTimeout(X),j(Y)}})}),Q={type:"index",requestId:W,cwd:$};return this.worker.postMessage(Q),Z}flushPending($){for(let[W,Z]of this.pending.entries())Z.reject($),this.pending.delete(W)}}DM();var o3;function _M(){if(!GM())return null;if(o3===void 0)o3=new JG;return o3}async function fM($){let W=_M();if(!W)return $Z($);try{let Z=await W.requestIndex($);if(Z===null)return $Z($);return new Set(Z)}catch{return $Z($)}}async function t1($,W={}){let Z=W.ttlMs??YM,Q=Date.now();KM(Q);let J=u8.get($);if(J&&Z>0&&Q-J.lastBuiltAt<=Z&&J.files.size>0)return J.lastAccessedAt=Q,J.files;if(J?.pending)return J.lastAccessedAt=Q,J.pending;let j=fM($).then((X)=>{return u8.set($,{files:X,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),X});return u8.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:Q,pending:j}),j}async function WZ($,W={}){await t1($,{...W,ttlMs:0})}import{stat as LM}from"node:fs/promises";import R2 from"node:path";var TM=/[),.:;!?`'"]+$/,OM=/^[(`'"]+/;function zM($){let W=$.matchAll(/(^|[\s])@([^\s]+)/g),Z=[];for(let Q of W){let J=(Q[2]??"").trim();if(J.length===0)continue;let j=J.replace(OM,"").replace(TM,"");if(j.length===0||j.includes("@"))continue;Z.push(j)}return Array.from(new Set(Z))}function qM($,W){let Z=$.replace(/\\/g,"/"),Q=R2.isAbsolute(Z)?R2.resolve(Z):R2.resolve(W,Z),J=R2.relative(W,Q);if(J.startsWith("..")||R2.isAbsolute(J))return;return J.split(R2.sep).join("/")}async function d8($,W,Z={}){let Q=zM($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:j,maxTotalBytes:X}=Z,Y=await t1(W,{ttlMs:Z.ttlMs}),V=[],B=[],H=[],G=0;for(let K of Q){if(J&&H.length>=J){B.push(K);continue}let F=qM(K,W);if(!F||!Y.has(F)){B.push(K);continue}if(!j||!X){V.push(F);continue}let A=R2.join(W,F);try{if(!(await LM(A)).isFile()){B.push(K);continue}let U=G+j;if(U>X){B.push(K);continue}G=U,V.push(F)}catch{B.push(K)}}return{prompt:$,mentions:Q,matchedFiles:V,ignoredMentions:B}}var MM=["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"],RM=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],E2=null;function EM(){if(E2!==null)return Promise.resolve(E2);return new Promise(($)=>{let W=YG("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});W.on("close",(Z)=>{E2=Z===0,$(E2)}),W.on("error",()=>{E2=!1,$(!1)}),setTimeout(()=>{if(!W.killed)W.kill("SIGTERM");if(E2===null)E2=!1,$(!1)},1000)})}function NM($,W,Z,Q,J=5000,j){return new Promise((X)=>{let Y=YG("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:W,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",B=!1,H=()=>{if(!Y.killed)Y.kill("SIGTERM")},G=setTimeout(()=>{if(!B)B=!0,H(),X(null)},J),K=(F)=>{if(!B)B=!0,clearTimeout(G),H(),X(F)};if(j?.aborted){H(),X(null);return}j?.addEventListener("abort",()=>{K(null)}),Y.stdout.on("data",(F)=>{V+=F.toString()}),Y.stderr.on("data",()=>{}),Y.on("close",(F)=>{if(F===0||F===1){try{let A=[],D=V.split(`
439
+ `).filter((U)=>U.trim());for(let U of D){if(A.length>=Z)break;let f=JSON.parse(U);if(f.type==="match"){let _=f.data,R=[];if(f.data.submatches&&f.data.submatches.length>0){let O=f.data.submatches[0];A.push({file:_.path.text,line:_.line_number,column:(O?.start??0)+1,match:O?.match?.text??"",context:R})}}else if(f.type==="context"&&A.length>0){let _=A[A.length-1],R=f.data.line_number===_.line?">":" ";_.context.push(`${R} ${f.data.line_number}: ${f.data.lines?.text??f.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),Y.on("error",()=>{K(null)})})}function wM($,W,Z,Q){let J=$.split("/"),j=J[J.length-1]??"";if(J.length-1>Q)return!1;for(let V=0;V<J.length-1;V++)if(W.has(J[V]??""))return!1;let Y=ZZ.posix.extname(j).slice(1).toLowerCase();return Z.has(Y)||!Y&&!j.startsWith(".")}function t4($={}){let{includeExtensions:W=MM,excludeDirs:Z=RM,maxResults:Q=100,contextLines:J=2,maxDepth:j=20}=$,X=new Set(Z),Y=new Set(W.map((V)=>V.toLowerCase()));return async(V,B,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let G=await EM(),K=null;if(G)K=await NM(V,B,Q,J,5000,H.signal);if(K){let _=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let R of K)_.push(`${R.file}:${R.line}:${R.column}`),_.push(...R.context),_.push("");if(K.length>=Q)_.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return XG(_.join(`
440
+ `))}let F;try{F=new RegExp(V,"gim")}catch(_){throw Error(`Invalid regex pattern: ${V}. ${_ instanceof Error?_.message:""}`)}let A=[],D=0,U=await t1(B);for(let _ of U){if(H.signal?.aborted)throw Error("Search operation aborted");if(!wM(_,X,Y,j))continue;if(A.length>=Q)break;D++;let R=ZZ.join(B,_);try{let T=(await VG.readFile(R,"utf-8")).split(`
441
+ `);for(let L=0;L<T.length;L++){let C=T[L];F.lastIndex=0;let E=F.exec(C);while(E!==null){if(A.length>=Q)break;let p=Math.max(0,L-J),x=Math.min(T.length-1,L+J),P=[];for(let r=p;r<=x;r++){let d=r===L?">":" ";P.push(`${d} ${r+1}: ${T[r]}`)}if(A.push({file:_,line:L+1,column:E.index+1,match:E[0],context:P}),E.index===F.lastIndex)F.lastIndex++;E=F.exec(C)}}}catch{}}if(A.length===0)return`No results found for pattern: ${V}
442
+ Searched ${D} files.`;let f=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${V}`,`Searched ${D} files.`,""];for(let _ of A)f.push(`${_.file}:${_.line}:${_.column}`),f.push(..._.context),f.push("");if(A.length>=Q)f.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return XG(f.join(`
443
+ `))}}function XG($){if($.length<=v8)return $;let W=Math.ceil(v8/2),Z=Math.max(1,v8-W);return`${$.slice(0,W)}
444
444
  [... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
445
- `+$.slice(-Z)}function zM($){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,`
445
+ `+$.slice(-Z)}function CM($){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,`
446
446
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(W,Z)=>String.fromCharCode(parseInt(Z,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
447
447
  `).replace(/\n{3,}/g,`
448
448
 
449
- `).trim()}function s4($={}){let{timeoutMs:W=30000,maxResponseBytes:Z=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:j=!0}=$;return async(X,Y,V)=>{let B;try{B=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}if(!["http:","https:"].includes(B.protocol))throw Error(`Invalid protocol: ${B.protocol}. Only http and https are supported.`);let H=new AbortController,G=setTimeout(()=>H.abort(),W),K;if(V.signal)K=()=>H.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(X,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...J},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(G),!j&&F.status>=300&&F.status<400)return`Redirect to: ${F.headers.get("location")}`;if(!F.ok)throw Error(`HTTP ${F.status}: ${F.statusText}`);let A=F.headers.get("content-type")||"",f=F.body?.getReader();if(!f)throw Error("Failed to read response body");let U=[],_=0;while(!0){let{done:C,value:N}=await f.read();if(C)break;if(_+=N.length,_>Z)throw f.cancel(),Error(`Response too large: exceeded ${Z} bytes`);U.push(N)}let D=new Uint8Array(_),M=0;for(let C of U)D.set(C,M),M+=C.length;let O=new TextDecoder("utf-8").decode(D),T;if(A.includes("text/html")||A.includes("application/xhtml"))T=zM(O);else if(A.includes("application/json"))try{let C=JSON.parse(O);T=JSON.stringify(C,null,2)}catch{T=O}else T=O;let L=[`URL: ${X}`,`Content-Type: ${A}`,`Size: ${_} bytes`,"","--- Content ---",T.slice(0,50000)];if(T.length>50000)L.push(`
449
+ `).trim()}function e4($={}){let{timeoutMs:W=30000,maxResponseBytes:Z=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:j=!0}=$;return async(X,Y,V)=>{let B;try{B=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}if(!["http:","https:"].includes(B.protocol))throw Error(`Invalid protocol: ${B.protocol}. Only http and https are supported.`);let H=new AbortController,G=setTimeout(()=>H.abort(),W),K;if(V.signal)K=()=>H.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(X,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...J},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(G),!j&&F.status>=300&&F.status<400)return`Redirect to: ${F.headers.get("location")}`;if(!F.ok)throw Error(`HTTP ${F.status}: ${F.statusText}`);let A=F.headers.get("content-type")||"",D=F.body?.getReader();if(!D)throw Error("Failed to read response body");let U=[],f=0;while(!0){let{done:C,value:E}=await D.read();if(C)break;if(f+=E.length,f>Z)throw D.cancel(),Error(`Response too large: exceeded ${Z} bytes`);U.push(E)}let _=new Uint8Array(f),R=0;for(let C of U)_.set(C,R),R+=C.length;let O=new TextDecoder("utf-8").decode(_),T;if(A.includes("text/html")||A.includes("application/xhtml"))T=CM(O);else if(A.includes("application/json"))try{let C=JSON.parse(O);T=JSON.stringify(C,null,2)}catch{T=O}else T=O;let L=[`URL: ${X}`,`Content-Type: ${A}`,`Size: ${f} bytes`,"","--- Content ---",T.slice(0,50000)];if(T.length>50000)L.push(`
450
450
  [Content truncated: showing first 50000 of ${T.length} characters]`);return L.push("","--- Analysis Request ---",`Prompt: ${Y}`),L.join(`
451
- `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${W}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function t4($={}){return L2($)}function u8($={}){return{readFile:a4($.fileRead),search:o4($.search),bash:t4($.bash),webFetch:s4($.webFetch),applyPatch:z2($.applyPatch),editor:q2($.editor)}}var qM={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"},d8=[{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 $G($,W){if(!W||W.length===0)return!0;let Z=$.toLowerCase();return W.some((Q)=>Z.includes(Q.toLowerCase()))}function MM($,W,Z,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return $G(W,$.providerIdIncludes)&&$G(Z,$.modelIdIncludes)}function l8($,W,Z,Q){if(!Q||Q.length===0)return{};let J=new Map;for(let X of Q){if(!MM(X,$,W,Z))continue;for(let Y of X.disableTools??[])J.set(Y,!1);for(let Y of X.enableTools??[])J.set(Y,!0)}let j={};for(let[X,Y]of J.entries())j[qM[X]]=Y;return j}var a0={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 t1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function n9($){if($!=="yolo")return{};let W={enabled:!0,autoApprove:!0},Z={"*":W};for(let Q of U$)Z[Q]=W;return Z}function a9($,W){let Z=a0[$],{enableSpawnAgent:Q,enableAgentTeams:J,...j}=Z;return N$({...j,...W})}import{createTool as vR,zodToJsonSchema as cR}from"@cline/shared";import{z as jJ}from"zod";X1();import{createAgentRuntime as wR}from"@cline/agents";import{createContributionRegistry as CR,mergeModelOptions as OG}from"@cline/shared";import{createGateway as hM,createHandlerAsync as kM,hasRegisteredHandler as IM,MODEL_COLLECTIONS_BY_PROVIDER_ID as xM,normalizeProviderId as gM}from"@cline/llms";import{EMPTY_CONTENT_TEXT as RM}from"@cline/shared";function NM($){let W=wM($.content),Z=[],Q=$.id??SM(),J=0,j=[],X=()=>{if(j.length===0)return;let Y=J===0?Q:`${Q}_part_${J}`;J+=1,Z.push({id:Y,role:$.role,content:j.map(CM),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:WG($.metrics)}),j=[]};if(W.length===0)return Z.push({id:Q,role:$.role,content:[{type:"text",text:RM}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:WG($.metrics)}),Z;for(let Y of W){if(Y.type!=="tool_result"){j.push(Y);continue}X(),Z.push({id:`${Q}_tool_${Y.tool_use_id}`,role:"tool",content:[QG(Y)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return X(),Z}function o9($){return $.flatMap(NM)}function EM($){let W=$.content.map(JG).filter((Z)=>Z!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:W,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:PM($.metrics)}}function p8($){return $.map(EM)}function s9($){let W=[];for(let Z of $){let Q=Z.content.map(JG).filter((X)=>X!==void 0),J=Z.role==="tool"?"user":Z.role,j=W[W.length-1];if(J==="user"&&Q.length>0&&Q.every((X)=>X.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((X)=>X.type==="tool_result")){j.content.push(...Q);continue}W.push({role:J,content:Q})}return W}function wM($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function CM($){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 QG($)}}function QG($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function JG($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let W=$.metadata;return{type:"thinking",thinking:$.text,signature:W?.signature,details:W?.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 W=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:W?.thoughtSignature??W?.signature}}case"tool-result":{let W=$.output,Z=typeof W==="string"?W:Array.isArray(W)?W:JSON.stringify(W);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Z,is_error:$.isError}}}}function WG($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function PM($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var ZG=0;function SM(){return ZG+=1,`msg_${Date.now().toString(36)}_${ZG.toString(36)}`}function bM($){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 W=$.tool_call.function,Z=W.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??W.id,toolName:W.name,inputText:typeof Z==="string"?Z:void 0,input:typeof Z==="string"?void 0:Z,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,reasoningTokenCount:$.thoughtsTokenCount,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:yM($),error:$.error}];default:return[]}}function yM($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function jG($){return{async*stream(W){let Z=!1,Q=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(W.signal);let j=s9(W.messages),X=W.tools.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}));for await(let Y of J.createMessage(W.systemPrompt??"",j,X))for(let V of bM(Y)){if(V.type==="finish")Z=!0;else if(V.type==="tool-call-delta")Q=!0;yield V}if(!Z)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(J){if(!Z)yield{type:"finish",reason:W.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function mM($){let W=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));return Object.keys(W).length>0?W:void 0}function vM($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function cM($){let W={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(vM($))Object.assign(W,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(W,{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 Z=$.gcp?.region??$.region;Object.assign(W,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Z,region:Z})}if($.providerId==="sapaicore")Object.assign(W,$.sap);return mM(W)}function i3($){let W=$.providerConfig;if(W?.knownModels)return W.knownModels;if($.knownModels)return $.knownModels;return xM[$.providerId]?.models??void 0}function uM($){if(!$?.length)return;let W=new Set;for(let Z of $)switch(Z){case"tools":case"reasoning":case"prompt-cache":case"images":W.add(Z);break;case"structured_output":W.add("structured-output");break;default:W.add("text")}return W.add("text"),[...W]}function dM($,W){return{id:$,name:W.name??$,description:W.description,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxOutputTokens:W.maxTokens,capabilities:uM(W.capabilities),metadata:{family:W.family,pricing:W.pricing,status:W.status,releaseDate:W.releaseDate}}}function XG($,W,Z){let Q=$.providerConfig,J=Q?.providerId===$.providerId?Q:void 0,j={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:i3($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:W,extensionContext:$.extensionContext};if(IM(gM(j.providerId)))return jG(()=>kM(j));return hM({fetch:j.fetch,providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,fetch:j.fetch,options:cM(j),models:j.knownModels?Object.entries(j.knownModels).map(([X,Y])=>dM(X,Y)):void 0}],logger:W,telemetry:Z??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens})}import{createMediaBudgetState as lM,IMAGE_OMITTED_PLACEHOLDER as YG,normalizeUserInput as VG,resolveMediaBudget as pM,validateAndReserveImageMedia as rM}from"@cline/shared";var iM=8000,nM=50000,aM=6000000,oM=200000,sM=12000,tM=65536,$5=2000,BG=40000,eM=8,n3={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},$R=new Set(["read","read_files"]),N2="[outdated - see the latest file content]",HG="Tool execution was interrupted before a result was produced.",GG=($)=>`
451
+ `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${W}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function $5($={}){return T2($)}function l8($={}){return{readFile:s4($.fileRead),search:t4($.search),bash:$5($.bash),webFetch:e4($.webFetch),applyPatch:q2($.applyPatch),editor:M2($.editor)}}var PM={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"},p8=[{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 BG($,W){if(!W||W.length===0)return!0;let Z=$.toLowerCase();return W.some((Q)=>Z.includes(Q.toLowerCase()))}function SM($,W,Z,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return BG(W,$.providerIdIncludes)&&BG(Z,$.modelIdIncludes)}function r8($,W,Z,Q){if(!Q||Q.length===0)return{};let J=new Map;for(let X of Q){if(!SM(X,$,W,Z))continue;for(let Y of X.disableTools??[])J.set(Y,!1);for(let Y of X.enableTools??[])J.set(Y,!0)}let j={};for(let[X,Y]of J.entries())j[PM[X]]=Y;return j}var a0={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 e1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function QZ($){if($!=="yolo")return{};let W={enabled:!0,autoApprove:!0},Z={"*":W};for(let Q of D$)Z[Q]=W;return Z}function JZ($,W){let Z=a0[$],{enableSpawnAgent:Q,enableAgentTeams:J,...j}=Z;return N$({...j,...W})}import{createTool as nR,zodToJsonSchema as aR}from"@cline/shared";import{z as HJ}from"zod";X1();import{createAgentRuntime as IR}from"@cline/agents";import{createContributionRegistry as xR,mergeModelOptions as PG}from"@cline/shared";import{createGateway as cM,createHandlerAsync as uM,hasRegisteredHandler as dM,MODEL_COLLECTIONS_BY_PROVIDER_ID as lM,normalizeProviderId as pM}from"@cline/llms";import{EMPTY_CONTENT_TEXT as bM}from"@cline/shared";function yM($){let W=kM($.content),Z=[],Q=$.id??gM(),J=0,j=[],X=()=>{if(j.length===0)return;let Y=J===0?Q:`${Q}_part_${J}`;J+=1,Z.push({id:Y,role:$.role,content:j.map(IM),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:HG($.metrics)}),j=[]};if(W.length===0)return Z.push({id:Q,role:$.role,content:[{type:"text",text:bM}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:HG($.metrics)}),Z;for(let Y of W){if(Y.type!=="tool_result"){j.push(Y);continue}X(),Z.push({id:`${Q}_tool_${Y.tool_use_id}`,role:"tool",content:[KG(Y)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return X(),Z}function jZ($){return $.flatMap(yM)}function hM($){let W=$.content.map(FG).filter((Z)=>Z!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:W,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:xM($.metrics)}}function i8($){return $.map(hM)}function XZ($){let W=[];for(let Z of $){let Q=Z.content.map(FG).filter((X)=>X!==void 0),J=Z.role==="tool"?"user":Z.role,j=W[W.length-1];if(J==="user"&&Q.length>0&&Q.every((X)=>X.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((X)=>X.type==="tool_result")){j.content.push(...Q);continue}W.push({role:J,content:Q})}return W}function kM($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function IM($){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 KG($)}}function KG($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function FG($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let W=$.metadata;return{type:"thinking",thinking:$.text,signature:W?.signature,details:W?.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 W=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:W?.thoughtSignature??W?.signature}}case"tool-result":{let W=$.output,Z=typeof W==="string"?W:Array.isArray(W)?W:JSON.stringify(W);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Z,is_error:$.isError}}}}function HG($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function xM($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var GG=0;function gM(){return GG+=1,`msg_${Date.now().toString(36)}_${GG.toString(36)}`}function mM($){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 W=$.tool_call.function,Z=W.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??W.id,toolName:W.name,inputText:typeof Z==="string"?Z:void 0,input:typeof Z==="string"?void 0:Z,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,reasoningTokenCount:$.thoughtsTokenCount,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:vM($),error:$.error}];default:return[]}}function vM($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function AG($){return{async*stream(W){let Z=!1,Q=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(W.signal);let j=XZ(W.messages),X=W.tools.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}));for await(let Y of J.createMessage(W.systemPrompt??"",j,X))for(let V of mM(Y)){if(V.type==="finish")Z=!0;else if(V.type==="tool-call-delta")Q=!0;yield V}if(!Z)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(J){if(!Z)yield{type:"finish",reason:W.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function rM($){let W=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));return Object.keys(W).length>0?W:void 0}function iM($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function nM($){let W={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(iM($))Object.assign(W,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(W,{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 Z=$.gcp?.region??$.region;Object.assign(W,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Z,region:Z})}if($.providerId==="sapaicore")Object.assign(W,$.sap);return rM(W)}function aM($){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):void 0}function t3($){let W=$.providerConfig,Z=W?.knownModels?W.knownModels:$.knownModels??lM[$.providerId]?.models??void 0,Q=aM(W?.maxInputTokens),J=W?.modelInfo&&W.modelInfo.id===$.modelId?W.modelInfo:void 0;if(Q===void 0&&!J)return Z;return{...Z??{},[$.modelId]:{...Z?.[$.modelId],...Q!==void 0?{contextWindow:Q,maxInputTokens:Q}:{},...J,id:$.modelId}}}function oM($){if(!$?.length)return;let W=new Set;for(let Z of $)switch(Z){case"tools":case"reasoning":case"prompt-cache":case"images":W.add(Z);break;case"structured_output":W.add("structured-output");break;default:W.add("text")}return W.add("text"),[...W]}function sM($,W){return{id:$,name:W.name??$,description:W.description,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxOutputTokens:W.maxTokens,capabilities:oM(W.capabilities),metadata:{family:W.family,pricing:W.pricing,status:W.status,releaseDate:W.releaseDate}}}function UG($,W,Z){let Q=$.providerConfig,J=Q?.providerId===$.providerId?Q:void 0,j={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:t3($),maxOutputTokens:$.maxTokensPerTurn,temperature:$.temperature,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:W,extensionContext:$.extensionContext};if(dM(pM(j.providerId)))return AG(()=>uM(j));return cM({fetch:j.fetch,providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,timeoutMs:j.timeoutMs,fetch:j.fetch,options:nM(j),models:j.knownModels?Object.entries(j.knownModels).map(([X,Y])=>sM(X,Y)):void 0}],logger:W,telemetry:Z??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens,temperature:j.temperature})}import{createMediaBudgetState as tM,IMAGE_OMITTED_PLACEHOLDER as DG,normalizeUserInput as _G,resolveMediaBudget as eM,validateAndReserveImageMedia as $R}from"@cline/shared";var WR=8000,ZR=50000,QR=6000000,JR=200000,jR=12000,XR=65536,Z5=2000,fG=40000,YR=8,e3={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},VR=new Set(["read","read_files"]),N2="[outdated - see the latest file content]",LG="Tool execution was interrupted before a result was produced.",TG=($)=>`
452
452
 
453
453
  ...[truncated ${$} chars]...
454
454
 
455
- `,W5=($)=>`
455
+ `,Q5=($)=>`
456
456
 
457
457
  ...[truncated ${$} chars to fit provider request budget]...
458
458
 
459
- `,WR=($)=>`
459
+ `,BR=($)=>`
460
460
 
461
461
  ...[assistant text truncated: omitted ${$} chars]...
462
462
 
463
- `,KG=($)=>`
463
+ `,OG=($)=>`
464
464
 
465
465
  ...[assistant text truncated: omitted ${$} chars to fit provider request budget]...
466
466
 
467
- `,ZR=($)=>`
467
+ `,HR=($)=>`
468
468
 
469
469
  ...[assistant text truncated: omitted ${$} chars due to repeated tool-call markup]...
470
470
 
471
- `;function UG($=process.env){return{maxToolResultChars:AG($[n3.maxToolResultChars]),maxTotalTextBytes:AG($[n3.maxTotalTextBytes]),minOutdatedRewriteBytes:JR($[n3.minOutdatedRewriteBytes])}}class o3{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor($={}){this.maxToolResultChars=e4($.maxToolResultChars,iM),this.maxFileContentChars=e4($.maxFileContentChars,nM),this.maxTotalTextBytes=e4($.maxTotalTextBytes,aM),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=e4($.maxAssistantTextChars,oM),this.maxAssistantToolMarkupChars=e4($.maxAssistantToolMarkupChars,sM),this.minOutdatedRewriteBytes=jR($.minOutdatedRewriteBytes,tM)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Z=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let Y=VG(J.content);if(Y!==J.content)return{...J,content:Y}}if(J.role==="assistant"&&typeof J.content==="string"){let Y=this.truncateAssistantText(J.content);if(Y!==J.content)return{...J,content:Y}}return J}let j=!1,X=J.content.map((Y)=>{let V=this.transformBlock(Y,J.role);if(V!==Y)j=!0;return V});return j?{...J,content:X}:J}),Q=this.applyMediaBudget(Z);return this.truncateToTotalTextBudget(Q)}transformBlock($,W){if(W==="user"&&$.type==="text"&&typeof $.text==="string"){let J=VG($.text);if(J!==$.text)return{...$,text:J};return $}if(W==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=r8($.content,this.maxFileContentChars,GG);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Z=this.resolveToolName($),Q=$.content;if(this.isReadTool(Z)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let X=this.getReadLocators($).filter((Y)=>J.has(this.toReadLocatorKey(Y))&&this.isOutdatedReadLocator(Y,$.tool_use_id));if(X.length>0)Q=this.replaceOutdatedReadContent(Q,X)}}return Q=this.truncateToolResultContent(Q),Q===$.content?$:{...$,content:Q}}reindex($){let W=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!W)this.resetIndexes();for(let Z=this.indexedMessageCount;Z<$.length;Z++){let Q=$[Z];if(!Array.isArray(Q.content))continue;for(let J=0;J<Q.content.length;J++){let j=Q.content[J];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Z}:${J}`);else if(j.type==="tool_use"){let X=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,X),this.isReadTool(X)){let Y=this.extractLocatorsFromReadToolInput(j.input);if(Y.length>0)this.readLocatorsByToolUseIdCache.set(j.id,Y)}}else if(j.type==="tool_result"){let X=this.resolveToolName(j);if(!this.isReadTool(X)||j.is_error===!0)continue;let Y=this.getReadLocators(j);for(let V of Y)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),j.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let W=new Map,Z=new Set,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result"||j.is_error===!0)continue;let X=this.resolveToolName(j);if(!this.isReadTool(X))continue;Z.add(j.tool_use_id);let Y=this.committedOutdatedRewrites.get(j.tool_use_id),V=new Set,B=new Set;for(let G of this.getReadLocators(j)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,j.tool_use_id))continue;if(B.add(K),!Y?.has(K))V.add(K)}if(Y){for(let G of Y)if(!B.has(G))Y.delete(G);if(Y.size===0)this.committedOutdatedRewrites.delete(j.tool_use_id)}if(V.size===0)continue;let H=W.get(j.tool_use_id);if(!H)H=new Set,W.set(j.tool_use_id,H);for(let G of V)H.add(G);Q+=this.estimateOutdatedReclaimBytes(j.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Z.has(J))this.committedOutdatedRewrites.delete(J);if(W.size===0||Q<this.minOutdatedRewriteBytes)return;for(let[J,j]of W){let X=this.committedOutdatedRewrites.get(J);if(!X)X=new Set,this.committedOutdatedRewrites.set(J,X);for(let Y of j)X.add(Y)}}estimateOutdatedReclaimBytes($,W){let Z=this.extractReadLocatorsFromToolResultContent($),Q=Z.length>0&&Z.every((V)=>W.has(this.toReadLocatorKey(V))),J=(V)=>{let B;try{B=JSON.parse(V)}catch{return Q||Z.length===0?j0(this.truncateMiddle(V)):0}let H=Array.isArray(B)?B:[B],G=0;for(let K of H){let F=this.extractLocatorFromResultEntry(K);if(F&&W.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let j=new Set(W),X=0;for(let V of $)if(V.type==="text")X+=this.countOutdatedImageEntries(V.text,j);let Y=0;for(let V of $)if(V.type==="text")Y+=J(V.text);else if(V.type==="image"){if(X>0)X-=1,Y+=j0(V.data)}else if(w$(V)){let B=this.extractLocatorFromResultEntry(V);if(B&&W.has(this.toReadLocatorKey(B)))Y+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(W.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))Y+=j0(this.truncateMiddle(V.content))}return Y}providerBoundEntryBytes($){let W=this.truncateNestedStrings($);return j0(JSON.stringify(W))}addMissingToolResults($){let W=this.collectToolResultIds($),Z=[],Q=new Map,J=!1,j=()=>{if(Q.size===0)return;X(this.createMissingToolResultMessage(Q)),Q.clear(),J=!0},X=(Y)=>{let V=Z.at(-1);if(this.shouldMergeUserAfterToolResults(V,Y)){Z[Z.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(Y.content)]},J=!0;return}Z.push(Y)};for(let Y of $){if(this.isToolResultOnlyMessage(Y)){if(X(this.appendMissingToolResults(Y,Q)),Q.size>0)Q.clear(),J=!0;continue}if(Array.isArray(Y.content)){let V=Y.content.filter((H)=>H.type==="tool_result"),B=Y.content.filter((H)=>H.type!=="tool_result");if(V.length>0){let H=this.appendMissingToolResults({...Y,role:"user",content:V},Q);if(X(H),Q.size>0)Q.clear();J=!0}if(B.length>0||V.length===0){if(V.length===0)j();let H=V.length>0?{...Y,content:B}:Y;if(X(H),H.role==="assistant")this.trackMissingToolCalls(H,W,Q)}continue}j(),X(Y)}return j(),J?Z:$}appendMissingToolResults($,W){if(W.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(W)]}}shouldMergeUserAfterToolResults($,W){return $?.role==="user"&&W.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(W.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}return W}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}trackMissingToolCalls($,W,Z){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||W.has(Q.id))continue;Z.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([W,Z])=>({type:"tool_result",tool_use_id:W,name:Z,content:[{type:"text",text:this.formatMissingToolResultText(Z)}],is_error:!0}))}formatMissingToolResultText($){return $?`${HG} Tool: ${$}.`:HG}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 W=$,Z=this.readResultLocatorCache.get(W);if(Z===void 0)Z=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(W,Z);if(Z.length>0)return Z;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let W=$,Z=[],Q=this.extractLocatorFromReadRequest(W);if(Q)Z.push(Q);if(Array.isArray(W.files))for(let J of W.files){let j=this.extractLocatorFromReadRequest(J);if(j)Z.push(j)}if(Array.isArray(W.file_paths)){for(let J of W.file_paths)if(typeof J==="string"&&J.length>0)Z.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Z)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let W=[];for(let Z of $){if(Z.type==="text"){W.push(...this.tryParseReadLocators(Z.text));continue}if(w$(Z)){let Q=this.extractLocatorFromResultEntry(Z);if(Q)W.push(Q)}}return this.dedupeReadLocators(W)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Z=[];for(let Q of $){let J=this.extractLocatorFromResultEntry(Q);if(J)Z.push(J)}return this.dedupeReadLocators(Z)}let W=this.extractLocatorFromResultEntry($);return W?[W]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(!Z)return;return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(Z)return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)};if(typeof W.query==="string"&&W.query.length>0)return this.parseReadQuery(W.query);return}extractPath($){let W=[$.path,$.file_path,$.filePath];for(let Z of W)if(typeof Z==="string"&&Z.length>0)return Z;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let W=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!W)return{path:$,startLine:null,endLine:null};return{path:W[1],startLine:Number(W[2]),endLine:W[3]==="EOF"?null:Number(W[3])}}dedupeReadLocators($){let W=new Map;for(let Z of $)W.set(this.toReadLocatorKey(Z),Z);return Array.from(W.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,W){let Z=this.latestFullContentOwnerByPathCache.get($.path);if(Z&&Z!==W)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==W}replaceOutdatedReadContent($,W){let Z=new Set(W.map((j)=>this.toReadLocatorKey(j))),Q=new Set(W.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Z)??N2;let J=0;for(let j of $)if(j.type==="text")J+=this.countOutdatedImageEntries(j.text,Z);return $.map((j)=>{if(j.type==="file"){if(!Q.has(j.path))return j;return{...j,content:N2}}if(j.type==="image"){if(J===0)return j;return J-=1,{type:"text",text:N2}}if(w$(j))return this.replaceOutdatedReadEntry(j,Z);if(j.type!=="text")return j;let X=this.replaceOutdatedInString(j.text,Z);if(X===null)return{...j,text:N2};return X===j.text?j:{...j,text:X}})}countOutdatedImageEntries($,W){let Z;try{Z=JSON.parse($)}catch{return 0}let Q=Array.isArray(Z)?Z:[Z],J=0;for(let j of Q){if(!j||typeof j!=="object")continue;let X=j,Y=this.extractLocatorFromResultEntry(X);if(!Y)continue;if(!W.has(this.toReadLocatorKey(Y)))continue;if(X.result==="Successfully read image"||X.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,W){let Z;try{Z=JSON.parse($)}catch{return null}let Q=Array.isArray(Z)?Z.map((J)=>this.replaceOutdatedReadEntry(J,W)):this.replaceOutdatedReadEntry(Z,W);return JSON.stringify(Q)}replaceOutdatedReadEntry($,W){if(!$||typeof $!=="object")return $;let Z=this.extractLocatorFromResultEntry($);if(!Z||!W.has(this.toReadLocatorKey(Z)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=N2;else if(typeof Q.content==="string")Q.content=N2;else Q.result=N2;return Q}isReadTool($){return!!$&&$R.has($)}resolveToolName($){let W=this.toolNameByIdCache.get($.tool_use_id);if(W!==void 0)return W;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((W)=>{if(W.type==="file"){let Z=this.truncateMiddle(W.content);return Z===W.content?W:{...W,content:Z}}if(W.type==="text"){let Z=this.truncateMiddle(W.text);return Z===W.text?W:{...W,text:Z}}if(w$(W))return this.truncateNestedStrings(W);return W})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let W=!1,Z=$.map((Q)=>{let J=this.truncateNestedStrings(Q);if(J!==Q)W=!0;return J});return W?Z:$}if($!==null&&typeof $==="object"){if(s3($))return $;let W=!1,Z={};for(let[Q,J]of Object.entries($)){let j=this.truncateNestedStrings(J);if(j!==J)W=!0;Z[Q]=j}return W?Z:$}return $}truncateMiddle($){return r8($,this.maxToolResultChars,GG)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return r8($,this.maxAssistantToolMarkupChars,ZR);return r8($,this.maxAssistantTextChars,WR)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let W=0;for(let Z of $.matchAll(QR))if(W+=1,W>=eM)return!0;return!1}truncateToTotalTextBudget($){let W=this.countMessageTextBytes($);if(W<=this.maxTotalTextBytes)return $;let Z=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((j)=>YR(j))}}),Q=this.collectTruncationCandidates(Z);for(let J of Q){if(W<=this.maxTotalTextBytes)break;let j=J.byteLength;if(j<=J.minBytes)continue;let X=W-this.maxTotalTextBytes,Y=Math.max(J.minBytes,j-X),V=XR(J.get(),Y,J.makeMarker);J.set(V),W-=j-j0(V)}return Z}countMessageTextBytes($){let W=0;for(let Z of $){if(typeof Z.content==="string"){W+=j0(Z.content);continue}for(let Q of Z.content)if(Q.type==="text")W+=j0(Q.text);else if(Q.type==="thinking")W+=j0(Q.thinking);else if(Q.type==="file")W+=j0(Q.content);else if(Q.type==="tool_use")W+=t9(Q.input);else if(Q.type==="tool_result"){if(typeof Q.content==="string")W+=j0(Q.content);else for(let J of Q.content)if(J.type==="text")W+=j0(J.text);else if(J.type==="file")W+=j0(J.content);else if(w$(J))W+=t9(J)}}return W}collectTruncationCandidates($){let W=[],Z=[];for(let Q of $){if(Q.role==="assistant"&&typeof Q.content==="string"){W.push({byteLength:j0(Q.content),minBytes:BG,makeMarker:KG,get:()=>Q.content,set:(J)=>{Q.content=J}});continue}if(!Array.isArray(Q.content))continue;for(let J of Q.content){if(J.type==="tool_use"){e9(J.input,Z);continue}if(Q.role==="assistant"&&J.type==="text"){W.push({byteLength:j0(J.text),minBytes:BG,makeMarker:KG,get:()=>J.text,set:(j)=>{J.text=j}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){W.push({byteLength:j0(J.content),minBytes:$5,makeMarker:W5,get:()=>J.content,set:(j)=>{J.content=j}});continue}for(let j of J.content)if(j.type==="text")W.push({byteLength:j0(j.text),minBytes:$5,makeMarker:W5,get:()=>j.text,set:(X)=>{j.text=X}});else if(j.type==="file")W.push({byteLength:j0(j.content),minBytes:$5,makeMarker:W5,get:()=>j.content,set:(X)=>{j.content=X}});else if(w$(j))e9(j,W)}}return W.sort((Q,J)=>J.byteLength-Q.byteLength),Z.sort((Q,J)=>J.byteLength-Q.byteLength),[...W,...Z]}applyMediaBudget($){let W=this.resolveMediaBudget();if(W.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&W.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&W.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Z=lM(),Q=!1,J=$.map((j)=>{if(!Array.isArray(j.content))return j;let X=!1,Y=j.content.map((V)=>{let B=this.applyMediaBudgetToBlock(V,W,Z);if(B!==V)X=!0;return B});if(!X)return j;return Q=!0,{...j,content:Y}});return Q?J:$}resolveMediaBudget(){return pM(this.mediaBudget)}applyMediaBudgetToBlock($,W,Z){if(a3($))return this.limitImageContent($,W,Z);if($.type!=="tool_result"||typeof $.content==="string")return $;let Q=!1,J=$.content.map((j)=>{let X=this.applyMediaBudgetToToolResultEntry(j,W,Z);if(X!==j)Q=!0;return X});return Q?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,W,Z){if(a3($))return this.limitImageContent($,W,Z);if(w$($))return this.limitNestedMedia($,W,Z);return $}limitNestedMedia($,W,Z){if(a3($)){let Q=this.limitImageContent($,W,Z);return Q.type==="text"?Q.text:Q}if(Array.isArray($)){let Q=!1,J=$.map((j)=>{let X=this.limitNestedMedia(j,W,Z);if(X!==j)Q=!0;return X});return Q?J:$}if($!==null&&typeof $==="object"){let Q=!1,J={};for(let[j,X]of Object.entries($)){let Y=this.limitNestedMedia(X,W,Z);if(Y!==X)Q=!0;J[j]=Y}return Q?J:$}return $}limitImageContent($,W,Z){if(!fG($))return{type:"text",text:YG};let Q=rM($.mediaType,$.data,{maxImageEncodedBytes:W.maxImageEncodedBytes,maxImageDecodedBytes:W.maxImageDecodedBytes,maxTotalMediaBytes:W.maxTotalMediaBytes},Z);if(!Q.ok)return{type:"text",text:YG};return{...$,data:Q.base64,mediaType:Q.mediaType}}}var FG=String.raw`[\|\uFF5C]`,QR=new RegExp(String.raw`<\s*(?:${FG}\s*)?DSML\s*(?:${FG}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function j0($){return Buffer.byteLength($,"utf8")}function AG($){if($===void 0)return;let W=Number.parseInt($,10);return Number.isFinite(W)&&W>0?W:void 0}function JR($){if($===void 0)return;let W=$.trim().toLowerCase();if(W==="infinity"||W==="disable")return Number.POSITIVE_INFINITY;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>=0?Z:void 0}function e4($,W){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):W}function jR($,W){if(typeof $!=="number"||Number.isNaN($)||$<0)return W;return Number.isFinite($)?Math.floor($):$}function r8($,W,Z){if($.length<=W)return $;let Q=Z($.length-W),J=Math.max(0,Math.floor((W-Q.length)/2)),j=Math.max(0,$.length-J*2),X=Z(j),Y=Math.max(0,Math.floor((W-X.length)/2)),V=$.slice(0,Y),B=Y>0?$.slice(-Y):"";return`${V}${X}${B}`}function XR($,W,Z){if(j0($)<=W)return $;let Q=0,J=$.length,j=r8($,0,Z);while(Q<=J){let X=Q+J>>>1,Y=r8($,X,Z);if(j0(Y)<=W)j=Y,Q=X+1;else J=X-1}return j}function YR($){if($.type==="tool_use")return{...$,input:$Z($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((W)=>w$(W)?$Z(W):{...W})}}function w$($){if($===null||typeof $!=="object")return!1;let W=$.type;return W!=="text"&&W!=="image"&&W!=="file"}function a3($){return $!==null&&typeof $==="object"&&$.type==="image"}function fG($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function s3($){return fG($)}function t9($){if(typeof $==="string")return j0($);if(Array.isArray($)){let W=0;for(let Z of $)W+=t9(Z);return W}if($!==null&&typeof $==="object"){if(s3($))return 0;let W=0;for(let Z of Object.values($))W+=t9(Z);return W}return 0}function e9($,W){if(Array.isArray($)){$.forEach((Z,Q)=>{if(typeof Z==="string")W.push({byteLength:j0(Z),minBytes:$5,makeMarker:W5,get:()=>$[Q],set:(J)=>{$[Q]=J}});else e9(Z,W)});return}if($!==null&&typeof $==="object"){if(s3($))return;let Z=$;for(let Q of Object.keys(Z)){let J=Z[Q];if(typeof J==="string")W.push({byteLength:j0(J),minBytes:$5,makeMarker:W5,get:()=>Z[Q],set:(j)=>{Z[Q]=j}});else e9(J,W)}}}function $Z($){if(Array.isArray($))return $.map($Z);if($!==null&&typeof $==="object"){let W={};for(let[Z,Q]of Object.entries($))W[Z]=$Z(Q);return W}return $}function t3(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class e3{messages=[];conversationId=t3();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=t3(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=t3(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function DG($){let{agentConfig:W}=$,Z=VR(W),Q=BR(W),J=$.hooks,j=HR(W.maxParallelToolCalls);return{sessionId:$.sessionId??W.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??W.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:Z,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:W.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??W.logger,telemetry:$.telemetry??W.telemetry,initialMessages:$.initialMessages,completionPolicy:W.completionPolicy,maxIterations:W.maxIterations,toolExecution:j,toolPolicies:W.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:W.requestToolApproval}}function VR($){let W={};if($.thinking!==void 0)W.thinking=$.thinking;if($.reasoningEffort!==void 0)W.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)W.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)W.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)W.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(W).length>0?W:void 0}function BR($){let W=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:W}}function HR($){if($===void 0)return;return $>=2?"parallel":"sequential"}var _G={};w(_G,{normalizeConnectionUpdate:()=>E2,buildConnectionUpdate:()=>$J});function $J($){let W={};if($.providerId!==void 0)W.providerId=$.providerId;if($.modelId!==void 0)W.modelId=$.modelId;if($.apiKey!==void 0)W.apiKey=$.apiKey;if($.baseUrl!==void 0)W.baseUrl=$.baseUrl;if($.headers!==void 0)W.headers=$.headers;if($.providerConfig!==void 0)W.providerConfig=$.providerConfig;if($.thinking===!1)return W.thinking=!1,W.reasoningEffort=null,W.thinkingBudgetTokens=null,W;if($.thinking===!0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort??null,W.thinkingBudgetTokens=null;else if($.reasoningEffort!==void 0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort;if(typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0,W.thinkingBudgetTokens=Math.trunc($.thinkingBudgetTokens);return W}function E2($){let W={...$},Z=Object.hasOwn($,"thinking"),Q=Object.hasOwn($,"thinkingBudgetTokens");if($.thinking===!1||$.thinking===null)return W.reasoningEffort=void 0,W.thinkingBudgetTokens=void 0,W;if(!Z&&Q&&typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0;return W}function GR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function KR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function WJ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(WJ);let W={};for(let Z of Object.keys($).sort())W[Z]=WJ($[Z]);return W}function FR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(WJ($))}catch{return String($)}}function AR($,W,Z,Q){if(W===$.lastToolName&&Z===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=W,$.lastToolSignature=Z,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var LG={softThreshold:3,hardThreshold:5};class ZJ{config;state=GR();constructor($){this.config={softThreshold:$?.softThreshold??LG.softThreshold,hardThreshold:$?.hardThreshold??LG.hardThreshold}}inspect($){let W=FR($.input),Z=AR(this.state,$.name,W,this.config);if(Z.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Z.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){KR(this.state)}}class QJ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let W=this.options.maxConsecutiveMistakes,Z=$.forceAtLimit&&W?W:this.consecutiveMistakes+1;this.consecutiveMistakes=Z;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Z,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!W||Z<W)return{action:"continue"};let J=await fR({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details},this.options.onLimitReached);if(J.action==="continue"){let j=J.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:J.reason?.trim()||void 0,message:UR({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details,stopReason:J.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function UR($){let W=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Z=$.details?.trim();if(Z)W.push(`Error: ${Z}`);let Q=$.stopReason?.trim();if(Q)W.push(`Decision: ${Q}`);return W.push("Session state was preserved. Send a new prompt to resume from the latest state."),W.join(" ")}async function fR($,W){if(!W)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await W($)}catch(Z){return{action:"stop",reason:Z instanceof Error?Z.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function DR($){switch($){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return $;default:return}}function _R($){let W=$.content.filter((Z)=>Z.type==="text");if(W.length===0)return;return W.map((Z)=>Z.text).join("")}function LR($){let W=$.content.filter((Z)=>Z.type==="reasoning");if(W.length===0)return;return{reasoning:W.map((Z)=>Z.text).join(""),redacted:W.some((Z)=>Z.redacted===!0)}}function TR($){return $.content.find((W)=>W.type==="tool-result")}function OR($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function zR($){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 JJ{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:DR($.metadata?.reason),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 W=[],Z=_R($);if(Z!==void 0)W.push({type:"content_end",contentType:"text",text:Z});let Q=LR($);if(Q!==void 0)W.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return W}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 W=this.toolStartedAt.get($.toolCall.toolCallId),Z=W===void 0?void 0:Date.now()-W;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=TR($.message),J=Q?.output,j=zR(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:j,durationMs:Z}]}translateUsage($){let W=$.inputTokens-this.lastUsage.inputTokens,Z=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,Y=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,W),outputTokens:Math.max(0,Z),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:Y===0?void 0:Y,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let W={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:OR($.status),text:$.outputText,iterations:$.iterations,usage:W}]}}function PR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function SR($){let Z=(typeof $.content==="function"?await $.content():$.content).trim();return Z.length>0?Z:void 0}function bR($,W){let Z=$.trim(),Q=W.map((J)=>J.trim()).filter(Boolean).join(`
471
+ `;function MG($=process.env){return{maxToolResultChars:qG($[e3.maxToolResultChars]),maxTotalTextBytes:qG($[e3.maxTotalTextBytes]),minOutdatedRewriteBytes:KR($[e3.minOutdatedRewriteBytes])}}class WJ{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor($={}){this.maxToolResultChars=W5($.maxToolResultChars,WR),this.maxFileContentChars=W5($.maxFileContentChars,ZR),this.maxTotalTextBytes=W5($.maxTotalTextBytes,QR),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=W5($.maxAssistantTextChars,JR),this.maxAssistantToolMarkupChars=W5($.maxAssistantToolMarkupChars,jR),this.minOutdatedRewriteBytes=FR($.minOutdatedRewriteBytes,XR)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Z=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let Y=_G(J.content);if(Y!==J.content)return{...J,content:Y}}if(J.role==="assistant"&&typeof J.content==="string"){let Y=this.truncateAssistantText(J.content);if(Y!==J.content)return{...J,content:Y}}return J}let j=!1,X=J.content.map((Y)=>{let V=this.transformBlock(Y,J.role);if(V!==Y)j=!0;return V});return j?{...J,content:X}:J}),Q=this.applyMediaBudget(Z);return this.truncateToTotalTextBudget(Q)}transformBlock($,W){if(W==="user"&&$.type==="text"&&typeof $.text==="string"){let J=_G($.text);if(J!==$.text)return{...$,text:J};return $}if(W==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=n8($.content,this.maxFileContentChars,TG);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Z=this.resolveToolName($),Q=$.content;if(this.isReadTool(Z)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let X=this.getReadLocators($).filter((Y)=>J.has(this.toReadLocatorKey(Y))&&this.isOutdatedReadLocator(Y,$.tool_use_id));if(X.length>0)Q=this.replaceOutdatedReadContent(Q,X)}}return Q=this.truncateToolResultContent(Q),Q===$.content?$:{...$,content:Q}}reindex($){let W=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!W)this.resetIndexes();for(let Z=this.indexedMessageCount;Z<$.length;Z++){let Q=$[Z];if(!Array.isArray(Q.content))continue;for(let J=0;J<Q.content.length;J++){let j=Q.content[J];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Z}:${J}`);else if(j.type==="tool_use"){let X=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,X),this.isReadTool(X)){let Y=this.extractLocatorsFromReadToolInput(j.input);if(Y.length>0)this.readLocatorsByToolUseIdCache.set(j.id,Y)}}else if(j.type==="tool_result"){let X=this.resolveToolName(j);if(!this.isReadTool(X)||j.is_error===!0)continue;let Y=this.getReadLocators(j);for(let V of Y)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),j.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let W=new Map,Z=new Set,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result"||j.is_error===!0)continue;let X=this.resolveToolName(j);if(!this.isReadTool(X))continue;Z.add(j.tool_use_id);let Y=this.committedOutdatedRewrites.get(j.tool_use_id),V=new Set,B=new Set;for(let G of this.getReadLocators(j)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,j.tool_use_id))continue;if(B.add(K),!Y?.has(K))V.add(K)}if(Y){for(let G of Y)if(!B.has(G))Y.delete(G);if(Y.size===0)this.committedOutdatedRewrites.delete(j.tool_use_id)}if(V.size===0)continue;let H=W.get(j.tool_use_id);if(!H)H=new Set,W.set(j.tool_use_id,H);for(let G of V)H.add(G);Q+=this.estimateOutdatedReclaimBytes(j.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Z.has(J))this.committedOutdatedRewrites.delete(J);if(W.size===0||Q<this.minOutdatedRewriteBytes)return;for(let[J,j]of W){let X=this.committedOutdatedRewrites.get(J);if(!X)X=new Set,this.committedOutdatedRewrites.set(J,X);for(let Y of j)X.add(Y)}}estimateOutdatedReclaimBytes($,W){let Z=this.extractReadLocatorsFromToolResultContent($),Q=Z.length>0&&Z.every((V)=>W.has(this.toReadLocatorKey(V))),J=(V)=>{let B;try{B=JSON.parse(V)}catch{return Q||Z.length===0?j0(this.truncateMiddle(V)):0}let H=Array.isArray(B)?B:[B],G=0;for(let K of H){let F=this.extractLocatorFromResultEntry(K);if(F&&W.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let j=new Set(W),X=0;for(let V of $)if(V.type==="text")X+=this.countOutdatedImageEntries(V.text,j);let Y=0;for(let V of $)if(V.type==="text")Y+=J(V.text);else if(V.type==="image"){if(X>0)X-=1,Y+=j0(V.data)}else if(C$(V)){let B=this.extractLocatorFromResultEntry(V);if(B&&W.has(this.toReadLocatorKey(B)))Y+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(W.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))Y+=j0(this.truncateMiddle(V.content))}return Y}providerBoundEntryBytes($){let W=this.truncateNestedStrings($);return j0(JSON.stringify(W))}addMissingToolResults($){let W=this.collectToolResultIds($),Z=[],Q=new Map,J=!1,j=()=>{if(Q.size===0)return;X(this.createMissingToolResultMessage(Q)),Q.clear(),J=!0},X=(Y)=>{let V=Z.at(-1);if(this.shouldMergeUserAfterToolResults(V,Y)){Z[Z.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(Y.content)]},J=!0;return}Z.push(Y)};for(let Y of $){if(this.isToolResultOnlyMessage(Y)){if(X(this.appendMissingToolResults(Y,Q)),Q.size>0)Q.clear(),J=!0;continue}if(Array.isArray(Y.content)){let V=Y.content.filter((H)=>H.type==="tool_result"),B=Y.content.filter((H)=>H.type!=="tool_result");if(V.length>0){let H=this.appendMissingToolResults({...Y,role:"user",content:V},Q);if(X(H),Q.size>0)Q.clear();J=!0}if(B.length>0||V.length===0){if(V.length===0)j();let H=V.length>0?{...Y,content:B}:Y;if(X(H),H.role==="assistant")this.trackMissingToolCalls(H,W,Q)}continue}j(),X(Y)}return j(),J?Z:$}appendMissingToolResults($,W){if(W.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(W)]}}shouldMergeUserAfterToolResults($,W){return $?.role==="user"&&W.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(W.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}return W}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}trackMissingToolCalls($,W,Z){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||W.has(Q.id))continue;Z.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([W,Z])=>({type:"tool_result",tool_use_id:W,name:Z,content:[{type:"text",text:this.formatMissingToolResultText(Z)}],is_error:!0}))}formatMissingToolResultText($){return $?`${LG} Tool: ${$}.`:LG}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 W=$,Z=this.readResultLocatorCache.get(W);if(Z===void 0)Z=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(W,Z);if(Z.length>0)return Z;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let W=$,Z=[],Q=this.extractLocatorFromReadRequest(W);if(Q)Z.push(Q);if(Array.isArray(W.files))for(let J of W.files){let j=this.extractLocatorFromReadRequest(J);if(j)Z.push(j)}if(Array.isArray(W.file_paths)){for(let J of W.file_paths)if(typeof J==="string"&&J.length>0)Z.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Z)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let W=[];for(let Z of $){if(Z.type==="text"){W.push(...this.tryParseReadLocators(Z.text));continue}if(C$(Z)){let Q=this.extractLocatorFromResultEntry(Z);if(Q)W.push(Q)}}return this.dedupeReadLocators(W)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Z=[];for(let Q of $){let J=this.extractLocatorFromResultEntry(Q);if(J)Z.push(J)}return this.dedupeReadLocators(Z)}let W=this.extractLocatorFromResultEntry($);return W?[W]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(!Z)return;return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(Z)return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)};if(typeof W.query==="string"&&W.query.length>0)return this.parseReadQuery(W.query);return}extractPath($){let W=[$.path,$.file_path,$.filePath];for(let Z of W)if(typeof Z==="string"&&Z.length>0)return Z;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let W=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!W)return{path:$,startLine:null,endLine:null};return{path:W[1],startLine:Number(W[2]),endLine:W[3]==="EOF"?null:Number(W[3])}}dedupeReadLocators($){let W=new Map;for(let Z of $)W.set(this.toReadLocatorKey(Z),Z);return Array.from(W.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,W){let Z=this.latestFullContentOwnerByPathCache.get($.path);if(Z&&Z!==W)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==W}replaceOutdatedReadContent($,W){let Z=new Set(W.map((j)=>this.toReadLocatorKey(j))),Q=new Set(W.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Z)??N2;let J=0;for(let j of $)if(j.type==="text")J+=this.countOutdatedImageEntries(j.text,Z);return $.map((j)=>{if(j.type==="file"){if(!Q.has(j.path))return j;return{...j,content:N2}}if(j.type==="image"){if(J===0)return j;return J-=1,{type:"text",text:N2}}if(C$(j))return this.replaceOutdatedReadEntry(j,Z);if(j.type!=="text")return j;let X=this.replaceOutdatedInString(j.text,Z);if(X===null)return{...j,text:N2};return X===j.text?j:{...j,text:X}})}countOutdatedImageEntries($,W){let Z;try{Z=JSON.parse($)}catch{return 0}let Q=Array.isArray(Z)?Z:[Z],J=0;for(let j of Q){if(!j||typeof j!=="object")continue;let X=j,Y=this.extractLocatorFromResultEntry(X);if(!Y)continue;if(!W.has(this.toReadLocatorKey(Y)))continue;if(X.result==="Successfully read image"||X.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,W){let Z;try{Z=JSON.parse($)}catch{return null}let Q=Array.isArray(Z)?Z.map((J)=>this.replaceOutdatedReadEntry(J,W)):this.replaceOutdatedReadEntry(Z,W);return JSON.stringify(Q)}replaceOutdatedReadEntry($,W){if(!$||typeof $!=="object")return $;let Z=this.extractLocatorFromResultEntry($);if(!Z||!W.has(this.toReadLocatorKey(Z)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=N2;else if(typeof Q.content==="string")Q.content=N2;else Q.result=N2;return Q}isReadTool($){return!!$&&VR.has($)}resolveToolName($){let W=this.toolNameByIdCache.get($.tool_use_id);if(W!==void 0)return W;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((W)=>{if(W.type==="file"){let Z=this.truncateMiddle(W.content);return Z===W.content?W:{...W,content:Z}}if(W.type==="text"){let Z=this.truncateMiddle(W.text);return Z===W.text?W:{...W,text:Z}}if(C$(W))return this.truncateNestedStrings(W);return W})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let W=!1,Z=$.map((Q)=>{let J=this.truncateNestedStrings(Q);if(J!==Q)W=!0;return J});return W?Z:$}if($!==null&&typeof $==="object"){if(ZJ($))return $;let W=!1,Z={};for(let[Q,J]of Object.entries($)){let j=this.truncateNestedStrings(J);if(j!==J)W=!0;Z[Q]=j}return W?Z:$}return $}truncateMiddle($){return n8($,this.maxToolResultChars,TG)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return n8($,this.maxAssistantToolMarkupChars,HR);return n8($,this.maxAssistantTextChars,BR)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let W=0;for(let Z of $.matchAll(GR))if(W+=1,W>=YR)return!0;return!1}truncateToTotalTextBudget($){let W=this.countMessageTextBytes($);if(W<=this.maxTotalTextBytes)return $;let Z=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((j)=>UR(j))}}),Q=this.collectTruncationCandidates(Z);for(let J of Q){if(W<=this.maxTotalTextBytes)break;let j=J.byteLength;if(j<=J.minBytes)continue;let X=W-this.maxTotalTextBytes,Y=Math.max(J.minBytes,j-X),V=AR(J.get(),Y,J.makeMarker);J.set(V),W-=j-j0(V)}return Z}countMessageTextBytes($){let W=0;for(let Z of $){if(typeof Z.content==="string"){W+=j0(Z.content);continue}for(let Q of Z.content)if(Q.type==="text")W+=j0(Q.text);else if(Q.type==="thinking")W+=j0(Q.thinking);else if(Q.type==="file")W+=j0(Q.content);else if(Q.type==="tool_use")W+=YZ(Q.input);else if(Q.type==="tool_result"){if(typeof Q.content==="string")W+=j0(Q.content);else for(let J of Q.content)if(J.type==="text")W+=j0(J.text);else if(J.type==="file")W+=j0(J.content);else if(C$(J))W+=YZ(J)}}return W}collectTruncationCandidates($){let W=[],Z=[];for(let Q of $){if(Q.role==="assistant"&&typeof Q.content==="string"){W.push({byteLength:j0(Q.content),minBytes:fG,makeMarker:OG,get:()=>Q.content,set:(J)=>{Q.content=J}});continue}if(!Array.isArray(Q.content))continue;for(let J of Q.content){if(J.type==="tool_use"){VZ(J.input,Z);continue}if(Q.role==="assistant"&&J.type==="text"){W.push({byteLength:j0(J.text),minBytes:fG,makeMarker:OG,get:()=>J.text,set:(j)=>{J.text=j}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){W.push({byteLength:j0(J.content),minBytes:Z5,makeMarker:Q5,get:()=>J.content,set:(j)=>{J.content=j}});continue}for(let j of J.content)if(j.type==="text")W.push({byteLength:j0(j.text),minBytes:Z5,makeMarker:Q5,get:()=>j.text,set:(X)=>{j.text=X}});else if(j.type==="file")W.push({byteLength:j0(j.content),minBytes:Z5,makeMarker:Q5,get:()=>j.content,set:(X)=>{j.content=X}});else if(C$(j))VZ(j,W)}}return W.sort((Q,J)=>J.byteLength-Q.byteLength),Z.sort((Q,J)=>J.byteLength-Q.byteLength),[...W,...Z]}applyMediaBudget($){let W=this.resolveMediaBudget();if(W.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&W.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&W.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Z=tM(),Q=!1,J=$.map((j)=>{if(!Array.isArray(j.content))return j;let X=!1,Y=j.content.map((V)=>{let B=this.applyMediaBudgetToBlock(V,W,Z);if(B!==V)X=!0;return B});if(!X)return j;return Q=!0,{...j,content:Y}});return Q?J:$}resolveMediaBudget(){return eM(this.mediaBudget)}applyMediaBudgetToBlock($,W,Z){if($J($))return this.limitImageContent($,W,Z);if($.type!=="tool_result"||typeof $.content==="string")return $;let Q=!1,J=$.content.map((j)=>{let X=this.applyMediaBudgetToToolResultEntry(j,W,Z);if(X!==j)Q=!0;return X});return Q?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,W,Z){if($J($))return this.limitImageContent($,W,Z);if(C$($))return this.limitNestedMedia($,W,Z);return $}limitNestedMedia($,W,Z){if($J($)){let Q=this.limitImageContent($,W,Z);return Q.type==="text"?Q.text:Q}if(Array.isArray($)){let Q=!1,J=$.map((j)=>{let X=this.limitNestedMedia(j,W,Z);if(X!==j)Q=!0;return X});return Q?J:$}if($!==null&&typeof $==="object"){let Q=!1,J={};for(let[j,X]of Object.entries($)){let Y=this.limitNestedMedia(X,W,Z);if(Y!==X)Q=!0;J[j]=Y}return Q?J:$}return $}limitImageContent($,W,Z){if(!RG($))return{type:"text",text:DG};let Q=$R($.mediaType,$.data,{maxImageEncodedBytes:W.maxImageEncodedBytes,maxImageDecodedBytes:W.maxImageDecodedBytes,maxTotalMediaBytes:W.maxTotalMediaBytes},Z);if(!Q.ok)return{type:"text",text:DG};return{...$,data:Q.base64,mediaType:Q.mediaType}}}var zG=String.raw`[\|\uFF5C]`,GR=new RegExp(String.raw`<\s*(?:${zG}\s*)?DSML\s*(?:${zG}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function j0($){return Buffer.byteLength($,"utf8")}function qG($){if($===void 0)return;let W=Number.parseInt($,10);return Number.isFinite(W)&&W>0?W:void 0}function KR($){if($===void 0)return;let W=$.trim().toLowerCase();if(W==="infinity"||W==="disable")return Number.POSITIVE_INFINITY;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>=0?Z:void 0}function W5($,W){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):W}function FR($,W){if(typeof $!=="number"||Number.isNaN($)||$<0)return W;return Number.isFinite($)?Math.floor($):$}function n8($,W,Z){if($.length<=W)return $;let Q=Z($.length-W),J=Math.max(0,Math.floor((W-Q.length)/2)),j=Math.max(0,$.length-J*2),X=Z(j),Y=Math.max(0,Math.floor((W-X.length)/2)),V=$.slice(0,Y),B=Y>0?$.slice(-Y):"";return`${V}${X}${B}`}function AR($,W,Z){if(j0($)<=W)return $;let Q=0,J=$.length,j=n8($,0,Z);while(Q<=J){let X=Q+J>>>1,Y=n8($,X,Z);if(j0(Y)<=W)j=Y,Q=X+1;else J=X-1}return j}function UR($){if($.type==="tool_use")return{...$,input:BZ($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((W)=>C$(W)?BZ(W):{...W})}}function C$($){if($===null||typeof $!=="object")return!1;let W=$.type;return W!=="text"&&W!=="image"&&W!=="file"}function $J($){return $!==null&&typeof $==="object"&&$.type==="image"}function RG($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function ZJ($){return RG($)}function YZ($){if(typeof $==="string")return j0($);if(Array.isArray($)){let W=0;for(let Z of $)W+=YZ(Z);return W}if($!==null&&typeof $==="object"){if(ZJ($))return 0;let W=0;for(let Z of Object.values($))W+=YZ(Z);return W}return 0}function VZ($,W){if(Array.isArray($)){$.forEach((Z,Q)=>{if(typeof Z==="string")W.push({byteLength:j0(Z),minBytes:Z5,makeMarker:Q5,get:()=>$[Q],set:(J)=>{$[Q]=J}});else VZ(Z,W)});return}if($!==null&&typeof $==="object"){if(ZJ($))return;let Z=$;for(let Q of Object.keys(Z)){let J=Z[Q];if(typeof J==="string")W.push({byteLength:j0(J),minBytes:Z5,makeMarker:Q5,get:()=>Z[Q],set:(j)=>{Z[Q]=j}});else VZ(J,W)}}}function BZ($){if(Array.isArray($))return $.map(BZ);if($!==null&&typeof $==="object"){let W={};for(let[Z,Q]of Object.entries($))W[Z]=BZ(Q);return W}return $}function QJ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class JJ{messages=[];conversationId=QJ();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=QJ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=QJ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function EG($){let{agentConfig:W}=$,Z=DR(W),Q=_R(W),J=$.hooks,j=fR(W.maxParallelToolCalls);return{sessionId:$.sessionId??W.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??W.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:Z,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:W.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??W.logger,telemetry:$.telemetry??W.telemetry,initialMessages:$.initialMessages,completionPolicy:W.completionPolicy,maxIterations:W.maxIterations,toolExecution:j,toolPolicies:W.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:W.requestToolApproval}}function DR($){let W={};if($.thinking!==void 0)W.thinking=$.thinking;if($.reasoningEffort!==void 0)W.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)W.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)W.maxTokensPerTurn=$.maxTokensPerTurn;if($.temperature!==void 0)W.temperature=$.temperature;if($.apiTimeoutMs!==void 0)W.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(W).length>0?W:void 0}function _R($){let W=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:W}}function fR($){if($===void 0)return;return $>=2?"parallel":"sequential"}var NG={};w(NG,{normalizeConnectionUpdate:()=>w2,buildConnectionUpdate:()=>jJ});function jJ($){let W={};if($.providerId!==void 0)W.providerId=$.providerId;if($.modelId!==void 0)W.modelId=$.modelId;if($.apiKey!==void 0)W.apiKey=$.apiKey;if($.baseUrl!==void 0)W.baseUrl=$.baseUrl;if($.headers!==void 0)W.headers=$.headers;if($.providerConfig!==void 0)W.providerConfig=$.providerConfig;if($.thinking===!1)return W.thinking=!1,W.reasoningEffort=null,W.thinkingBudgetTokens=null,W;if($.thinking===!0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort??null,W.thinkingBudgetTokens=null;else if($.reasoningEffort!==void 0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort;if(typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0,W.thinkingBudgetTokens=Math.trunc($.thinkingBudgetTokens);return W}function w2($){let W={...$},Z=Object.hasOwn($,"thinking"),Q=Object.hasOwn($,"thinkingBudgetTokens");if($.thinking===!1||$.thinking===null)return W.reasoningEffort=void 0,W.thinkingBudgetTokens=void 0,W;if(!Z&&Q&&typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0;return W}function LR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function TR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function XJ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(XJ);let W={};for(let Z of Object.keys($).sort())W[Z]=XJ($[Z]);return W}function OR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(XJ($))}catch{return String($)}}function zR($,W,Z,Q){if(W===$.lastToolName&&Z===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=W,$.lastToolSignature=Z,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var wG={softThreshold:3,hardThreshold:5};class YJ{config;state=LR();constructor($){this.config={softThreshold:$?.softThreshold??wG.softThreshold,hardThreshold:$?.hardThreshold??wG.hardThreshold}}inspect($){let W=OR($.input),Z=zR(this.state,$.name,W,this.config);if(Z.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Z.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){TR(this.state)}}class VJ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let W=this.options.maxConsecutiveMistakes,Z=$.forceAtLimit&&W?W:this.consecutiveMistakes+1;this.consecutiveMistakes=Z;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Z,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!W||Z<W)return{action:"continue"};let J=await MR({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details},this.options.onLimitReached);if(J.action==="continue"){let j=J.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:J.reason?.trim()||void 0,message:qR({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details,stopReason:J.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function qR($){let W=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Z=$.details?.trim();if(Z)W.push(`Error: ${Z}`);let Q=$.stopReason?.trim();if(Q)W.push(`Decision: ${Q}`);return W.push("Session state was preserved. Send a new prompt to resume from the latest state."),W.join(" ")}async function MR($,W){if(!W)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await W($)}catch(Z){return{action:"stop",reason:Z instanceof Error?Z.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function RR($){switch($){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return $;default:return}}function ER($){let W=$.content.filter((Z)=>Z.type==="text");if(W.length===0)return;return W.map((Z)=>Z.text).join("")}function NR($){let W=$.content.filter((Z)=>Z.type==="reasoning");if(W.length===0)return;return{reasoning:W.map((Z)=>Z.text).join(""),redacted:W.some((Z)=>Z.redacted===!0)}}function wR($){return $.content.find((W)=>W.type==="tool-result")}function CR($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function PR($){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 BJ{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:RR($.metadata?.reason),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 W=[],Z=ER($);if(Z!==void 0)W.push({type:"content_end",contentType:"text",text:Z});let Q=NR($);if(Q!==void 0)W.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return W}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 W=this.toolStartedAt.get($.toolCall.toolCallId),Z=W===void 0?void 0:Date.now()-W;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=wR($.message),J=Q?.output,j=PR(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:j,durationMs:Z}]}translateUsage($){let W=$.inputTokens-this.lastUsage.inputTokens,Z=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,Y=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,W),outputTokens:Math.max(0,Z),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:Y===0?void 0:Y,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let W={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:CR($.status),text:$.outputText,iterations:$.iterations,usage:W}]}}function gR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function mR($){let Z=(typeof $.content==="function"?await $.content():$.content).trim();return Z.length>0?Z:void 0}function vR($,W){let Z=$.trim(),Q=W.map((J)=>J.trim()).filter(Boolean).join(`
472
472
 
473
473
  `);if(Z&&Q)return`${Z}
474
474
 
475
- ${Q}`;return Z||Q}function yR($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function hR($,W){return $.filter((Z)=>yR(Z.name,W))}function kR($,W){return c1(hR($,W))}function IR($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return{};return{beforeRun:async(Z)=>{for(let Q of W){let J=await Q.beforeRun?.(Z);if(J?.stop)return J}return},afterRun:async(Z)=>{for(let Q of W)await Q.afterRun?.(Z)},beforeModel:async(Z)=>{let Q=Z.request,J;for(let j of W){let X=await j.beforeModel?.({...Z,request:Q});if(!X)continue;if(X.stop)return X;J={...J,...X,options:OG(J?.options,X.options)},Q={...Q,...X.messages?{messages:X.messages}:{},...X.tools?{tools:X.tools}:{},...X.options?{options:OG(Q.options,X.options)}:{}}}return J},afterModel:async(Z)=>{for(let Q of W){let J=await Q.afterModel?.(Z);if(J?.stop)return J}return},beforeTool:async(Z)=>{let Q=Z.input,J;for(let j of W){let X=await j.beforeTool?.({...Z,input:Q});if(!X)continue;if(X.stop||X.skip)return X;if(J={...J,...X},Object.hasOwn(X,"input"))Q=X.input}return J},afterTool:async(Z)=>{let Q=Z.result,J;for(let j of W){let X=await j.afterTool?.({...Z,result:Q});if(!X)continue;if(X.stop)return X;if(J={...J,...X},X.result)Q=X.result}return J},onEvent:async(Z)=>{for(let Q of W)await Q.onEvent?.(Z)}}}class C${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 JJ;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($,W={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=W.logger??$.logger,this.telemetry=W.telemetry??$.telemetry,this.createAgentRuntimeImpl=W.createAgentRuntimeImpl??wR,this.conversation=new e3($.initialMessages),this.messageBuilder=new o3(UG()),this.contributionRegistry=CR({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 Z=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new QJ({maxConsecutiveMistakes:Z,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,X,Y)=>xR(this.logger,j,X,Y),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,X)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let J=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new ZJ(J)}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 W=new Set(this.config.tools.map((Q)=>Q.name)),Z=[...this.config.tools];for(let Q of $)if(!W.has(Q.name))Z.push(Q),W.add(Q.name);this.config={...this.config,tools:Z}}updateConnection($){let W=E2($),Z={...this.config};if(W.providerId!==void 0)Z.providerId=W.providerId;if(W.modelId!==void 0)Z.modelId=W.modelId;if(W.apiKey!==void 0)Z.apiKey=W.apiKey;if(W.baseUrl!==void 0)Z.baseUrl=W.baseUrl;if(W.headers!==void 0)Z.headers=W.headers;if(W.providerConfig!==void 0)Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"reasoningEffort"))Z.reasoningEffort=W.reasoningEffort??void 0;if(Object.hasOwn(W,"thinkingBudgetTokens"))Z.thinkingBudgetTokens=W.thinkingBudgetTokens??void 0;if(Object.hasOwn(W,"thinking")){if(Z.thinking=W.thinking??void 0,W.thinking===!1||W.thinking===null)Z.reasoningEffort=void 0,Z.thinkingBudgetTokens=void 0}this.config=Z}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.messageBuilder.resetConversationState(),this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let W=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=W,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(W)}async shutdown($,W){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($,W,Z){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!1})}continue($,W,Z){return this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let W of this.contributionRegistry.getRegisteredRules()){let Z=await SR(W);if(Z)$.push(Z)}return bR(this.config.systemPrompt,$)}executeRun($){let W;return W=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===W)this.activeRunPromise=null}),this.activeRunPromise=W,W}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 W=new Date,Z=$.userMessage;if(Z!==void 0){let D=await mR(Z,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:D})}let Q=await this.composeSystemPrompt(),J=XG(this.config,this.logger,this.telemetry),j=new Map;for(let D of this.contributionRegistry.getRegisteredTools())j.set(D.name,D);let X=kR([...j.values()],this.config.toolPolicies),Y=new Map;for(let D of X)Y.set(D.name,D);for(let D of this.config.tools)Y.set(D.name,D);let V=this.conversation.getConversationId(),B=zG(this.config),H=Array.from(Y.values()),G=o9(this.conversation.getMessages()),K=DG({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:B?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[zH]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(B,H),initialMessages:G,systemPrompt:Q}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((D)=>{this.handleRuntimeEvent(D)}),f,U;try{if($.isContinue)f=await F.continue(void 0);else f=await F.run("")}catch(D){U=D instanceof Error?D:Error(String(D))}finally{A();try{await this.activeTrackerWork}catch(D){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:D})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(f&&f.messages.length>0){let D=p8(f.messages);this.conversation.replaceMessages(D)}let _=new Date;try{return this.buildLegacyResult({runResult:f,thrownError:U,startedAt:W,endedAt:_})}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 $=IR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((W)=>W.hooks)]);return{...$,beforeModel:async(W)=>{let Z=await $.beforeModel?.(W);if(Z?.stop)return Z;let Q=Z?.messages??W.request.messages,J=await this.prepareMessagesForModelRequest(Q);return{...Z,messages:J}}}}createRuntimePrepareTurn($,W){let Z=this.config.prepareTurn;if(!Z)return;return async(Q)=>{let J=p8(Q.messages),j=await this.prepareProviderMessagesForApi(J),X=await Z({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:J,apiMessages:j,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:W,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!X)return;return{...X.messages?{messages:o9(X.messages)}:{},...X.systemPrompt!==void 0?{systemPrompt:X.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let W=await this.prepareProviderMessagesForApi(s9($));return o9(W)}async prepareProviderMessagesForApi($){let W=$,Z=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of Z)W=await Q.build(W);return this.messageBuilder.buildForApi(W)}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 W=this.toolStartedAt.get($.toolCall.toolCallId),Z=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let J=$.message.content.find((V)=>V.type==="tool-result"),j=J?.type==="tool-result"&&J.isError===!0,X=j?PR(J?.type==="tool-result"?J.output:void 0):void 0,Y={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:J?.type==="tool-result"?J.output:void 0,error:X,durationMs:W===void 0?0:Z.getTime()-W.getTime(),startedAt:W??Z,endedAt:Z};if(this.currentRunToolCalls.push(Y),j){if(this.currentTurnFailedTools+=1,X)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${X}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let W=this.currentTurnFailedTools,Z=this.currentTurnSuccessfulTools;if(W>0&&Z===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${W} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(Z>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 W of this.eventAdapter.translate($))this.emitLegacyEvent(W)}syncConversationFromRuntimeMessage($,W){if($.length>0){this.conversation.replaceMessages(p8($));return}if(W.length===0)return;let Z=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),Q=p8(W).filter((J)=>!J.id||!Z.has(J.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let W of this.listeners)try{W($)}catch(Z){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Z})}}inspectLoopForToolCall($,W,Z){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:W});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:Z,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let W=await this.mistakeTracker.record($);if(W.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]}),this.activeRuntime?.abort(W.reason??W.message)})}buildLegacyResult($){let{runResult:W,thrownError:Z,startedAt:Q,endedAt:J}=$,j=J.getTime()-Q.getTime(),X=Z?"error":gR(W),Y=(W?.status==="failed"?W.error?.message:void 0)||W?.outputText||"",V=W?{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens>0?W.usage.cacheReadTokens:void 0,cacheWriteTokens:W.usage.cacheWriteTokens>0?W.usage.cacheWriteTokens:void 0,totalCost:W.usage.totalCost}:this.currentRunUsage,B=W?p8(W.messages):this.conversation.getMessages(),H=zG(this.config);if(Z)throw Z;return{text:Y,usage:V,messages:B,toolCalls:this.currentRunToolCalls,iterations:W?.iterations??0,finishReason:X,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Q,endedAt:J,durationMs:j}}}function xR($,W,Z,Q){if(!$)return;if(W==="debug"){$.debug(Z,Q);return}if(W==="error"&&$.error){$.error(Z,Q);return}let J=W==="warn"?"warn":W==="error"?"error":"info";$.log(Z,{...Q,severity:J})}function gR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function mR($,W,Z,Q){let{buildInitialUserContent:J}=await Promise.resolve().then(() => TG);return J($,W,Z,Q)}function zG($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let W=i3($);if(W?.[$.modelId])return W[$.modelId];return}import{buildClineSystemPrompt as qG}from"@cline/shared";function MG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return qG({ide:W.clineIdeName?.trim()||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,rules:`# Team Teammate Role
476
- ${Z}`,platform:W.clinePlatform,metadata:W.workspaceMetadata})}function RG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return qG({ide:W.clineIdeName||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,overridePrompt:Z,metadata:W.workspaceMetadata,platform:W.clinePlatform})}function P$($){let W={...$};return{getRuntimeConfig:()=>W,getConnectionConfig:()=>({providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn}),updateConnectionDefaults:(Z)=>{W={...W,...Z}}}}function w2($){let W=$.configProvider.getRuntimeConfig(),Z=$.kind==="teammate"?MG($.prompt,W):RG($.prompt,W);return{...$.configProvider.getConnectionConfig(),systemPrompt:Z,tools:$.tools,maxIterations:$.maxIterations??W.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:W.hooks,extensions:W.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:W.logger,role:$.role}}function S$($){let W=w2($),Z=new C$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);return Z}var uR=jJ.object({systemPrompt:jJ.string().describe("System prompt defining the sub-agent's behavior"),task:jJ.string().describe("Task for the sub-agent to complete")});function b$($){return vR({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:cR(uR),execute:async(W,Z)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(W,Z):$.subAgentTools??[],J=S$({kind:"subagent",prompt:W.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:Z.agentId,abortSignal:Z.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=J.getAgentId(),X=J.getConversationId(),Y=Z.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:X,parentAgentId:Y,input:W})}catch{}try{let V=await J.run(W.task),B={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,result:B,agentResult:V})}catch{}return B}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as f0,TEAM_AWAIT_TIMEOUT_MS as dR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as lR,TEAM_RUN_TEXT_PREVIEW_LIMIT as pR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as rR,TeamAttachOutcomeFragmentInputSchema as NG,TeamAwaitRunsInputSchema as EG,TeamBroadcastInputSchema as wG,TeamBroadcastToolResultSchema as iR,TeamCancelRunInputSchema as CG,TeamCancelRunToolResultSchema as nR,TeamCleanupInputSchema as PG,TeamCleanupToolResultSchema as aR,TeamCreateOutcomeInputSchema as SG,TeamCreateOutcomeToolResultSchema as oR,TeamFinalizeOutcomeInputSchema as bG,TeamFinalizeOutcomeToolResultSchema as sR,TeamListOutcomesInputSchema as yG,TeamListRunsInputSchema as hG,TeamMailboxMessageToolResultSchema as tR,TeamMissionLogInputSchema as kG,TeamMissionLogToolResultSchema as eR,TeamOutcomeFragmentToolResultSchema as IG,TeamOutcomeToolResultSchema as $N,TeamReadMailboxInputSchema as xG,TeamReviewOutcomeFragmentInputSchema as gG,TeamRunTaskInputSchema as mG,TeamRunTaskToolResultSchema as XJ,TeamRunToolSummarySchema as YJ,TeamSendMessageInputSchema as vG,TeamSendMessageToolResultSchema as WN,TeamShutdownTeammateInputSchema as cG,TeamSimpleAgentStatusToolResultSchema as uG,TeamSpawnTeammateInputSchema as dG,TeamStatusInputSchema as lG,TeamStatusToolResultSchema as ZN,TeamTaskInputSchema as pG,TeamTaskToolResultSchema as Z5,validateWithZod as g,zodToJsonSchema as D0}from"@cline/shared";function rG($,W){let Z=$.replace(/\s+/g," ").trim();if(Z.length<=W)return Z;return`${Z.slice(0,Math.max(0,W-3)).trimEnd()}...`}function C2($,W){if($===void 0)throw Error(`Missing required field: ${W}`);return $}function QN($){let W=$.result;if(!W)return;return{textPreview:rG(W.text,pR),iterations:W.iterations,finishReason:W.finishReason,durationMs:W.durationMs,usage:{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens,cacheWriteTokens:W.usage.cacheWriteTokens,totalCost:W.usage.totalCost}}}function WZ($){return $?.toISOString()}function VJ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:rG($.message,lR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:WZ($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:WZ($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:WZ($.heartbeatAt),lastProgressAt:WZ($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:QN($)}}function JN($){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 i8=["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 iG($){let W=[];if($.createBaseTools)W.push(...$.createBaseTools());W.push(...P2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:w2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:W,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function n8($){let W=$.leadAgentId??"lead",Z=$.restoredFromPersistence===!0,Q=P2({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;iG({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),J.push(j.agentId)}return{tools:Q,restoredFromPersistence:Z,restoredTeammates:J}}function P2($){let W=$.allowSpawn??!0,Z=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,J=[];if(Z)J.push(f0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:D0(dG),execute:async(X)=>{let Y=g(dG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!W)throw Error("Spawning teammates is disabled in this context.");let V={agentId:Y.agentId,rolePrompt:Y.rolePrompt};if(iG({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!Q)$.onLeadToolsUnlocked?.(P2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return g(uG,{agentId:Y.agentId,status:"spawned"})}}));if(!Q)return J;J.push(f0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:D0(cG),execute:async(X)=>{let Y=g(cG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(Y.agentId,Y.reason),g(uG,{agentId:Y.agentId,status:"stopped"})}})),J.push(f0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:D0(lG),execute:async(X)=>{return g(lG,X),g(ZN,$.runtime.getSnapshot())}})),J.push(f0({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:D0(pG),execute:async(X)=>{let Y=g(pG,X);switch(Y.action){case"create":{let V=new Set(rR.create??[]),B=Object.entries(X).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),H=$.runtime.createTask({title:C2(Y.title,"title"),description:C2(Y.description,"description"),dependsOn:Y.dependsOn,assignee:Y.assignee,createdBy:$.requesterId});return g(Z5,{action:"create",taskId:H.id,status:H.status,...B.length>0?{ignoredFields:B,note:`Ignored fields for action=create: ${B.join(", ")}`}:{}})}case"list":return g(Z5,{action:"list",tasks:$.runtime.listTaskItems({status:Y.status,assignee:Y.assignee})});case"claim":{let V=$.runtime.claimTask(C2(Y.taskId,"taskId"),$.requesterId);return g(Z5,{action:"claim",taskId:V.id,status:V.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 V=$.runtime.completeTask(C2(Y.taskId,"taskId"),$.requesterId,C2(Y.summary,"summary"));return g(Z5,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(C2(Y.taskId,"taskId"),$.requesterId,C2(Y.reason,"reason"));return g(Z5,{action:"block",taskId:V.id,status:V.status})}}}}));let j=new Map;return J.push(f0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:D0(mG),execute:async(X)=>{let Y=g(mG,X);if(Y.runMode==="async"){let H=$.runtime.startTeammateRun(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0});return g(XJ,{agentId:Y.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${Y.agentId} and queued as ${H.id}.`,runId:H.id})}let V=j.get(Y.agentId);if(V){let H=await V;return g(XJ,{...H,status:"joined",deduped:!0,message:`Task for ${Y.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let B=$.runtime.routeToTeammate(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0}).then((H)=>g(XJ,{agentId:Y.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${Y.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(Y.agentId)});return j.set(Y.agentId,B),await B}})),J.push(f0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:D0(CG),execute:async(X)=>{let Y=g(CG,X),V=$.runtime.cancelRun(Y.runId,Y.reason);return g(nR,{runId:V.id,status:V.status})}})),J.push(f0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:D0(hG),execute:async(X)=>g(YJ.array(),$.runtime.listRuns(g(hG,X)).map(VJ))})),J.push(f0({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:D0(EG),timeoutMs:dR,execute:async(X)=>{let Y=g(EG,X);if(Y.runId){let H=await $.runtime.awaitRun(Y.runId);return JN(H),g(YJ,VJ(H))}let V=await $.runtime.awaitAllRuns(),B=V.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(B.length>0){let H=B.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return g(YJ.array(),V.map(VJ))}})),J.push(f0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:D0(vG),execute:async(X)=>{let Y=g(vG,X),V=$.runtime.sendMessage($.requesterId,Y.toAgentId,Y.subject,Y.body,Y.taskId??void 0);return g(WN,{id:V.id,toAgentId:V.toAgentId})}})),J.push(f0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:D0(wG),execute:async(X)=>{let Y=g(wG,X),V=$.runtime.broadcast($.requesterId,Y.subject,Y.body,{taskId:Y.taskId??void 0});return g(iR,{delivered:V.length})}})),J.push(f0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:D0(xG),execute:async(X)=>{let Y=g(xG,X);return g(tR.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:Y.unreadOnly,markRead:!0}))}})),J.push(f0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:D0(kG),execute:async(X)=>{let Y=g(kG,X),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:Y.taskId||void 0,kind:Y.kind,summary:Y.summary,evidence:Y.evidence?.length?Y.evidence:void 0,nextAction:Y.nextAction||void 0});return g(eR,{id:V.id})}})),J.push(f0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:D0(PG),execute:async(X)=>{if(g(PG,X),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),g(aR,{status:"cleaned"})}})),J.push(f0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:D0(SG),execute:async(X)=>{let Y=g(SG,X),V=$.runtime.createOutcome({title:Y.title,requiredSections:Y.requiredSections,createdBy:$.requesterId});return g(oR,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(f0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:D0(NG),execute:async(X)=>{let Y=g(NG,X),V=$.runtime.attachOutcomeFragment({outcomeId:Y.outcomeId,section:Y.section,sourceAgentId:$.requesterId,sourceRunId:Y.sourceRunId||void 0,content:Y.content});return g(IG,{fragmentId:V.id,status:V.status})}})),J.push(f0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:D0(gG),execute:async(X)=>{let Y=g(gG,X),V=$.runtime.reviewOutcomeFragment({fragmentId:Y.fragmentId,reviewedBy:$.requesterId,approved:Y.approved});return g(IG,{fragmentId:V.id,status:V.status})}})),J.push(f0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:D0(bG),execute:async(X)=>{let Y=g(bG,X),V=$.runtime.finalizeOutcome(Y.outcomeId);return g(sR,{outcomeId:V.id,status:V.status})}})),J.push(f0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:D0(yG),execute:async(X)=>{return g(yG,X),g($N.array(),$.runtime.listOutcomes())}})),J}function ZZ($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}function nG($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var jN=[{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:b$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...i8]}],XN={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function YN($){return $==="plan"||$==="yolo"?$:"act"}function oG($){let W=YN($.mode),Z=a0[t1({mode:W})],Q=l8($.providerId??"",$.modelId??"",W,d8);return{mode:W,flags:{...Z,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function aG($,W){if(W.disabledToolIds?.has($))return!1;let{flags:Z}=oG(W);if($==="spawn_agent")return Z.enableSpawnAgent===!0;if($==="teams")return Z.enableAgentTeams===!0;if($==="editor")return Z.enableEditor===!0||Z.enableApplyPatch===!0;let Q=XN[$];return Q?Z[Q]===!0:!1}function VN($,W){if($.id==="editor"){let{flags:Z}=oG(W),Q=Z.enableApplyPatch===!0&&Z.enableEditor!==!0;return{...$,defaultEnabled:aG($.id,W),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:aG($.id,W)}}function S2($={}){return jN.map((W)=>VN(W,$))}function QZ($={}){return S2($).filter((W)=>W.defaultEnabled).map((W)=>W.id)}function JZ($){if(!$.enabled)return new Set;let W=S2($.availabilityContext),Z=new Set(W.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(W.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!Z.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${W.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function Q5($,W={}){return S2(W).filter((Z)=>$.has(Z.id)).flatMap((Z)=>Z.headlessToolNames)}function jZ($,W={}){return Q5($,W)}function b2($={}){let{executorOptions:W={},executors:Z,...Q}=$,J={...u8(W),...Z??{}};return N$({...Q,executors:J})}import{mkdirSync as AN,writeFileSync as UN}from"node:fs";import{dirname as fN}from"node:path";import{normalizeUserInput as DN,stripModeNotices as _N}from"@cline/shared";import{nanoid as LN}from"nanoid";var tG={};w(tG,{sanitizeSessionToken:()=>y2,parseTeamTaskSubSessionId:()=>o8,parseSubSessionId:()=>j5,makeTeamTaskSubSessionId:()=>J5,makeSubSessionId:()=>a8,deriveSubsessionStatus:()=>X5});import{nanoid as GN}from"nanoid";function y2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function a8($,W){let Z=y2($),Q=y2(W),J=`${Z}__${Q}`;return J.length>180?J.slice(0,180):J}function J5($,W){let Z=y2($),Q=y2(W);return`${Z}__teamtask__${Q}__${GN(6)}`}function o8($){let Z=$.indexOf("__teamtask__");if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+12),j=J.lastIndexOf("__");if(j<=0)return null;let X=J.slice(0,j),Y=J.slice(j+2);if(!Q||!X||!Y)return null;return{rootSessionId:Q,agentId:X,teamTaskId:Y}}function j5($){if(o8($))return null;let W="__",Z=$.indexOf(W);if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+W.length);if(!Q||!J)return null;return{rootSessionId:Q,agentId:J}}function X5($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let W=String($.reason??"").toLowerCase();if(W.includes("cancel")||W.includes("abort")||W.includes("interrupt"))return"cancelled";if(W.includes("fail")||W.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as W0}from"zod";var WK={};w(WK,{isTerminalSessionStatus:()=>$K,isNonTerminalSessionStatus:()=>K0,SessionSource:()=>F0,SESSION_STATUSES:()=>Y5,NON_TERMINAL_SESSION_STATUSES:()=>eG});import{SESSION_STATUS_VALUES as KN}from"@cline/shared";var Y5=KN,eG=["idle","running","pending"];function $K($){return!eG.includes($)}function K0($){return!$K($)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var FN=W0.enum(Y5),g0=W0.object({version:W0.literal(1),session_id:W0.string().min(1),source:W0.string().min(1),pid:W0.number().int(),started_at:W0.string().min(1),ended_at:W0.string().min(1).optional(),exit_code:W0.number().int().nullable().optional(),status:FN,interactive:W0.boolean(),provider:W0.string().min(1),model:W0.string().min(1),cwd:W0.string().min(1),workspace_root:W0.string().min(1),team_name:W0.string().min(1).optional(),enable_tools:W0.boolean(),enable_spawn:W0.boolean(),enable_teams:W0.boolean(),prompt:W0.string().optional(),metadata:W0.record(W0.string(),W0.unknown()).optional(),messages_path:W0.string().min(1).optional(),compaction_path:W0.string().min(1).optional()});function ZK($){if(!$)return!1;return Object.values($).some((W)=>typeof W==="function")}function HJ($,W){let Z=[...$??[],...W??[]];if(Z.length===0)return;let Q=[],J=new Set;for(let j of Z){if(J.has(j.name))continue;J.add(j.name),Q.push(j)}return Q}function QK($){return JSON.stringify($,(W,Z)=>{if(Z instanceof Error)return{name:Z.name,message:Z.message,stack:Z.stack};return Z})}function e1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function BJ($,W){let Z={...$};Z.id=e1(Z.id)??LN();let Q=Z.modelInfo&&typeof Z.modelInfo==="object"?{...Z.modelInfo}:void 0,J={id:e1(Q?.id)??e1(Z.modelId)??e1(W?.id),provider:e1(Q?.provider)??e1(Z.providerId)??e1(W?.provider),family:e1(Q?.family)??e1(W?.family)};if(delete Z.providerId,delete Z.modelId,J.id&&J.provider)Z.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Z.modelInfo;return Z}function XZ($){return $.map((W)=>BJ(W))}function YZ($,W,Z=[]){let Q=$.map((V,B)=>{let H=Z[B],K=H?.role===V.role&&JSON.stringify(H.content)===JSON.stringify(V.content)?{...H,...V}:{...V};return BJ(K)}),J=Z.length,j=[];for(let V=J;V<Q.length;V+=1)if(Q[V]?.role==="assistant")j.push(V);if(j.length===0){let V=[...Q].reverse().findIndex((B)=>B.role==="assistant");if(V===-1)return Q;j.push(Q.length-1-V)}let X=j[j.length-1],Y=j.some((V)=>Q[V]?.metrics);for(let V of j){let B=Q[V],H=B.metrics;if(!H&&V===X&&!Y){let G=W.usage;H={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}Q[V]={...BJ(B,{id:W.model.id,provider:W.model.provider,family:W.model.info?.family}),...H?{metrics:H}:{},ts:B.ts??W.endedAt.getTime()}}return Q}function V5($){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 TN=120;function h2($){let W=$?.trim();return W?W.slice(0,TN):void 0}function GJ($){let W=_N(DN($??"")).trim();if(!W)return;return h2(W.split(`
477
- `)[0]?.trim())}function y$($){if(!$)return;let W={...$},Z=h2(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function B5($){let W=y$($.metadata)??{},Z=$.title!==void 0?h2($.title):GJ($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function KJ($){let W=o8($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=j5($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function FJ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:XZ($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function JK($,W,Z){AN(fN($),{recursive:!0}),UN($,`${JSON.stringify(FJ({updatedAt:W,context:Z,messages:[]}),null,2)}
478
- `,"utf8")}function jK($,W){return g0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.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:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function XK($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}M0();var YK={};w(YK,{summarizeUsageFromMessages:()=>t8,sumUsageTotals:()=>H5,getCurrentContextSize:()=>AJ,createInitialAccumulatedUsage:()=>O0,accumulateUsageTotals:()=>_0});function O0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function _0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function H5($){let W=O0();for(let Z of $)W=_0(W,Z);return W}function s8($){return typeof $==="number"&&Number.isFinite($)?$:0}function t8($){let W=O0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=_0(W,{inputTokens:s8(Q.inputTokens),outputTokens:s8(Q.outputTokens),cacheReadTokens:s8(Q.cacheReadTokens),cacheWriteTokens:s8(Q.cacheWriteTokens),totalCost:s8(Q.cost)})}return W}function AJ($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=s8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function ON($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function UJ($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function $$($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function zN($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function qN($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function fJ($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=UJ(W),G=$$({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=ON(W.input);if(K)aW(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(_8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))oW(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")X4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")X4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=zN(W);if(B){j.turnPrimaryUsage=_0(j.turnPrimaryUsage??O0(),K);let A=_0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),D8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),iW(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=qN({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),f=j.turnUsageByAgent??new Map;j.turnUsageByAgent=f,f.set(A,_0(f.get(A)??O0(),K))}let F=_0(j.turnPrimaryUsage??O0(),H5(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,_0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:QK(W),ts:Date.now()}})}function W$($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as Sw}from"@cline/llms";import{hasRuntimeConfigExtension as bw}from"@cline/shared";X1();import{existsSync as FZ,readFileSync as HE,statSync as GE}from"node:fs";import{basename as KE,dirname as GZ,join as AZ,resolve as KZ}from"node:path";import{discoverPluginModulePaths as FE,resolveConfiguredPluginModulePaths as wK,resolvePluginConfigSearchPaths as AE,SKILLS_CONFIG_DIRECTORY_NAME as UE}from"@cline/shared/storage";import{resolve as dN}from"node:path";import{normalizePluginManifest as lN}from"@cline/shared";import{existsSync as E0,readFileSync as $6}from"node:fs";import{builtinModules as MN,createRequire as TJ}from"node:module";import{dirname as h$,extname as K5,isAbsolute as RN,resolve as o}from"node:path";import{fileURLToPath as BK}from"node:url";import{PLUGIN_FILE_EXTENSIONS as NN}from"@cline/shared";var HK=h$(BK(import.meta.url)),EN=TJ(import.meta.url),wN=o(HK,"..","..","..","..",".."),DJ=SN(wN),CN=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],OJ=new Set(MN.flatMap(($)=>[$,$.replace(/^node:/,"")])),G5=new Set(NN),PN=["development","node","import","require","default"];function SN($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(E0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!E0(j))continue;try{let X=JSON.parse($6(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(E0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=bN(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function bN($,W){let Z=zJ(W);if(!Z)return null;let Q=GK($,Z);for(let J of Q)if(E0(J))return J;return null}function zJ($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of PN){let J=zJ(Z[Q],W);if(J)return J}return null}function GK($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function yN($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function VZ($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function e8($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function hN($){let W=e8($);if($===W)return".";return`.${$.slice(W.length)}`}function KK($){return e8($).startsWith("@cline/")}function _J($,W){let Z=e8(W),Q=h$($);while(!0){let J=o(Q,"node_modules",Z);if(E0(J)||E0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function VK($){return LJ($)!==null}function LJ($){try{return EN.resolve($)}catch{}return kN($)}function kN($){let W=e8($),Z=FK(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse($6(Q,"utf8")),j=hN($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=zJ(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...GK(Z,Y).filter((H)=>H!==V)];for(let H of B)if(E0(H))return H;return null}catch{return null}}function IN(){let $=[HK],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(h$(h$(W)));let Z=process.execPath?.trim();if(Z)$.push(h$(Z));return[...new Set($.map((Q)=>o(Q)))]}function xN($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(E0(Q))try{if(JSON.parse($6(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(E0(J))return h$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function FK($){for(let W of IN()){let Z=xN(W,$);if(Z)return Z}return null}function gN($){let Z=h$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(E0(J))try{let X=JSON.parse($6(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function AK($,W){let Z=W.startsWith("file:")?BK(W):RN(W)?W:o(h$($),W);if(E0(Z)&&G5.has(K5(Z)))return Z;for(let Q of G5){let J=`${Z}${Q}`;if(E0(J))return J}for(let Q of G5){let J=o(Z,`index${Q}`);if(E0(J))return J}return null}function UK($){let W=new Set,Z=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function mN($){return K5($)!==".ts"}function fK($,W,Z=new Set){if(Z.has($)||!E0($))return;if(Z.add($),!G5.has(K5($)))return;let Q=$6($,"utf8"),J=mN($);for(let j of UK(Q)){if(j.startsWith("node:")||OJ.has(j))continue;if(VZ(j)){if(!J)continue;if(Object.hasOwn(DJ,j)||Object.hasOwn(DJ,e8(j))||_J($,j)||KK(j)&&VK(j)||W&&VK(j))continue;throw Error(`Cannot find module '${e8(j)}'`)}let X=AK($,j);if(X)fK(X,W,Z)}}function DK($,W=new Set,Z=new Set){if(W.has($)||!E0($))return Z;if(W.add($),!G5.has(K5($)))return Z;let Q=$6($,"utf8");for(let J of UK(Q)){if(Z.add(J),VZ(J))continue;let j=AK($,J);if(j)DK(j,W,Z)}return Z}function vN($,W){let Z=TJ($),Q={},J=DK($),j=new Set(CN);for(let[X,Y]of Object.entries(DJ)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if(VZ(X)&&(KK(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||_J($,X))continue;let Y=LJ(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!VZ(X)||Object.hasOwn(Q,X)||_J($,X)||X.startsWith("node:")||OJ.has(X))continue;let Y=LJ(X);if(Y)Q[X]=Y}return Q}function cN($){let W=K5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var k2;function uN(){if(k2!==void 0)return k2;let $=FK("jiti");if(!$)return k2=null,null;let W=o($,"dist","babel.cjs");if(!E0(W))return k2=null,null;try{let Q=TJ(W)(W);k2=typeof Q==="function"?Q:null}catch{k2=null}return k2}async function _K($,W={}){let Z=!gN($);fK($,Z);let Q=vN($,Z),J=yN(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>cN(G)).map(([G])=>G),V=uN(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...OJ],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function LK($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function TK($){return typeof $==="object"&&$!==null}function qJ($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function pN($,W){if(!TK($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!qJ($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!qJ($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!qJ($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function rN($,W){if(!TK($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);pN($,W)}async function F5($,W={}){let Z=dN(W.cwd??process.cwd(),$),Q=await _K(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];rN(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:lN(X.manifest),setup:V}}async function BZ($,W={}){return(await I2($,W)).plugins}async function I2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await F5(Y,W);if(!LK(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as EJ}from"node:fs";import{createRequire as EK}from"node:module";import{dirname as HZ,join as Z6}from"node:path";import{fileURLToPath as sN}from"node:url";var RK={};w(RK,{resolveSubprocessRuntimeExecutable:()=>MJ,buildSubprocessSandboxCommand:()=>MK,SubprocessSandbox:()=>W6,CLINE_JS_RUNTIME_PATH_ENV:()=>qK});import{spawn as iN}from"node:child_process";import{basename as nN}from"node:path";import{augmentNodeCommandForDebug as aN,withResolvedClineBuildEnv as oN}from"@cline/shared";function OK($){if($ instanceof Error)return $;return Error(String($))}var qK="CLINE_JS_RUNTIME_PATH";function zK($){let W=$?.trim();if(!W)return!1;let Z=nN(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function MJ($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[qK]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(zK(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&zK(j))return j}return"node"}function MK($,W={}){let Z=MJ({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return aN([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class W6{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=MK($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=iN(W[0]??MJ(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:oN(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${OK(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${OK(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),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 W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function tN($){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 A5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function eN(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function $E(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=EK($).resolve(`${eN()}/package.json`),Q=Z6(HZ(Z),"extensions","plugin-sandbox-bootstrap.js");return EJ(Q)?Q:void 0}catch{return}}function WE(){let $=process.execPath?.trim();if(!$)return;let W=Z6(HZ(HZ($)),"extensions","plugin-sandbox-bootstrap.js");return EJ(W)?W:void 0}function ZE(){let $=HZ(sN(import.meta.url)),W=EK(import.meta.url),Z=[Z6($,"plugin-sandbox-bootstrap.js"),Z6($,"extensions","plugin-sandbox-bootstrap.js"),Z6($,"agents","plugin-sandbox-bootstrap.js"),$E(),WE()];for(let j of Z.filter((X)=>typeof X==="string"))if(EJ(j))return{file:j};let Q=Z6($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
479
- `)}}var RJ=ZE();function NJ($,W,Z){if(typeof $==="number"&&$>0)return $;if(Z){let Q=process.env[Z];if(Q){let J=Number(Q);if(Number.isInteger(J)&&J>0)return J}}return W}async function Q6($){let W=new W6({name:"plugin-sandbox",..."file"in RJ?{bootstrapFile:RJ.file}:{bootstrapScript:RJ.script},onEvent:$.onEvent}),Z=NJ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=NJ($.hookTimeoutMs,3000),J=NJ($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},X,Y=()=>{return X??=W.call("initialize",j,{timeoutMs:Z}).finally(()=>{X=void 0}),X},V;try{V=await W.call("initialize",j,{timeoutMs:Z})}catch(G){throw await W.shutdown().catch(()=>{}),G}let B=V.plugins.map(tN);return{extensions:B.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{QE(F,W,G,J,Y),JE(F,W,G,J,Y),jE(F,W,G,J,Y),YE(F,W,G,J,Y),XE(F,G)}};return K.hooks=BE(W,G,Q,Y),K}),failures:V.failures,pluginPaths:B.map((G)=>G.pluginPath),shutdown:async()=>{await W.shutdown()},warnings:V.warnings}}function QE($,W,Z,Q,J){for(let j of Z.contributions?.tools??[]){let X={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(Y,V)=>{try{return await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}catch(B){if(!A5(B))throw B;return await J(),await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}}};$.registerTool(X)}}function JE($,W,Z,Q,J){for(let j of Z.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(X)=>{try{return await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}catch(Y){if(!A5(Y))throw Y;return await J(),await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}}})}function jE($,W,Z,Q,J){for(let j of Z.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}catch(X){if(!A5(X))throw X;return await J(),await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}}:j.content??""})}function XE($,W){for(let Z of W.contributions?.providers??[])$.registerProvider({name:Z.name,description:Z.description,metadata:Z.metadata});for(let Z of W.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Z.eventType,source:Z.source,description:Z.description,attributesSchema:Z.attributesSchema,payloadSchema:Z.payloadSchema,examples:Z.examples,metadata:Z.metadata});for(let Z of W.contributions?.mcpServers??[])$.registerMcpServer(Z)}function YE($,W,Z,Q,J){for(let j of Z.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(X){try{let Y=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return NK(Y)?Y:X}catch(Y){if(!A5(Y))throw Y;await J();let V=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return NK(V)?V:X}}})}function NK($){return Array.isArray($)&&$.every((W)=>typeof W==="object"&&W!==null&&("role"in W)&&("content"in W))}function VE($,W,Z,Q,J){return async(j)=>{try{return await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}catch(X){if(!A5(X))throw X;return await J(),await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}}}function BE($,W,Z,Q){let J={};for(let j of W.hooks??[])J[j]=VE($,W.pluginId,j,Z,Q);return Object.keys(J).length>0?J:void 0}var CJ="package.json",fE="package";function U5($){return AE($)}function f5($){return FE($)}function DE($){try{return FZ($)&&GE($).isDirectory()}catch{return!1}}function PJ($){let W=[],Z=new Set;for(let Q of $){let J=KZ(Q);if(Z.has(J))continue;Z.add(J),W.push(J)}return W}function CK($){let W=PJ($);return V9(W)}function PK($){return U5($).flatMap((W)=>f5(W)).filter((W)=>FZ(W))}function _E($,W){let Z=[];for(let Q of $)try{Z.push(...wK([Q],W))}catch{}return Z}function wJ($){return typeof $==="object"&&$!==null}function LE($){try{let W=JSON.parse(HE(AZ($,CJ),"utf8"));if(!wJ(W)||!wJ(W.cline))return[];let Z=W.cline.plugins;if(!Array.isArray(Z))return[];let Q=[];for(let J of Z){if(typeof J==="string"){Q.push(J);continue}if(!wJ(J)||!Array.isArray(J.paths))continue;for(let j of J.paths)if(typeof j==="string")Q.push(j)}return Q}catch{return[]}}function SK($,W){let Z=KZ(W);return LE($).some((Q)=>KZ($,Q)===Z)}function TE($,W){return KE($)===fE&&FZ(AZ(GZ($),CJ))&&SK(GZ($),W)}function OE($){let W=KZ($),Z=[],Q=GZ(W);while(!0){if(TE(Q,W)){Z.push(Q);break}if(FZ(AZ(Q,CJ))){if(SK(Q,W))Z.push(Q);break}let J=GZ(Q);if(J===Q)break;Q=J}return PJ(Z)}function Z$($={}){let W=$.cwd??process.cwd(),Z=PK($.workspacePath),Q=wK($.pluginPaths??[],W);return CK([...Q,...Z])}function zE($={}){let W=$.cwd??process.cwd(),Z=PK($.workspacePath),Q=_E($.pluginPaths??[],W);return CK([...Q,...Z])}function Q$($){let W=[];for(let Z of $)for(let Q of OE(Z)){let J=AZ(Q,UE);if(DE(J))W.push(J)}return PJ(W)}function bK($={}){return Q$(zE($))}async function J6($={}){let W=Z$($);if(W.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await I2(W,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let Z=await Q6({pluginPaths:W,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:Z.extensions??[],shutdown:Z.shutdown,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}import{execFile as qE}from"node:child_process";import{promisify as ME}from"node:util";var RE=ME(qE);function SJ($,W){$?.log(W,{severity:"warn"})}function NE($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))return;let Z=W;if(!Z.latest||!Array.isArray(Z.history))return;let Q=Z.latest,J=Z.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:J}}async function x2($,W){let Z=await RE("git",["-C",$,...W],{windowsHide:!0});return{stdout:Z.stdout.trim(),stderr:Z.stderr.trim()}}async function bJ($,W){if(!$)return;let Z=`refs/cline/checkpoints/${W}/`;try{let{stdout:Q}=await x2($,["for-each-ref","--format=%(refname)",Z]),J=Q.trim().split(`
480
- `).filter(Boolean);await Promise.allSettled(J.map((j)=>x2($,["update-ref","-d",j])))}catch{}}async function yK($,W,Z){if(!$||Z.length===0)return;await Promise.allSettled(Z.map((Q)=>x2($,["update-ref",`refs/cline/checkpoints/${W}/${Q.runCount}`,Q.ref])))}function EE($,W){let Z=$.findIndex((Q)=>Q.runCount===W.runCount);if(Z<0)return[...$,W];return $.map((Q,J)=>J===Z?W:Q)}function hK($){let W=$.initialRunCount??0,Z,Q=async()=>{if(Z!==void 0)return Z;try{Z=(await x2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Z=!1}return Z},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:W});if(!await Q())return;let j=async(B)=>{try{let G=(await x2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:W,kind:"commit"}}catch(H){SJ($.logger,`${B}: ${H instanceof Error?H.message:String(H)}`);return}},X=`cline checkpoint session=${$.sessionId} run=${W}`,Y="";try{Y=(await x2($.cwd,["stash","create",X])).stdout.trim()}catch(B){return SJ($.logger,`Checkpoint snapshot failed: ${B instanceof Error?B.message:String(B)}`),j("Checkpoint HEAD fallback failed")}if(!Y)return j("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${W}`;try{await x2($.cwd,["update-ref",V,Y])}catch(B){SJ($.logger,`Checkpoint store failed: ${B instanceof Error?B.message:String(B)}`);return}return{ref:Y,createdAt:Date.now(),runCount:W,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;W+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||W<1)return;let X=await J();if(!X)return;let Y=await $.readSessionMetadata(),V=NE(Y);if(V?.latest.ref===X.ref)return;let B=EE(V?.history??[],X);await $.writeSessionMetadata({...Y??{},checkpoint:{latest:X,history:B}});return}}}import{spawn as IE}from"node:child_process";import{appendFileSync as xE,readFileSync as gE}from"node:fs";import{join as mE}from"node:path";import{augmentNodeCommandForDebug as xK,withResolvedClineBuildEnv as kJ}from"@cline/shared";import{ensureHookLogDir as kK}from"@cline/shared/storage";function j6($,W){if(!W)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:W}}import{existsSync as wE,readdirSync as CE}from"node:fs";import{basename as PE,extname as SE,join as bE}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as UZ,resolveHooksConfigSearchPaths as yE}from"@cline/shared/storage";function D5($){return yE($)}var X6;((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"})(X6||={});var _5={["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"},hE=new Map(Object.values(X6).map(($)=>[$.toLowerCase(),$])),kE=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function L5($){let W=SE($).toLowerCase();if(!kE.has(W))return;let Z=PE($,W).trim().toLowerCase();return hE.get(Z)}function k$($){let W=[],Z=new Set,Q=D5($).filter((J)=>wE(J));for(let J of Q)try{for(let j of CE(J,{withFileTypes:!0})){if(!j.isFile())continue;let X=L5(j.name);if(!X)continue;let Y=bE(J,j.name);if(Z.has(Y))continue;Z.add(Y),W.push({fileName:X,hookEventName:_5[X],path:Y})}}catch{}return W.sort((J,j)=>J.path.localeCompare(j.path))}function DZ($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))W[Z]=typeof Q==="string"?Q:JSON.stringify(Q);return W}function fZ($,W,Z){let Q=Z instanceof Error?`: ${Z.message}`:"",J=`${W}${Q}`;if($){try{$.log(J,{severity:"warn",...Z!==void 0?{error:Z}:{}})}catch{}return}console.warn(J)}function vE($,W){if(!W)return $;if(!$)return{...W};let Z=[$.context,W.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
481
- `),Q=[...$.appendMessages??[],...W.appendMessages??[]];return{cancel:$.cancel===!0||W.cancel===!0?!0:void 0,review:$.review===!0||W.review===!0?!0:void 0,context:Z||void 0,overrideInput:W.overrideInput!==void 0?W.overrideInput:$.overrideInput,systemPrompt:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function cE($){if(!$||typeof $!=="object")return;let W=$,Z=typeof W.context==="string"?W.context:typeof W.contextModification==="string"?W.contextModification:typeof W.errorMessage==="string"?W.errorMessage:void 0;return{cancel:typeof W.cancel==="boolean"?W.cancel:void 0,review:typeof W.review==="boolean"?W.review:void 0,context:Z,overrideInput:Object.hasOwn(W,"overrideInput")?W.overrideInput:void 0}}function yJ($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function w0($,W){let Z=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:W.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:W.workspacePath?[W.workspacePath]:[],workspaceInfo:W.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function uE($){let W=$.trim();if(!W)return{};let Q=W.split(`
482
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function dE($,W){let Z=$.stdin;if(!Z)throw Error("hook command failed to create stdin");await new Promise((Q,J)=>{let j=!1,X=()=>{Z.off("error",V),Z.off("finish",B),$.off("close",H)},Y=(G)=>{if(j)return;if(j=!0,X(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){Q();return}J(G);return}Q()},V=(G)=>Y(G),B=()=>Y(),H=()=>Y();Z.on("error",V),Z.once("finish",B),$.once("close",H);try{Z.end(W)}catch(G){Y(G)}})}async function gK($,W){if(W.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await IK($,W)}catch(Z){let Q=rE(W.command,process.platform,Z);if(!Q)throw Z;return await IK($,{...W,command:Q})}}async function IK($,W){let Z=xK(W.command,{env:W.env,debugRole:"hook"}),Q=IE(Z[0],Z.slice(1),{cwd:W.cwd,env:kJ(W.env),stdio:W.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W.detached,windowsHide:!0}),J=new Promise((K)=>{Q.once("spawn",()=>K())}),j=new Promise((K,F)=>{Q.once("error",(A)=>F(A))}),X=JSON.stringify($);if(await Promise.race([J,j]),await dE(Q,X),W.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let Y="",V="",B=!1,H;Q.stdout.on("data",(K)=>{Y+=K.toString()}),Q.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,Q.kill("SIGKILL")},W.timeoutMs);Q.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:f}=uE(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:f,timedOut:B})})});return await Promise.race([G,j])}function lE($){try{let Z=gE($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Z?.startsWith("#!"))return;let Q=Z.slice(2).trim();if(!Q)return;let J=Q.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function pE($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function rE($,W=process.platform,Z){if(W!=="win32"||!pE(Z))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function mK($){if($.length===0)return;let[W,...Z]=$,Q=W.replace(/\\/g,"/").toLowerCase(),J=Q.split("/").at(-1)??Q;if(J==="env")return mK(Z);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Z];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Z]:[J,...Z];return $}function iE($){let W=lE($);if(W&&W.length>0)return[...mK(W)??W,$];let Z=$.toLowerCase();if(Z.endsWith(".sh")||Z.endsWith(".bash")||Z.endsWith(".zsh"))return["bash",$];if(Z.endsWith(".js")||Z.endsWith(".mjs")||Z.endsWith(".cjs"))return xK(["node",$],{debugRole:"hook"});if(Z.endsWith(".ts")||Z.endsWith(".mts")||Z.endsWith(".cts"))return["bun","run",$];if(Z.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Z.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function nE($){let W={};for(let Z of k$($)){if(!Z.hookEventName)continue;let Q=Z.hookEventName,J=W[Q]??[];J.push(iE(Z.path)),W[Q]=J}return W}async function aE($){let W;for(let Z of $.commands){let Q=Z.join(" ");try{let J=await gK($.payload,{command:Z,cwd:$.cwd,env:kJ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){fZ($.logger,`hook command timed out: ${Q}`);continue}if(J?.parseError){fZ($.logger,`hook command returned invalid JSON control output: ${Q} (${J.parseError})`);continue}W=vE(W,cE(J?.parsedJson))}catch(J){fZ($.logger,`hook command failed: ${Q}`,J)}}return W}function g2($){for(let W of $.commands){let Z=W.join(" ");gK($.payload,{command:W,cwd:$.cwd,env:kJ(process.env),detached:!0}).catch((Q)=>{fZ($.logger,`hook command failed: ${Z}`,Q)})}}function I$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function hJ($,W){return{...I$($.snapshot),userMessage:W}}function vK($){return{...I$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function cK($){return{...I$($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function uK($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function oE($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}function Y6($){let W={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Z=(Q)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
483
- `,X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??mE(kK(),"hooks.jsonl");kK(X),xE(X,J,"utf8")};return{beforeRun:async(Q)=>{let J=hJ(Q,"");Z({...w0(J,W),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let J=vK(Q);Z({...w0(J,W),hookName:"tool_call",iteration:J.iteration,tool_call:{id:J.call.id,name:J.call.name,input:J.call.input},preToolUse:{toolName:J.call.name,parameters:DZ(J.call.input)}});return},afterTool:async(Q)=>{let J=cK(Q);Z({...w0(J,W),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:DZ(J.record.input),result:typeof J.record.output==="string"?J.record.output:JSON.stringify(J.record.output),success:!J.record.error,executionTimeMs:J.record.durationMs}});return},afterRun:async({snapshot:Q,result:J})=>{let j=I$(Q);if(J.status==="completed"){Z({...w0(j,W),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||yJ(J.error?.message)){Z({...w0(j,W),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Z({...w0(j,W),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let J=hJ({snapshot:Q.snapshot},uK(Q.message.content));Z({...w0(J,W),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function T5($){let W=nE($.workspacePath);if(!Object.values(W).some((G)=>G.length>0))return;let Q=async(G,K)=>{let F=W[K]??[];if(F.length===0)return;g2({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...w0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...w0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=W.prompt_submit??[];if(K.length>0)g2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},j=async(G)=>{let K=W.tool_call??[];if(K.length===0)return;return aE({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...w0(G,$),hookName:"tool_call",iteration:G.iteration,tool_call:{id:G.call.id,name:G.call.name,input:G.call.input},preToolUse:{toolName:G.call.name,parameters:DZ(G.call.input)}}})},X=async(G)=>{let K=W.tool_result??[];if(K.length===0)return;g2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:DZ(G.record.input),result:typeof G.record.output==="string"?G.record.output:JSON.stringify(G.record.output),success:!G.record.error,executionTimeMs:G.record.durationMs}}})},Y=async(G)=>{let K=W.agent_end??[];if(K.length===0)return;g2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=W.agent_error??[];if(K.length===0)return;g2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},B=async(G)=>{if(yJ(G.reason)){let F=W.agent_abort??[];if(F.length>0)g2({commands:F,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=W.session_shutdown??[];if(K.length===0)return;g2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"session_shutdown",reason:G.reason}})},H={};if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0||(W.prompt_submit?.length??0)>0){if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0)H.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(I$(G.snapshot),K);return};if((W.prompt_submit?.length??0)>0)H.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(hJ({snapshot:G.snapshot},uK(G.message.content)))}}if((W.tool_call?.length??0)>0)H.beforeTool=async(G)=>{let K=await j(vK(G));return oE(K)};if((W.tool_result?.length??0)>0)H.afterTool=async(G)=>{await X(cK(G));return};if((W.agent_end?.length??0)>0)H.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await Y({...I$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((W.agent_error?.length??0)>0||(W.agent_abort?.length??0)>0||(W.session_shutdown?.length??0)>0){let G=H.afterRun;H.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||yJ(A.error?.message)){await B({...I$(F),reason:A.error?.message});return}if(A.error)await V({...I$(F),iteration:A.iterations,error:A.error})}}return H}function V6($){return j6("core.hook_config_files",T5($))}function m2($,W){let Z=$.map((Q)=>Q[W]).filter((Q)=>typeof Q==="function");if(Z.length===0)return;return async(Q)=>{let J;for(let j of Z){let X=await j(Q);if(!X||typeof X!=="object")continue;let Y=X;J={...J??{},...Y,stop:J?.stop===!0||Y.stop===!0?!0:Y.stop,options:J?.options||Y.options?{...J?.options??{},...Y.options??{}}:void 0}}return J}}function v2($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return;return{beforeRun:m2(W,"beforeRun"),afterRun:m2(W,"afterRun"),beforeModel:m2(W,"beforeModel"),afterModel:m2(W,"afterModel"),beforeTool:m2(W,"beforeTool"),afterTool:m2(W,"afterTool"),onEvent:m2(W,"onEvent")}}var dK={};w(dK,{normalizeRuntimeCapabilities:()=>C0});function C0(...$){let W,Z;for(let J of $){if(!J)continue;if(J.toolExecutors)W={...W??{},...J.toolExecutors};if(J.requestToolApproval)Z=J.requestToolApproval}let Q=W&&Object.keys(W).length>0;if(!Q&&!Z)return;return{...Q?{toolExecutors:W}:{},...Z?{requestToolApproval:Z}:{}}}var tK={};w(tK,{toProviderConfig:()=>s0,emptyStoredProviderSettings:()=>m$,StoredProviderSettingsSchema:()=>K6,StoredProviderSettingsEntrySchema:()=>vZ,ProviderSettingsSchemaTyped:()=>G6});import{z as g$}from"zod";var sK={};w(sK,{toProviderConfig:()=>s0,safeParseSettings:()=>mZ,safeCreateProviderConfig:()=>pJ,parseSettings:()=>gZ,normalizeProviderId:()=>H6,isBuiltInProviderId:()=>dJ,createProviderConfig:()=>lJ,SapSettingsSchema:()=>kZ,ReasoningSettingsSchema:()=>SZ,ProviderSettingsSchema:()=>x$,ProviderProtocolSchema:()=>wZ,ProviderIdSchema:()=>R5,ProviderClientSchema:()=>CZ,OcaSettingsSchema:()=>IZ,ModelCatalogSettingsSchema:()=>xZ,GcpSettingsSchema:()=>yZ,BUILT_IN_PROVIDER_IDS:()=>uJ,BUILT_IN_PROVIDER:()=>M5,AzureSettingsSchema:()=>hZ,AwsSettingsSchema:()=>bZ,AuthSettingsSchema:()=>PZ});import*as o0 from"@cline/llms";import{z as E}from"zod";var oK={};w(oK,{resolveProviderConfig:()=>q5,getProviderConfig:()=>EZ,getLiveModelsCatalog:()=>B6,clearPublicModelsCatalogCache:()=>Lw,clearPrivateModelsCatalogCache:()=>cJ,clearLiveModelsCatalogCache:()=>vJ,OPENAI_COMPATIBLE_PROVIDERS:()=>z5,DEFAULT_MODELS_CATALOG_URL:()=>qZ});import*as e from"@cline/llms";function IJ($){if(!Array.isArray($))return[];return $.map((W)=>{if(typeof W==="string")return W.trim();if(W&&typeof W==="object"){let Z=W;for(let Q of[Z.id,Z.name,Z.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((W)=>W.length>0)}function sE($,W){let Z=IJ($);if(Z.length>0)return Z;if(!$||typeof $!=="object")return[];let Q=$,J=IJ(Q.data??Q.models);if(J.length>0)return J;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let X=Object.keys(Q.models).filter((Y)=>Y.trim().length>0);if(X.length>0)return X}let j=Q.providers?.[W];if(j&&typeof j==="object"){let Y=IJ(j.models??j);if(Y.length>0)return Y}return[]}async function _Z($,W){let Z=await fetch($,{method:"GET"});if(!Z.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Z.status}`);return sE(await Z.json(),W)}function lK($){return $.replace(/\/+$/,"")}function LZ($,W,Z){let Q=Z?.trim();if(!Q)return;let J=$?.trim();if(!J||!W?.trim())return Q;try{let j=new URL(Q),X=new URL(W),Y=new URL(J);if(j.origin!==X.origin)return Q;let V=lK(X.pathname),B=lK(Y.pathname);if(V&&j.pathname.startsWith(`${V}/`)){let H=j.pathname.slice(V.length);Y.pathname=`${B}${H}`}else Y.pathname=j.pathname;return Y.search=j.search,Y.hash=j.hash,Y.toString()}catch{return Q}}function tE($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{...Z}]))}function eE($){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 $w=Object.values(e.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:tE($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),rK=Object.fromEntries($w.map(($)=>[$.id,$]));function Ww($){return rK[$]}function Zw(){return Object.fromEntries(Object.entries(rK).filter(([,$])=>eE($)))}function iK($=[]){let W=$.flatMap((Z)=>{switch(Z){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Z];default:return[]}});return W.length>0?W:void 0}var qZ="https://models.dev/api.json",Qw=600000,nK=300000,Jw=5000,zZ=new Map,O5=new Map,xJ=new Map,TZ=new Map;async function jw(){return e.getGeneratedProviderModels()}async function Xw($,W={},Z={},Q={},J={},j={}){if($==="litellm")return e.sortModelsByReleaseDate(Q);let X=await jw(),Y=e.resolveProviderModelCatalogKeys($),V=Object.assign({},...Y.map((K)=>X[K]??{})),B=Boolean(e.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),H=Object.keys(J).length>0;if(B&&H)return e.sortModelsByReleaseDate({...J,...j});if($==="openai-codex")return e.sortModelsByReleaseDate({...W,...e.filterOpenAICodexModels(Z),...J,...j});if($==="cline-pass"&&Object.keys(Z).length>0)return{...Z,...j};let G=e.sortModelsByReleaseDate({...V,...W,...Z,...Q,...J});if($==="cline")return e.sortModelsByReleaseDate({...e.preferCanonicalModelIds(G,e.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...j});return e.sortModelsByReleaseDate({...G,...j})}function Yw($,W){let Z=e.resolveProviderModelCatalogKeys($);return Object.assign({},...Z.map((Q)=>W[Q]??{}))}function MZ($){let W=$?.trim();return W&&W.length>0?W:""}function mJ($){let W=$.apiKey?.trim()||$.accessToken?.trim();return W&&W.length>0?W:void 0}function Vw($){let W=2166136261;for(let Z=0;Z<$.length;Z+=1)W^=$.charCodeAt(Z),W+=(W<<1)+(W<<4)+(W<<7)+(W<<8)+(W<<24);return(W>>>0).toString(16)}function Bw($,W){return`${$}:${MZ(W.baseUrl)}:${Vw(mJ(W)??"")}`}async function RZ($,W,Z=Jw){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await fetch($,{...W,signal:Q.signal})}finally{clearTimeout(J)}}function c2($,W,Z){if(Z&&!$.includes(W))$.push(W)}function NZ($,W){let Z=["streaming","tools"];return c2(Z,"images",Boolean(W.supportsImages)),c2(Z,"prompt-cache",Boolean(W.supportsPromptCache)),c2(Z,"reasoning",Boolean(W.supportsReasoning)),{id:$,name:W.name??$,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxTokens:W.maxTokens,capabilities:Z,releaseDate:W.releaseDate,status:"active"}}async function Hw($,W){let Z=await RZ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"}});if(!Z.ok)throw Error(`Baseten model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;if(Y.includes("whisper")||Y.includes("tts")||Y.includes("embedding"))continue;let V=X.supported_features??[];j[Y]=NZ(Y,{name:Y,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return j}function pK($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let W=Number($);return Number.isFinite(W)?W:void 0}return}async function Gw($,W){let Z=await RZ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":W}});if(!Z.ok)throw Error(`Hicap model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;j[Y]=NZ(Y,{name:Y,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function Kw($,W){let Q=`${(MZ($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await RZ(Q,{method:"GET",headers:{Authorization:`Bearer ${W}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let X=(await J.json())?.data??[],Y={};for(let V of X){let B=V.id?.trim();if(!B)continue;let H=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];c2(F,"tools",H.includes("tools")),c2(F,"reasoning",H.includes("reasoning")),c2(F,"temperature",G.includes("temperature")),c2(F,"images",K.includes("image"));let A={input:pK(V.pricing?.prompt),output:pK(V.pricing?.completion)};Y[B]={id:B,name:V.name??B,description:V.description,contextWindow:V.context_length,maxInputTokens:V.context_length,maxTokens:V.max_completion_tokens,capabilities:F,pricing:A.input!==void 0||A.output!==void 0?A:void 0,status:"active"}}return Y}function Fw($){let W=MZ($).replace(/\/+$/,"");if(!W)return"http://localhost:4000";return W.endsWith("/v1")?W.slice(0,-3):W}function Aw($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function Uw($){let W=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Z=500,Q=W?`: ${W.slice(0,500)}${W.length>500?"...":""}`:"";return`HTTP ${$.status}${Q}`}async function fw($,W){let Z=Fw($.baseUrl),Q=[],J=[["x-litellm-api-key",{"x-litellm-api-key":W}],["Authorization",{Authorization:`Bearer ${W}`}]];for(let j of Aw(Z))for(let[X,Y]of J)try{let V=await RZ(j,{method:"GET",headers:{accept:"application/json",...Y}});if(V.ok){let H=(await V.json())?.data??[],G={};for(let K of H){let F=K.model_name?.trim(),f=K.litellm_params?.model?.trim()||F;if(!f)continue;let U=K.model_info,_=NZ(f,{name:F??f,maxTokens:U?.max_output_tokens??U?.max_tokens,maxInputTokens:U?.max_input_tokens??U?.max_tokens,supportsImages:U?.supports_vision,supportsPromptCache:U?.supports_prompt_caching,supportsReasoning:U?.supports_reasoning});if(G[f]=_,F)G[F]={..._,id:F,name:F}}return G}Q.push(`${new URL(j).pathname} (${X}): ${await Uw(V)}`)}catch(V){let B=V instanceof Error?V.message:String(V);Q.push(`${new URL(j).pathname} (${X}): ${B}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${Q.join("; ")}`)}var aK={baseten:Hw,hicap:Gw,litellm:fw,poolside:Kw},gJ=new Map,OZ=new Map;function Dw($,W){return`${$}:${MZ(W.baseUrl)}`}async function _w($,W,Z){let Q=e.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=LZ(Z.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!J)return{};let j=W?.cacheTtlMs??nK,X=Dw($,Z),Y=Date.now(),V=gJ.get(X);if(V&&V.expiresAt>Y)return V.data;let B=OZ.get(X);if(B)return B;let H=_Z(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,NZ(F,{name:F})]));return gJ.set(X,{data:K,expiresAt:Y+j}),K}).finally(()=>{OZ.delete(X)});return OZ.set(X,H),H}function Lw(){gJ.clear(),OZ.clear()}async function Tw($,W){let Z=mJ(W);if(!Z)return{};let Q=aK[$];if(!Q)return{};return Q(W,Z)}function Ow($,W,Z){if(!Z)return!1;if(!aK[$])return!1;if(W?.loadPrivateOnAuth===!1)return!1;return Boolean(mJ(Z))}async function zw($,W,Z){let Q=W?.cacheTtlMs??nK,J=Bw($,Z),j=Date.now(),X=xJ.get(J);if(X&&X.expiresAt>j)return X.data;let Y=TZ.get(J);if(Y)return Y;let V=Tw($,Z).then((B)=>{return xJ.set(J,{data:B,expiresAt:j+Q}),B}).finally(()=>{TZ.delete(J)});return TZ.set(J,V),V}async function qw($){return e.fetchLiveProviderModels($,globalThis.fetch)}async function B6($={}){let W=$.url??qZ,Z=$.cacheTtlMs??Qw,Q=Date.now(),J=zZ.get(W);if(J&&J.expiresAt>Q)return J.data;let j=O5.get(W);if(j)return j;let X=qw(W).then((Y)=>{return zZ.set(W,{data:Y,expiresAt:Q+Z}),Y}).finally(()=>{O5.delete(W)});return O5.set(W,X),X}function vJ($){if($){zZ.delete($),O5.delete($);return}zZ.clear(),O5.clear()}function cJ(){xJ.clear(),TZ.clear()}function Mw($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{baseUrl:Z.baseUrl,modelId:Z.modelId,capabilities:iK(Z.capabilities)}]))}var z5=Mw(Zw());function EZ($){let W=Ww($);if(!W)return;return{baseUrl:W.baseUrl||void 0,modelId:W.modelId,knownModels:W.knownModels,capabilities:iK(W.capabilities)}}async function q5($,W,Z){let Q=EZ($);if(!Q)return;try{let J=W?.loadLatestOnInit?await B6(W):void 0,j=J?Yw($,J):{},X=Z&&Ow($,W,Z)?await zw($,W,Z):{},V=Boolean(e.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Z??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:Z,B=V?await _w($,W,V).catch(()=>({})):{},H=await Xw($,Q.knownModels,j,X,B,Z?.knownModels);return{...Q,knownModels:H}}catch(J){if(W?.failOnError)throw J;if($==="litellm")return{...Q,knownModels:{}};return Q}}var M5=o0.BUILT_IN_PROVIDER,uJ=o0.BUILT_IN_PROVIDER_IDS,dJ=o0.isBuiltInProviderId,H6=o0.normalizeProviderId,R5=E.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),wZ=E.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),CZ=E.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),PZ=E.object({apiKey:E.string().optional(),accessToken:E.string().optional(),refreshToken:E.string().optional(),expiresAt:E.number().int().positive().optional(),accountId:E.string().optional(),organizationId:E.string().optional(),organizationName:E.string().optional(),memberId:E.string().optional(),metadata:E.record(E.string(),E.unknown()).optional()}),Rw=E.enum(["none","low","medium","high","xhigh"]),SZ=E.object({enabled:E.boolean().optional(),effort:Rw.optional(),budgetTokens:E.number().int().positive().optional()}),bZ=E.object({accessKey:E.string().optional(),secretKey:E.string().optional(),sessionToken:E.string().optional(),region:E.string().optional(),profile:E.string().optional(),authentication:E.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:E.boolean().optional(),useCrossRegionInference:E.boolean().optional(),useGlobalInference:E.boolean().optional(),endpoint:E.string().url().optional(),customModelBaseId:E.string().optional()}),yZ=E.object({projectId:E.string().optional(),region:E.string().optional()}),hZ=E.object({apiVersion:E.string().optional(),useIdentity:E.boolean().optional()}),kZ=E.object({clientId:E.string().optional(),clientSecret:E.string().optional(),tokenUrl:E.string().url().optional(),resourceGroup:E.string().optional(),deploymentId:E.string().optional(),useOrchestrationMode:E.boolean().optional(),api:E.enum(["orchestration","foundation-models"]).optional(),defaultSettings:E.record(E.string(),E.unknown()).optional()}),IZ=E.object({mode:E.enum(["internal","external"]).optional(),usePromptCache:E.boolean().optional()}),xZ=E.object({loadLatestOnInit:E.boolean().optional(),loadPrivateOnAuth:E.boolean().optional(),url:E.string().url().optional(),cacheTtlMs:E.number().int().positive().optional(),failOnError:E.boolean().optional()}),x$=E.object({provider:R5,apiKey:E.string().optional(),auth:PZ.optional(),model:E.string().optional(),protocol:wZ.optional(),client:CZ.optional(),routingProviderId:R5.optional(),maxTokens:E.number().int().positive().optional(),contextWindow:E.number().int().positive().optional(),baseUrl:E.string().url().optional(),headers:E.record(E.string(),E.string()).optional(),timeout:E.number().int().positive().optional(),reasoning:SZ.optional(),aws:bZ.optional(),gcp:yZ.optional(),azure:hZ.optional(),sap:kZ.optional(),oca:IZ.optional(),region:E.string().optional(),apiLine:E.enum(["china","international"]).optional(),capabilities:E.array(E.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:xZ.optional()});function gZ($){return x$.parse($)}function mZ($){return x$.safeParse($)}function Nw($){return $.protocol==="openai-responses"||$.client==="openai"}function s0($,W={}){let Z=$.provider,Q=H6(Z),J=W.includeKnownModels!==!1,j=$.reasoning?.effort||"none",X=j==="none"?void 0:j,Y=z5[Q],V=Object.assign({},...o0.resolveProviderModelCatalogKeys(Q).map((f)=>o0.getGeneratedModelsForProvider(f))),B=Object.keys(V)[0],H=b8(Q,$),G=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?C9:P9:Y?.baseUrl),K=$.routingProviderId??(Nw($)&&Q!==M5.OPENAI_NATIVE?M5.OPENAI_NATIVE:void 0),F=J?Y?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Z,clientType:$.client,routingProviderId:K,modelId:$.model??Y?.modelId??B??"default",...J?{knownModels:F}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:X,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??Y?.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(A).filter(([f,U])=>U!==void 0))}function lJ($){let W=gZ($);return s0(W)}function pJ($){let W=mZ($);if(W.success)return{success:!0,config:s0(W.data)};return{success:!1,error:W.error}}var G6=x$;var vZ=g$.object({settings:x$,updatedAt:g$.string().datetime(),tokenSource:g$.enum(["manual","oauth","migration"]).default("manual")}),K6=g$.object({version:g$.literal(1),lastUsedProvider:g$.string().min(1).optional(),providers:g$.record(g$.string(),vZ)});function m$(){return{version:1,providers:{}}}X1();var eK={};w(eK,{InMemoryWorkspaceManager:()=>F6});import{upsertWorkspaceInfo as Ew,WorkspaceManifestSchema as rJ}from"@cline/shared";class F6{manifest;listeners=new Set;constructor($){this.manifest=rJ.parse($??{workspaces:{}})}async addWorkspacePath($){let W=await U8($);return this.manifest=Ew(this.manifest,W),this.emit({type:"workspace_added",workspace:W}),W}async switchWorkspace($){let W=D1($),Z=this.manifest.workspaces[W];if(Z)return this.manifest=rJ.parse({...this.manifest,currentWorkspacePath:W}),this.emit({type:"workspace_switched",workspace:Z}),Z;let Q=await this.addWorkspacePath(W);return this.manifest=rJ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let W=D1($);return this.manifest.workspaces[W]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let W of this.listeners)W($)}}M0();import{createHash as ww}from"node:crypto";var $F=new Set,WF=new Set;function Cw($){return ww("sha256").update($).digest("hex")}function Pw($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function ZF($){if(!$.telemetry)return;let W=Cw($.rootPath),Z=$.rootCount??1;if(!$F.has(W))$F.add(W),dW($.telemetry,{root_count:Z,vcs_types:Pw($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!WF.has(W)){WF.add(W);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",lW($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:Z})}}function yw($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function hw($,W,Z){if(W.length>0)for(let j of W)Z?.log(j.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(yw).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Z?.log(`Some plugins failed to initialize. ${Q}${J}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Z?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function kw($,W){let Z=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!Z&&!Q)return W;return{...W??{},...Z?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function QF($,W){return bw($,W)}function Iw($){let W=0;for(let Z of $??[]){if(Z.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0)?.kind==="recovery_notice")continue;W+=1}return W}function xw($,W,Z,Q,J,j){let X=Q.getProviderSettings($.providerId),Y=J||X?.modelCatalog?{...J??{},...X?.modelCatalog??{}}:void 0,V=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,B=Sw({providerId:$.providerId,sessionId:W,source:Z,defaultSource:F0.CLI,client:{name:$.extensionContext?.client?.name,version:$.extensionContext?.client?.version,versionHeaderFallback:$.headers?.["X-CLIENT-VERSION"],platform:$.extensionContext?.client?.platform,platformVersion:$.extensionContext?.client?.platformVersion,isMultiRoot:$.extensionContext?.client?.isMultiRoot},coreVersion:q8,openAiCodex:{accountId:V?.accountId??X?.auth?.accountId,accessToken:V?.accessToken??$.apiKey??X?.auth?.accessToken??X?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:X?.headers,config:$.headers,session:V?.headers}}),H={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:void 0,reasoning:kw($,X?.reasoning),modelCatalog:Y},G={...s0(H),...V??{}};if(B)G.headers=B;if($.knownModels)G.knownModels=$.knownModels;if($.extensionContext)G.extensionContext=$.extensionContext;let F=$.fetch??G.fetch??j;if(F)G.fetch=F;return G}async function JF($){let{input:W,sessionId:Z,providerSettingsManager:Q,defaultTelemetry:J,defaultCapabilities:j,defaultToolPolicies:X,defaultFetch:Y,onPluginEvent:V,onTeamEvent:B,createSubAgentLifecycleCallbacks:H,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,f=W$(W.config),{modelCatalogDefaults:U,userInstructionService:_,configExtensions:D,onTeamRestored:M,...O}=K??{},T=Object.keys(O).length>0?O:void 0,{workspaceInfo:L,workspaceMetadata:C,gitState:N,durationMs:p,vcsType:x,initError:P}=await E7(f),r=T?.extensionContext,d={...r??{},workspace:{...L,...r?.workspace??{}},session:{...r?.session??{},sessionId:Z},logger:r?.logger??T?.logger,telemetry:r?.telemetry??T?.telemetry??J};ZF({telemetry:d.telemetry,rootPath:L.rootPath,workspaceInfo:L,rootCount:1,vcsType:x,durationMs:p,initError:P,featureFlagEnabled:!0});let k1=V6({cwd:W.config.cwd,workspacePath:f,rootSessionId:Z,logger:T?.logger,workspaceInfo:L}),e$=ZK(T?.hooks)?void 0:Y6({rootSessionId:Z,workspacePath:f,workspaceInfo:L}),F$=v2([T?.hooks,e$]),k0;if(QF(D,"plugins"))try{k0=await J6({pluginPaths:T?.pluginPaths,workspacePath:f,cwd:W.config.cwd,onEvent:V,providerId:W.config.providerId,modelId:W.config.modelId,workspaceInfo:L,session:d.session,client:d.client,user:d.user,logger:d.logger,telemetry:d.telemetry,automation:d.automation}),hw(k0.failures,k0.warnings,T?.logger)}catch(o6){let G8=o6 instanceof Error?o6.message:String(o6);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${G8})`)}let f1=HJ(k1?[k1]:void 0,HJ(T?.extensions,B9(k0?.extensions))),H8=QF(D,"plugins")?Q$(k0?.pluginPaths??[]):void 0,V0={...W.config,...T??{},sessionId:Z,hooks:F$,extensions:f1,extensionContext:d,telemetry:d.telemetry},d0=xw(V0,Z,W.source,Q,U,Y),J1=v2([V0.hooks,V0.checkpoint?.enabled===!0?hK({cwd:V0.cwd,sessionId:Z,logger:V0.logger,createCheckpoint:V0.checkpoint?.createCheckpoint,initialRunCount:Iw(W.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),y={...V0,providerConfig:d0,workspaceMetadata:C,hooks:J1},j1=W.toolPolicies??V0.toolPolicies??X,k=C0(j,W.capabilities),$0=k?.requestToolApproval,L0=k?.toolExecutors,z0=H?.(y),kW=new F6({currentWorkspacePath:L.rootPath,workspaces:{[L.rootPath]:L}});return{effectiveInput:W,config:y,providerConfig:d0,workspaceMetadata:C,workspaceInfo:L,gitState:N,extensions:f1,hooks:J1,toolPolicies:j1,requestToolApproval:$0,pluginSandboxShutdown:k0?.shutdown,runtimeBuilderInput:{config:y,hooks:J1,extensions:f1,onTeamEvent:B,createSpawnTool:G,onTeamRestored:M,onSubAgentEvent:z0?.onSubAgentEvent,onSubAgentStart:z0?.onSubAgentStart,onSubAgentEnd:z0?.onSubAgentEnd,userInstructionService:_,pluginSkillDirectories:H8,configExtensions:D,toolExecutors:L0,toolPolicies:j1,workspaceManager:kW,logger:y.logger,telemetry:y.telemetry,requestToolApproval:$0}}}import{existsSync as cZ,mkdirSync as gw,readdirSync as mw,rmdirSync as vw,rmSync as cw,unlinkSync as uw}from"node:fs";import{dirname as jF,join as N5}from"node:path";function X0(){return new Date().toISOString()}function E5($){if(!$||!cZ($))return;try{uw($)}catch{}}function dw($){let W=o8($);if(W)return{rootSessionId:W.rootSessionId,fileStem:`${W.agentId}__${W.teamTaskId}`};let Z=j5($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:Z.agentId};return{rootSessionId:$,fileStem:$}}class iJ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return N5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let W=this.sessionArtifactsDir($);if(!cZ(W))gw(W,{recursive:!0});return W}sessionMessagesPath($){return N5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionCompactionPath($){return N5(this.sessionArtifactsDir($),`${$}.compaction.json`)}sessionManifestPath($,W=!1){let Z=W?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return N5(Z,`${$}.json`)}removeSessionDirIfEmpty($){let W=this.sessionArtifactsDir($),Z=this.ensureSessionsDir();while(W.startsWith(Z)&&W!==Z){if(!cZ(W)){W=jF(W);continue}try{if(mw(W).length>0)break;vw(W)}catch{break}W=jF(W)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!cZ($))return;try{cw($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,W,Z){let{rootSessionId:Q,fileStem:J}=dw($),j=this.sessionArtifactsDir(Q);return{messagesPath:N5(j,`${J}.messages.json`)}}}import{resolveDocumentsExtensionPath as lw}from"@cline/shared/storage";M0();function XF($,W,Z,Q,J){if(Z)rW($.telemetry,{ulid:W,apiProvider:$.providerId,...J});else pW($.telemetry,{ulid:W,apiProvider:$.providerId,...J});pw($.telemetry,{workspacePath:Q})}function pw($,W){let Z=lw("Hooks"),Q=k$(W.workspacePath),J=new Map;for(let j of Q){let X=j.hookEventName??"unknown",Y=J.get(X)??{global:0,workspace:0};if(j.path===Z||j.path.startsWith(`${Z}/`))Y.global+=1;else Y.workspace+=1;J.set(X,Y)}for(let[j,X]of J.entries())W9($,j,X.global,X.workspace)}function YF($,W){for(let Z of W.mentions)eW($,Z,W.matchedFiles.includes(Z)?1:0,"file",!W.matchedFiles.includes(Z));for(let Z of W.matchedFiles)sW($,"file",Z.length);for(let Z of W.ignoredMentions)tW($,"file","not_found",Z)}var BD={};w(BD,{ProviderSettingsManager:()=>h1});import{chmodSync as UD,existsSync as jY,mkdirSync as Mg,readFileSync as Rg,renameSync as Ng,rmSync as Eg,writeFileSync as wg}from"node:fs";import{basename as fD,dirname as XY}from"node:path";import{resolveProviderSettingsPath as Cg}from"@cline/shared/storage";var q={};w(q,{writeHubDiscovery:()=>F9,writeGlobalSettings:()=>_1,withHubStartupLock:()=>A9,verifyHubConnection:()=>z1,updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>_6,updateMcpServerOAuthStateAsync:()=>p5,updateMcpServerOAuthState:()=>r2,updateLocalProvider:()=>Z7,uninstallPlugin:()=>_W,uninstallMarketplaceSkill:()=>xQ,uninstallMarketplacePlugin:()=>gQ,uninstallMarketplaceMcpServerFromSettings:()=>kQ,uninstallMarketplaceEntry:()=>zX,truncateNotificationBody:()=>EW,truncateCommandOutput:()=>_2,toggleDisabledTool:()=>Y9,toTeamProgressLifecycleEvent:()=>C6,toProviderConfig:()=>s0,toHubStatusUrl:()=>r7,toHubHealthUrl:()=>U9,toHookConfigFileName:()=>L5,syncPluginMcpServersToSettings:()=>fW,summarizeUsageFromMessages:()=>t8,stopLocalHubServerGracefully:()=>J3,startLocalOAuthServer:()=>H1,startHubWebSocketServer:()=>PW,startHubServer:()=>KD,startClineDeviceAuth:()=>f3,splitCoreSessionConfig:()=>A4,spawnDetachedHubServerWithRetry:()=>R8,spawnDetachedHubServer:()=>t7,setTelemetryOptOutGlobally:()=>LV,setSdkLogger:()=>H3,setMcpServerDisabled:()=>l2,setDisabledTools:()=>m7,setDisabledPlugin:()=>EV,setCompactionStrategyGlobally:()=>qV,setAutoUpdateEnabledGlobally:()=>OV,sendHubCommand:()=>JB,sdkDebug:()=>Q0,saveProviderOAuthCredentials:()=>K2,saveLocalProviderSettings:()=>xX,saveLocalProviderOAuthCredentials:()=>cX,sanitizeSessionToken:()=>y2,safeParseSettings:()=>mZ,safeCreateProviderConfig:()=>pJ,runSubprocessEvent:()=>I6,runHook:()=>g6,reviveTeamStateDates:()=>ZZ,restartLocalHubIfIdleAfterStartupTimeout:()=>T9,resolveWorkspaceHubOwnerContext:()=>cV,resolveWorkflowsConfigSearchPaths:()=>g5,resolveSkillsConfigSearchPaths:()=>I5,resolveSharedHubOwnerContext:()=>V1,resolveSessionBackend:()=>pj,resolveRulesConfigSearchPaths:()=>x5,resolveProviderConfig:()=>q5,resolveProviderApiKeyFromSettings:()=>q3,resolveProductionHubOwnerContext:()=>O1,resolvePluginSkillDirectoriesFromPaths:()=>Q$,resolvePluginConfigSearchPaths:()=>U5,resolveMcpServerRegistrations:()=>t0,resolveMarketplaceMcpServerName:()=>TW,resolveLocalClineAuthToken:()=>dX,resolveHubUrl:()=>j3,resolveHubOwnerContext:()=>p1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>K9,resolveHooksConfigSearchPaths:()=>D5,resolveDisabledToolNames:()=>L1,resolveDisabledPluginPaths:()=>B4,resolveDefaultMcpSettingsPath:()=>J0,resolveDefaultHubPort:()=>M8,resolveDefaultHubPathname:()=>s7,resolveDefaultHubHost:()=>o7,resolveCoreSelectedToolIds:()=>JZ,resolveCoreDistinctId:()=>I0,resolveCompatibleLocalHubUrl:()=>_4,resolveClineDir:()=>xV,resolveClineDataDir:()=>X2,resolveAndLoadAgentPlugins:()=>J6,resolveAgentPluginPaths:()=>Z$,requestHubShutdown:()=>D4,requestDesktopToolApproval:()=>XX,removePluginMcpServersFromSettings:()=>DW,rememberRecoverableLocalHubUrl:()=>T$,registerRemoteConfigSessionBlobUpload:()=>NQ,registerMcpServersFromSettingsFile:()=>i2,registerDisposable:()=>Tg,refreshProviderModelsFromSource:()=>gX,refreshOpenAICodexToken:()=>w9,refreshOcaToken:()=>b9,refreshClineToken:()=>N9,readSessionCheckpointHistory:()=>W8,readRemoteConfigSessionBlobUploadMetadata:()=>sj,readHubDiscovery:()=>U0,readGlobalSettings:()=>R0,readCompactionStrategyGlobally:()=>zV,readBearerToken:()=>F7,projectSessionCompactionState:()=>F2,probeHubServer:()=>r1,probeHubConnection:()=>QB,prewarmFileIndex:()=>r9,prewarmDetachedHubServer:()=>D9,prepareRemoteConfigCoreIntegration:()=>ej,parseWorkflowConfigFromMarkdown:()=>k5,parseUserCommandEnvelope:()=>Lg,parseSkillConfigFromMarkdown:()=>y5,parseSettings:()=>gZ,parseSessionCompactionState:()=>G1,parseRuleConfigFromMarkdown:()=>h5,parsePluginSource:()=>iQ,parseMcpInstallArgs:()=>UW,parseHookEventPayload:()=>x6,parseConfiguredAgentConfig:()=>jW,normalizeWorkspacePath:()=>D1,normalizeUserInput:()=>_g,normalizeSdkError:()=>Dg,normalizeRuntimeCapabilities:()=>C0,normalizeProviderId:()=>H6,normalizeOAuthProvider:()=>mX,normalizeHubWebSocketUrl:()=>O$,noopBasicLogger:()=>fg,migrateLegacyProviderSettings:()=>RW,mergeRulesForSystemPrompt:()=>A8,mergeAgentHooks:()=>v2,marketplaceEntryKey:()=>OX,markLocalProviderEnabled:()=>hX,makeTeamTaskSubSessionId:()=>J5,makeSubSessionId:()=>a8,loginOpenAICodex:()=>O4,loginOcaOAuth:()=>R4,loginLocalProvider:()=>vX,loginClineOAuth:()=>L4,loginAndSaveProviderOAuthCredentials:()=>E4,loginAndSaveLocalProviderOAuthCredentials:()=>uX,loadOpenTelemetryAdapter:()=>dx,loadMcpSettingsFile:()=>d2,loadLlmsConfigFromFile:()=>WY,loadConfiguredAgentConfigs:()=>N6,loadAgentPluginsFromPathsWithDiagnostics:()=>I2,loadAgentPluginsFromPaths:()=>BZ,loadAgentPluginFromPath:()=>F5,listSessionHistoryFromBackend:()=>Mj,listPluginToolsWithDiagnostics:()=>YQ,listPluginTools:()=>n5,listMcpServerOAuthStatuses:()=>r5,listLocalProviders:()=>kX,listHookConfigFiles:()=>k$,isToolDisabledGlobally:()=>MV,isTelemetryOptedOutGlobally:()=>X9,isSessionNotFoundError:()=>l1,isRuleEnabled:()=>IW,isPluginDisabledGlobally:()=>NV,isOfficialPluginSlug:()=>rQ,isOAuthProvider:()=>G2,isMarketplaceSkillInstalled:()=>IQ,isLocalHubOrigin:()=>JY,isLocalHubHostName:()=>A7,isHubReconnectableTransportError:()=>Z3,isHubCommandTimeoutError:()=>L9,isDiscoveryFilePresent:()=>mV,isClinePassLimitMessage:()=>Qg,isClinePassLimitError:()=>Zg,isClineOrgIndividualInferenceSubscriptionMessage:()=>Wg,isClineOrgIndividualInferenceSubscriptionError:()=>$g,isClineNotSubscribedMessage:()=>ex,isClineNotSubscribedError:()=>tx,isClineAccountActionRequest:()=>uZ,isBuiltInProviderId:()=>dJ,isAutoUpdateEnabledGlobally:()=>TV,installPlugin:()=>wX,installMcpServer:()=>YX,identifyAccount:()=>v1,hashSecret:()=>N0,hasMcpSettingsFile:()=>j$,getValidOpenAICodexCredentials:()=>z4,getValidOcaCredentials:()=>N4,getValidClineCredentials:()=>T4,getProviderOAuthCredentialsFromSettings:()=>w4,getProviderConfigFields:()=>lX,getProviderConfig:()=>EZ,getProviderAuthStorageId:()=>z3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>b8,getMcpServerOAuthState:()=>p2,getMarketplaceSkillCandidates:()=>OW,getLocalProviderModels:()=>IX,getLiveModelsCatalog:()=>B6,getGlobalMarketplaceSkillPaths:()=>zW,getFileIndex:()=>s1,getCurrentContextSize:()=>AJ,getCoreHeadlessToolNames:()=>Q5,getCoreDefaultEnabledToolIds:()=>QZ,getCoreBuiltinToolCatalog:()=>S2,getCoreAcpToolNames:()=>jZ,getClinePassSubscriptionUrl:()=>sx,getClineOrgIndividualInferenceSubscriptionMessage:()=>ox,getClineNotSubscribedMessage:()=>ax,getClineDefaultSystemPrompt:()=>Jg,generateWorkspaceInfoWithDiagnostics:()=>t6,generateWorkspaceInfo:()=>U8,formatRulesForSystemPrompt:()=>F8,formatProviderOAuthApiKey:()=>M3,formatDisplayUserInput:()=>Ug,findInstalledGlobalMarketplaceSkillName:()=>qW,findCheckpointForRun:()=>h6,filterExtensionToolRegistrations:()=>B9,filterDisabledTools:()=>c1,filterDisabledPluginPaths:()=>V9,fetchClineRecommendedModels:()=>eX,extractClinePassLimitMessage:()=>nx,executeClineAccountAction:()=>dZ,ensureHubWebSocketServer:()=>U7,ensureHubServer:()=>FD,ensureDetachedHubServer:()=>iV,ensureCustomProvidersLoaded:()=>eQ,ensureCompatibleLocalHubUrl:()=>B2,enrichPromptWithMentions:()=>c8,emptyWorkspaceManifest:()=>Kg,emptyStoredProviderSettings:()=>m$,discoverPluginModulePaths:()=>f5,disablePluginMcpServersInSettings:()=>GX,deriveSubsessionStatus:()=>X5,deleteLocalProvider:()=>Q7,defineLlmsConfig:()=>$Y,createWorkflowsConfigDefinition:()=>c5,createUserInstructionConfigService:()=>v$,createToolPoliciesWithPreset:()=>n9,createTool:()=>Gg,createTeamName:()=>CQ,createSubprocessHooks:()=>zQ,createSpawnAgentTool:()=>b$,createSkillsConfigDefinition:()=>m5,createShellTool:()=>n4,createShellExecutor:()=>L2,createSessionHost:()=>b6,createSessionCompactionState:()=>y8,createRuntimeHost:()=>b6,createRulesConfigDefinition:()=>v5,createRemoteConfigSessionMessagesArtifactUploader:()=>tj,createProviderConfig:()=>lJ,createOpenTelemetryTelemetryService:()=>F4,createOAuthClientCallbacks:()=>A6,createMcpTools:()=>z6,createLocalHubScheduleRuntimeHandlers:()=>GD,createLlmsSdk:()=>QY,createInitialAccumulatedUsage:()=>O0,createInMemoryHubOwnerContext:()=>gV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>G9,createHookConfigFileHooks:()=>T5,createHookConfigFileExtension:()=>V6,createHookAuditHooks:()=>Y6,createEditorExecutor:()=>q2,createDisabledMcpToolPolicy:()=>i5,createDisabledMcpToolPolicies:()=>XQ,createDelegatedAgentConfigProvider:()=>P$,createDelegatedAgent:()=>S$,createDefaultToolsWithPreset:()=>a9,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>t4,createDefaultMcpServerClientFactory:()=>T6,createDefaultExecutors:()=>u8,createCoreSettingsService:()=>a2,createCoreSessionSnapshot:()=>E1,createContributionRegistry:()=>Hg,createContextCompactionPrepareTurn:()=>x4,createConfiguredTelemetryService:()=>u1,createConfiguredTelemetryHandle:()=>z8,createConfiguredAgentTools:()=>E6,createCompactionStateAwarePrepareTurn:()=>g4,createClineTelemetryServiceMetadata:()=>Bg,createClineTelemetryServiceConfig:()=>Vg,createCheckpointComparePlan:()=>_Q,createBuiltinTools:()=>b2,createApplyPatchExecutor:()=>z2,createAgentTeamsTools:()=>P2,createAgentRuntime:()=>qg,createAgentHooksExtension:()=>j6,connectToHub:()=>O9,computePatchChanges:()=>m8,completeClineDeviceAuth:()=>D3,compareCheckpointToWorkspace:()=>KW,collectPluginMcpOAuthCandidates:()=>nQ,clearPrivateModelsCatalogCache:()=>cJ,clearLiveModelsCatalogCache:()=>vJ,clearHubDiscovery:()=>x0,captureWorkspacePathResolved:()=>KV,captureWorkspaceInitialized:()=>dW,captureWorkspaceInitError:()=>lW,captureToolUsage:()=>_8,captureTokenUsage:()=>iW,captureTaskRestarted:()=>rW,captureTaskCreated:()=>pW,captureTaskCompleted:()=>j4,captureSubagentExecution:()=>Y4,captureSkillUsed:()=>aW,captureSdkError:()=>Yg,captureProviderConfigured:()=>FV,captureProviderApiError:()=>X4,captureModeSwitch:()=>nW,captureMentionUsed:()=>sW,captureMentionSearchResults:()=>eW,captureMentionFailed:()=>tW,captureHookDiscovery:()=>W9,captureExtensionActivated:()=>GV,captureDiffEditFailure:()=>oW,captureConversationTurnEvent:()=>D8,captureCompactionSkipped:()=>Q9,captureCompactionExecuted:()=>Z9,captureAuthSucceeded:()=>g1,captureAuthStarted:()=>x1,captureAuthLoggedOut:()=>_$,captureAuthFailed:()=>m1,captureAgentUnexpectedReasoningTokens:()=>HV,captureAgentTeamCreated:()=>$9,captureAgentCreated:()=>L$,buildWorkspaceMetadata:()=>e6,buildTeamProgressSummary:()=>w6,buildSdkErrorProperties:()=>jg,buildRemoteConfigSessionBlobUploadMetadata:()=>MQ,buildMcpInstallTransport:()=>PQ,buildDelegatedAgentConfig:()=>w2,buildConnectionUpdate:()=>$J,buildConfiguredAgentToolName:()=>XW,buildConfiguredAgentToolDescriptors:()=>YW,buildCheckpointWorkspaceDiff:()=>LQ,bootstrapAgentTeams:()=>n8,authorizeMcpServerOAuth:()=>ZQ,addLocalProvider:()=>yX,accumulateUsageTotals:()=>_0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>b5,UnifiedConfigFileWatcher:()=>u2,ToolPresets:()=>a0,TelemetryService:()=>T8,TelemetryLoggerSink:()=>K4,TEAM_TOOL_NAMES:()=>i8,SubprocessSandbox:()=>W6,StructuredCommandInputSchema:()=>f2,StoredProviderSettingsSchema:()=>K6,StoredProviderSettingsEntrySchema:()=>vZ,SqliteTeamStore:()=>J8,SqliteSessionStore:()=>C1,SessionVersioningService:()=>a$,SessionVersioningError:()=>c0,SessionSource:()=>F0,SessionNotFoundError:()=>d1,SapSettingsSchema:()=>kZ,SKILLS_CONFIG_DIRECTORY_NAME:()=>S5,SESSION_STATUSES:()=>Y5,SESSION_NOT_FOUND_ERROR_CODE:()=>j2,SDK_ERROR_TELEMETRY_EVENT:()=>Og,RpcClineAccountService:()=>C5,RemoteRuntimeHost:()=>R6,ReasoningSettingsSchema:()=>SZ,RULES_CONFIG_DIRECTORY_NAME:()=>oZ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>RQ,ProviderSettingsSchema:()=>x$,ProviderSettingsManager:()=>h1,ProviderProtocolSchema:()=>wZ,ProviderIdSchema:()=>R5,ProviderClientSchema:()=>CZ,PatchActionType:()=>O2,OpenTelemetryProvider:()=>O8,OcaSettingsSchema:()=>IZ,OPENAI_COMPATIBLE_PROVIDERS:()=>z5,NodeHubClient:()=>B1,NoOpFeatureFlagsProvider:()=>$8,NativeHubTransportAdapter:()=>CW,ModelCatalogSettingsSchema:()=>xZ,McpSettingsUpdateSkippedError:()=>D6,McpSettingsMutatorPurityError:()=>c$,McpSettingsLockTimeoutError:()=>u$,MAX_COMMAND_OUTPUT_CHARS:()=>n1,LocalRuntimeHost:()=>b1,Llms:()=>lx,InMemoryWorkspaceManager:()=>F6,InMemoryMcpManager:()=>n2,HubUIClient:()=>V3,HubTransportError:()=>b0,HubSessionClient:()=>Y3,HubServerTransport:()=>n6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>K8,HubRuntimeHost:()=>X$,HubCommandError:()=>N8,HookEventPayloadSchema:()=>OQ,HookEventNameSchema:()=>TQ,HookConfigFileName:()=>X6,HOOK_CONFIG_FILE_EVENT_MAP:()=>_5,HOOKS_CONFIG_DIRECTORY_NAME:()=>UZ,GlobalSettingsSchema:()=>V4,GcpSettingsSchema:()=>yZ,FileTeamPersistenceStore:()=>X7,FeatureFlagsService:()=>e2,FeatureFlagDefaultValue:()=>Ag,FEATURE_FLAGS:()=>Fg,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>K7,DefaultToolNames:()=>T0,DefaultRuntimeBuilder:()=>c6,DefaultLlmsSdk:()=>NW,DEFAULT_MODELS_CATALOG_URL:()=>qZ,DEFAULT_HUB_PORT:()=>n7,DEFAULT_HUB_PATHNAME:()=>a7,DEFAULT_HUB_HOST:()=>i7,CoreSettingsService:()=>d$,CoreSessionService:()=>S1,ContributionRegistry:()=>Xg,CommandExitError:()=>a1,ClinePassLimitError:()=>ix,ClineOrgIndividualInferenceSubscriptionError:()=>rx,ClineNotSubscribedError:()=>px,ClineCore:()=>FW,ClineAccountService:()=>w5,ChatViewStateSchema:()=>oX,ChatSummarySchema:()=>G7,ChatSessionStatusSchema:()=>V7,ChatSessionConfigSchema:()=>Y7,ChatMessageSchema:()=>H7,ChatMessageRoleSchema:()=>B7,CORE_TELEMETRY_EVENTS:()=>v,CORE_BUILD_VERSION:()=>sX,BrowserWebSocketHubAdapter:()=>wW,BUILT_IN_PROVIDER_IDS:()=>uJ,BUILT_IN_PROVIDER:()=>M5,AzureSettingsSchema:()=>hZ,AwsSettingsSchema:()=>bZ,AuthSettingsSchema:()=>PZ,AgentTeamsRuntime:()=>t2,AgentTeam:()=>S6,Agent:()=>zg,ALL_DEFAULT_TOOL_NAMES:()=>U$});R(q,V00);import*as lx from"@cline/llms";import{ClineNotSubscribedError as px,ClineOrgIndividualInferenceSubscriptionError as rx,ClinePassLimitError as ix,extractClinePassLimitMessage as nx,getClineNotSubscribedMessage as ax,getClineOrgIndividualInferenceSubscriptionMessage as ox,getClinePassSubscriptionUrl as sx,isClineNotSubscribedError as tx,isClineNotSubscribedMessage as ex,isClineOrgIndividualInferenceSubscriptionError as $g,isClineOrgIndividualInferenceSubscriptionMessage as Wg,isClinePassLimitError as Zg,isClinePassLimitMessage as Qg}from"@cline/llms";import{buildClineSystemPrompt as Jg,buildSdkErrorProperties as jg,ContributionRegistry as Xg,captureSdkError as Yg,createClineTelemetryServiceConfig as Vg,createClineTelemetryServiceMetadata as Bg,createContributionRegistry as Hg,createTool as Gg,emptyWorkspaceManifest as Kg,FEATURE_FLAGS as Fg,FeatureFlagDefaultValue as Ag,formatDisplayUserInput as Ug,noopBasicLogger as fg,normalizeSdkError as Dg,normalizeUserInput as _g,parseUserCommandEnvelope as Lg,registerDisposable as Tg,SDK_ERROR_TELEMETRY_EVENT as Og}from"@cline/shared";import"@cline/shared/storage";var BF={};w(BF,{isClineAccountActionRequest:()=>uZ,executeClineAccountAction:()=>dZ,RpcClineAccountService:()=>C5,ClineAccountService:()=>w5});function rw($){if(typeof $!=="object"||$===null||!("error"in $))return;let W=$.error;return typeof W==="string"&&W.trim()?W:void 0}function VF($,W,Z){let Q=rw(Z);if(Q)return Q;let J=W.trim();if(J){let j=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class w5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let W=$.apiBaseUrl.trim();if(!W)throw Error("apiBaseUrl is required");this.apiBaseUrl=W,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 W=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(W)}/balance`)}async fetchUsageTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/usages`)).items??[]}async fetchPaymentTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let W=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)W.searchParams.set("type",$.type);return this.request(`${W.pathname}${W.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}`)}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}/balance`)}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");let Z=await this.resolveOrganizationMemberId(W,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(W)}/members/${encodeURIComponent(Z)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let W=$?.trim();if(W)return W;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,W){let Z=W?.trim();if(Z)return Z;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let X=(await this.fetchUserOrganizations()).find((Y)=>Y.organizationId===$)?.memberId;if(!X?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return X}async request($,W){let Z=(await this.getAuthTokenFn())?.trim();if(!Z)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,j=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let X=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:W?.method??"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json",...Q??{}},body:W?.body!==void 0?JSON.stringify(W.body):void 0,signal:J.signal});if(X.status===204||W?.expectNoContent){if(!X.ok)throw Error(`Cline account request failed with status ${X.status}`);return}let Y=await X.text(),V;if(Y.trim())try{V=JSON.parse(Y)}catch{if(!X.ok)throw Error(VF(X.status,Y,void 0));throw Error("Cline account response was not valid JSON")}if(!X.ok)throw Error(VF(X.status,Y,V));if(typeof V==="object"&&V!==null){let B=V;if(typeof B.success==="boolean"){if(!B.success)throw Error(B.error||"Cline account request failed");return B.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(j)}}}function uZ($){return $.action==="clineAccount"}async function dZ($,W){switch($.operation){case"fetchMe":return W.fetchMe();case"fetchBalance":return W.fetchBalance($.userId);case"fetchUsageTransactions":return W.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return W.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return W.fetchUserOrganizations();case"fetchOrganizationBalance":return W.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return W.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await W.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return W.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class C5{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 W=$.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:W})}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:W,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var HF={};w(HF,{createOAuthClientCallbacks:()=>A6});function A6($){return{onAuth:({url:W,instructions:Z})=>{if($.onOutput?.(Z??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(W)).catch((Q)=>{$.onOpenUrlError?.({url:W,error:Q})})}catch(Q){$.onOpenUrlError?.({url:W,error:Q})}$.onOutput?.(W)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var hU={};w(hU,{ClineCore:()=>FW});function GF($){if($===!0)return{};if(!$)return;return $}function KF($){if($==="user")return"global";return $}class nJ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let W=this.getService().ingestEvent($);return{event:W.event,duplicate:W.duplicate,matchedSpecIds:W.matchedSpecs.map((Z)=>Z.specId),queuedRuns:W.queuedRuns,suppressions:W.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function FF($){let{host:W}=$;return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:H6(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:aw(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content),delivery:Q.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:nw(J)}},async abortSession(Z){return await W.abort(Z,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}function lZ($){let W=iw($.automationService,$.automation),Z=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!W&&!Z&&!Q&&!J&&!j)return $.context;return{...$.context??{},...Z?{client:Z}:{},...Q?{user:Q}:{},...J?{logger:J}:{},...j?{telemetry:j}:{},...W?{automation:W}:{}}}function iw($,W){if(!$)return;return{ingestEvent:(Z)=>{W.ingestEvent(Z)}}}function nw($){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((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function aw($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var UA={};w(UA,{createCoreSettingsService:()=>a2,CoreSettingsService:()=>d$});import{existsSync as o5,readFileSync as hP}from"node:fs";import{basename as Hj,dirname as VA,extname as kP,isAbsolute as GA,join as IP,relative as KA,resolve as BA}from"node:path";var NF={};w(NF,{resolveWorkflowsConfigSearchPaths:()=>g5,resolveSkillsConfigSearchPaths:()=>I5,resolveRulesConfigSearchPaths:()=>x5,parseWorkflowConfigFromMarkdown:()=>k5,parseSkillConfigFromMarkdown:()=>y5,parseRuleConfigFromMarkdown:()=>h5,createWorkflowsConfigDefinition:()=>c5,createUserInstructionConfigService:()=>v$,createSkillsConfigDefinition:()=>m5,createRulesConfigDefinition:()=>v5,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>b5,UnifiedConfigFileWatcher:()=>u2,SKILLS_CONFIG_DIRECTORY_NAME:()=>S5,RULES_CONFIG_DIRECTORY_NAME:()=>oZ});import{createHash as ow}from"node:crypto";import{watch as sw}from"node:fs";import{readdir as tw,readFile as ew}from"node:fs/promises";import{join as $C}from"node:path";function WC($){return ow("sha1").update($).digest("hex")}function fF($){return Boolean($&&typeof $==="object"&&"code"in $)}function AF($){return fF($)&&$.code==="ENOENT"}function UF($){return fF($)&&($.code==="EACCES"||$.code==="EPERM")}class u2{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($,W){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=W?.debounceMs??75,this.emitParseErrors=W?.emitParseErrors??!1;for(let Z of $){if(this.definitionsByType.has(Z.type))throw Error(`Duplicate unified config definition type '${Z.type}'.`);this.definitionsByType.set(Z.type,Z),this.recordsByType.set(Z.type,new Map),this.discoveredDirectoriesByType.set(Z.type,new Set);for(let Q of Z.directories){let J=this.baseTypesByDirectory.get(Q);if(J)J.add(Z.type);else this.baseTypesByDirectory.set(Q,new Set([Z.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 W=this.definitionsByType.get($);if(!W)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(W)})}getSnapshot($){let W=this.recordsByType.get($);return new Map([...W?.entries()??[]].map(([Z,Q])=>[Z,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[W,Z]of this.recordsByType.entries())$.set(W,new Map([...Z.entries()].map(([Q,J])=>[Q,{...J}])));return $}emit($){for(let W of this.listeners)W($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[W,Z]of this.watchersByDirectory.entries()){if($.has(W))continue;Z.close(),this.watchersByDirectory.delete(W)}this.watchedTypesByDirectory=$;for(let W of $.keys()){if(this.watchersByDirectory.has(W))continue;try{let Z=sw(W,()=>{let Q=this.watchedTypesByDirectory.get(W);if(!Q)return;for(let J of Q)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(W,Z),Z.on("error",(Q)=>{let J=this.watchedTypesByDirectory.get(W);if(!J)return;for(let j of J)this.emit({kind:"error",type:j,error:Q,filePath:W})})}catch(Z){if(!AF(Z)&&!UF(Z)){let Q=$.get(W);if(!Q)continue;for(let J of Q)this.emit({kind:"error",type:J,error:Z,filePath:W})}}}}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 W of $){let Z=this.definitionsByType.get(W);if(!Z)continue;await this.refreshTypeInternal(Z)}})},this.debounceMs)}async refreshTypeInternal($){let{records:W,discoveredDirectories:Z}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[J,j]of Q.entries()){if(W.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:j.filePath})}for(let[J,j]of W.entries()){let X=Q.get(J);if(X&&X.filePath===j.filePath&&X.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:J,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,W),this.discoveredDirectoriesByType.set($.type,Z),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let W=new Map,Z=new Set;for(let Q of $.directories){Z.add(Q);let J=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let j of J){let{fileName:X,filePath:Y}=j;if(Z.add(j.directoryPath),$.includeFile&&!$.includeFile(X,Y))continue;try{let V=await ew(Y,"utf8"),B={type:$.type,directoryPath:j.directoryPath,fileName:X,filePath:Y,content:V},H=$.parseFile(B),G=$.resolveId(H,B).trim();if(!G)continue;W.set(G,{type:$.type,id:G,item:H,filePath:Y,fingerprint:WC(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:Y})}}}return{records:W,discoveredDirectories:Z}}buildDesiredTypesByDirectory(){let $=new Map;for(let[W,Z]of this.baseTypesByDirectory.entries())$.set(W,new Set(Z));for(let[W,Z]of this.discoveredDirectoriesByType.entries())for(let Q of Z){let J=$.get(Q);if(J)J.add(W);else $.set(Q,new Set([W]))}return $}async readDirectoryFileCandidates($){try{return(await tw($,{withFileTypes:!0})).filter((Z)=>Z.isFile()).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:$C($,Z.name)})).sort((Z,Q)=>Z.fileName.localeCompare(Q.fileName))}catch(W){if(AF(W)||UF(W))return[];throw W}}}import{readdir as oJ,readFile as ZC,stat as aJ}from"node:fs/promises";import{basename as J$,dirname as QC,extname as rZ,join as m0,resolve as P5}from"node:path";import{AGENTS_RULES_FILE_NAME as DF,RULES_CONFIG_DIRECTORY_NAME as oZ,resolveGlobalAgentsRulesPath as JC,resolveRulesConfigSearchPaths as jC,resolveSkillsConfigSearchPaths as XC,resolveWorkflowsConfigSearchPaths as YC,SKILLS_CONFIG_DIRECTORY_NAME as S5,WORKFLOWS_CONFIG_DIRECTORY_NAME as b5}from"@cline/shared/storage";import VC from"yaml";var pZ="SKILL.md",BC="managed.json",HC=new Set([".md",".markdown",".txt"]);function sJ($){return $.trim().toLowerCase()}function U6($){let W=$;return W?.code==="ENOENT"||W?.code==="EACCES"||W?.code==="EPERM"||W?.code==="ELOOP"}function iZ($){return HC.has(rZ($).toLowerCase())}function _F($){let W=[],Z=new Set;for(let Q of $){let J=P5(Q);if(Z.has(J))continue;Z.add(J),W.push(Q)}return W}function GC($){let W=[...$?.directories??I5($?.workspacePath)];if($?.pluginSkillDirectories)W.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)W.push(...bK({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return _F(W)}async function tJ($){try{let W=await oJ($,{withFileTypes:!0}),Z=[];for(let Q of W){if(!Q.isDirectory())continue;let J=m0($,Q.name),j=m0(J,BC);try{let X=await ZC(j,"utf8"),Y=JSON.parse(X);if(Y&&typeof Y==="object")Z.push(J)}catch(X){if(U6(X))continue;if(X?.name==="SyntaxError")continue;throw X}}return Z.sort((Q,J)=>Q.localeCompare(J))}catch(W){if(U6(W))return[];throw W}}function eJ($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z;try{let j=VC.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}catch(j){let X=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:X}}}function nZ($,W,Z){if($===void 0||$===null){if(Z)throw Error(`Missing required frontmatter field '${W}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${W}' must be a string.`);let Q=$.trim();if(!Q&&Z)throw Error(`Frontmatter field '${W}' cannot be empty.`);return Q||void 0}function f6($,W){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${W}' must be a boolean.`);return $}function KC($,W){if(J$($.filePath).toLowerCase()!==DF.toLowerCase())return J$($.filePath,rZ($.filePath));if(W&&P5($.filePath)===P5(W,DF))return"Workspace AGENTS.md";if(P5($.filePath)===P5(JC()))return"Global AGENTS.md";return J$($.filePath,rZ($.filePath))}function y5($,W){let{data:Z,body:Q,parseError:J}=eJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in skill file.");let Y=nZ(Z.name,"name",!1)??W.trim();if(!Y)throw Error("Missing skill name.");return{name:Y,description:nZ(Z.description,"description",!1),disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function h5($,W){let{data:Z,body:Q,parseError:J}=eJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in rule file.");let X=nZ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing rule name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function k5($,W){let{data:Z,body:Q,parseError:J}=eJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in workflow file.");let X=nZ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing workflow name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function I5($){return XC($)}function x5($){return jC($)}function g5($){return YC($)}async function LF($){if(J$($)===".cline"){let W=await tJ($);return(await Promise.all(W.map((Q)=>LF(m0(Q,S5))))).flat()}try{let W=await oJ($,{withFileTypes:!0}),Z=[];for(let Q of W){if(Q.isFile()&&Q.name===pZ){Z.push({directoryPath:$,fileName:Q.name,filePath:m0($,Q.name)});continue}let J=m0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await aJ(J).then((X)=>X.isDirectory()).catch((X)=>{if(U6(X))return!1;throw X}))Z.push({directoryPath:J,fileName:pZ,filePath:m0(J,pZ)})}return Z}catch(W){if(U6(W))return[];throw W}}async function aZ($){if(J$($)===".cline"){let W=await tJ($);return(await Promise.all(W.map((Q)=>aZ(m0(Q,"rules.md"))))).flat()}try{if((await aJ($)).isFile())return[{directoryPath:QC($),fileName:J$($),filePath:$}]}catch(W){if(!U6(W))throw W}try{let Z=(await oJ($,{withFileTypes:!0})).filter((J)=>J.isFile()&&iZ(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:m0($,J.name)})),Q=m0($,"AGENTS.md");try{if((await aJ(Q)).isFile()){if(!Z.some((X)=>X.fileName==="AGENTS.md"))Z.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return Z}catch(W){if(U6(W))return[];throw W}}async function FC($){if(J$($)===".cline"){let W=await tJ($);return(await Promise.all(W.map((Q)=>aZ(m0(Q,b5))))).flat()}return aZ($)}function m5($){let W=GC($),Z=$?.workspacePath?m0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Z?_F([...W,Z]):W,discoverFiles:LF,includeFile:(Q)=>Q===pZ,parseFile:(Q)=>y5(Q.content,J$(Q.directoryPath)),resolveId:(Q)=>sJ(Q.name)}}function v5($){let W=$?.directories??x5($?.workspacePath),Z=$?.workspacePath?m0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Z?[...W,Z]:W,discoverFiles:aZ,includeFile:(Q,J)=>Q===".clinerules"||iZ(Q)||iZ(J),parseFile:(Q)=>h5(Q.content,KC(Q,$?.workspacePath)),resolveId:(Q)=>sJ(Q.name)}}function c5($){let W=$?.directories??g5($?.workspacePath),Z=$?.workspacePath?m0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Z?[...W,Z]:W,discoverFiles:FC,includeFile:(Q)=>iZ(Q),parseFile:(Q)=>k5(Q.content,J$(Q.filePath,rZ(Q.filePath))),resolveId:(Q)=>sJ(Q.name)}}function TF($){let W=[m5($?.skills),v5($?.rules),c5($?.workflows)];return new u2(W,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as OF}from"@cline/shared";function AC($,W){if($.description?.trim())return OF($.description,".");if(W==="workflow")return;return OF($.instructions,".")}function UC($){return $.disabled!==!0}function zF($,W){return[...$.getSnapshot(W).entries()].map(([Z,Q])=>({id:Z,record:Q})).filter(({record:Z})=>UC(Z.item)).map(({id:Z,record:Q})=>({id:Z,name:Q.item.name,instructions:Q.item.instructions,description:AC(Q.item,W),kind:W})).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function u5($){let W=new Map;for(let Z of[...zF($,"workflow"),...zF($,"skill")])if(!W.has(Z.name))W.set(Z.name,Z);return[...W.values()].sort((Z,Q)=>Z.name.localeCompare(Q.name))}function qF($,W){if(!$.startsWith("/")||$.length<2)return $;let Z=$.match(/^\/(\S+)/);if(!Z)return $;let Q=Z[1];if(!Q)return $;let J=Q.length+1,j=$.slice(J),X=u5(W).find((Y)=>Y.name===Q);return X?`${X.instructions}${j}`:$}function sZ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function fC($){if(!$||$.length===0)return;let W=$.map(sZ).filter((Z)=>Z.length>0);return W.length>0?new Set(W):void 0}function DC($,W,Z){if(!Z)return!0;let Q=sZ($),J=sZ(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function d5($,W){let Z=fC(W);return[...$.getSnapshot("skill").entries()].map(([J,j])=>{let X=j.item;return{id:J,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0,skill:X}}).filter((J)=>DC(J.id,J.name,Z))}function _C($,W){return d5($,W).filter((Z)=>!Z.disabled).map((Z)=>Z.name.trim()).filter((Z)=>Z.length>0).sort((Z,Q)=>Z.localeCompare(Q))}function LC($,W,Z){let Q=sZ(W);if(!Q)return{error:"Missing skill name."};let J=d5($,Z),j=J.find((H)=>H.id===Q);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 X=Q.includes(":")?Q.split(":").at(-1)??Q:Q,Y=J.filter(({id:H})=>{if(H===X)return!0;return H.endsWith(`:${X}`)}),V=Y.filter(({skill:H})=>H.disabled!==!0);if(V.length===1){let{id:H,skill:G}=V[0];return{id:H,skill:G}}if(V.length>1)return{error:`Skill "${W}" is ambiguous. Use one of: ${V.map(({id:H})=>H).join(", ")}`};if(Y.length===1){let{skill:H}=Y[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(Y.length>1)return{error:`Skill "${W}" is ambiguous, and all matches are disabled: ${Y.map(({id:H})=>H).join(", ")}`};let B=_C($,Z);return{error:B.length>0?`Skill "${W}" not found. Available skills: ${B.join(", ")}`:"No skills are currently available."}}function $j($,W=Promise.resolve(),Z){let Q=new Set,J=async(j,X)=>{await W;let Y=LC($,j,Z);if("error"in Y)return Y.error;let{id:V,skill:B}=Y;if(Q.has(V))return`Skill "${B.name}" is already running.`;Q.add(V);try{let H=X?.trim(),G=H?`
475
+ ${Q}`;return Z||Q}function cR($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function uR($,W){return $.filter((Z)=>cR(Z.name,W))}function dR($,W){return u1(uR($,W))}function lR($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return{};return{beforeRun:async(Z)=>{for(let Q of W){let J=await Q.beforeRun?.(Z);if(J?.stop)return J}return},afterRun:async(Z)=>{for(let Q of W)await Q.afterRun?.(Z)},beforeModel:async(Z)=>{let Q=Z.request,J;for(let j of W){let X=await j.beforeModel?.({...Z,request:Q});if(!X)continue;if(X.stop)return X;J={...J,...X,options:PG(J?.options,X.options)},Q={...Q,...X.messages?{messages:X.messages}:{},...X.tools?{tools:X.tools}:{},...X.options?{options:PG(Q.options,X.options)}:{}}}return J},afterModel:async(Z)=>{for(let Q of W){let J=await Q.afterModel?.(Z);if(J?.stop)return J}return},beforeTool:async(Z)=>{let Q=Z.input,J;for(let j of W){let X=await j.beforeTool?.({...Z,input:Q});if(!X)continue;if(X.stop||X.skip)return X;if(J={...J,...X},Object.hasOwn(X,"input"))Q=X.input}return J},afterTool:async(Z)=>{let Q=Z.result,J;for(let j of W){let X=await j.afterTool?.({...Z,result:Q});if(!X)continue;if(X.stop)return X;if(J={...J,...X},X.result)Q=X.result}return J},onEvent:async(Z)=>{for(let Q of W)await Q.onEvent?.(Z)}}}class P${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 BJ;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($,W={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=W.logger??$.logger,this.telemetry=W.telemetry??$.telemetry,this.createAgentRuntimeImpl=W.createAgentRuntimeImpl??IR,this.conversation=new JJ($.initialMessages),this.messageBuilder=new WJ(MG()),this.contributionRegistry=xR({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 Z=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new VJ({maxConsecutiveMistakes:Z,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,X,Y)=>pR(this.logger,j,X,Y),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,X)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let J=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new YJ(J)}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 W=new Set(this.config.tools.map((Q)=>Q.name)),Z=[...this.config.tools];for(let Q of $)if(!W.has(Q.name))Z.push(Q),W.add(Q.name);this.config={...this.config,tools:Z}}updateConnection($){let W=w2($),Z={...this.config};if(W.providerId!==void 0)Z.providerId=W.providerId;if(W.modelId!==void 0)Z.modelId=W.modelId;if(W.apiKey!==void 0)Z.apiKey=W.apiKey;if(W.baseUrl!==void 0)Z.baseUrl=W.baseUrl;if(W.headers!==void 0)Z.headers=W.headers;if(W.providerConfig!==void 0)Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"reasoningEffort"))Z.reasoningEffort=W.reasoningEffort??void 0;if(Object.hasOwn(W,"thinkingBudgetTokens"))Z.thinkingBudgetTokens=W.thinkingBudgetTokens??void 0;if(Object.hasOwn(W,"thinking")){if(Z.thinking=W.thinking??void 0,W.thinking===!1||W.thinking===null)Z.reasoningEffort=void 0,Z.thinkingBudgetTokens=void 0}this.config=Z}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.messageBuilder.resetConversationState(),this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let W=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=W,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(W)}async shutdown($,W){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($,W,Z){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!1})}continue($,W,Z){return this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let W of this.contributionRegistry.getRegisteredRules()){let Z=await mR(W);if(Z)$.push(Z)}return vR(this.config.systemPrompt,$)}executeRun($){let W;return W=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===W)this.activeRunPromise=null}),this.activeRunPromise=W,W}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 W=new Date,Z=$.userMessage;if(Z!==void 0){let _=await iR(Z,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:_})}let Q=await this.composeSystemPrompt(),J=UG(this.config,this.logger,this.telemetry),j=new Map;for(let _ of this.contributionRegistry.getRegisteredTools())j.set(_.name,_);let X=dR([...j.values()],this.config.toolPolicies),Y=new Map;for(let _ of X)Y.set(_.name,_);for(let _ of this.config.tools)Y.set(_.name,_);let V=this.conversation.getConversationId(),B=SG(this.config),H=Array.from(Y.values()),G=jZ(this.conversation.getMessages()),K=EG({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:B?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[iW]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(B,H),initialMessages:G,systemPrompt:Q}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((_)=>{this.handleRuntimeEvent(_)}),D,U;try{if($.isContinue)D=await F.continue(void 0);else D=await F.run("")}catch(_){U=_ instanceof Error?_:Error(String(_))}finally{A();try{await this.activeTrackerWork}catch(_){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:_})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(D&&D.messages.length>0){let _=i8(D.messages);this.conversation.replaceMessages(_)}let f=new Date;try{return this.buildLegacyResult({runResult:D,thrownError:U,startedAt:W,endedAt:f})}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 $=lR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((W)=>W.hooks)]);return{...$,beforeModel:async(W)=>{let Z=await $.beforeModel?.(W);if(Z?.stop)return Z;let Q=Z?.messages??W.request.messages,J=await this.prepareMessagesForModelRequest(Q);return{...Z,messages:J}}}}createRuntimePrepareTurn($,W){let Z=this.config.prepareTurn;if(!Z)return;return async(Q)=>{let J=i8(Q.messages),j=await this.prepareProviderMessagesForApi(J),X=await Z({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:J,apiMessages:j,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:W,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!X)return;return{...X.messages?{messages:jZ(X.messages)}:{},...X.systemPrompt!==void 0?{systemPrompt:X.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let W=await this.prepareProviderMessagesForApi(XZ($));return jZ(W)}async prepareProviderMessagesForApi($){let W=$,Z=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of Z)W=await Q.build(W);return this.messageBuilder.buildForApi(W)}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 W=this.toolStartedAt.get($.toolCall.toolCallId),Z=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let J=$.message.content.find((V)=>V.type==="tool-result"),j=J?.type==="tool-result"&&J.isError===!0,X=j?gR(J?.type==="tool-result"?J.output:void 0):void 0,Y={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:J?.type==="tool-result"?J.output:void 0,error:X,durationMs:W===void 0?0:Z.getTime()-W.getTime(),startedAt:W??Z,endedAt:Z};if(this.currentRunToolCalls.push(Y),j){if(this.currentTurnFailedTools+=1,X)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${X}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let W=this.currentTurnFailedTools,Z=this.currentTurnSuccessfulTools;if(W>0&&Z===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${W} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(Z>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 W of this.eventAdapter.translate($))this.emitLegacyEvent(W)}syncConversationFromRuntimeMessage($,W){if($.length>0){this.conversation.replaceMessages(i8($));return}if(W.length===0)return;let Z=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),Q=i8(W).filter((J)=>!J.id||!Z.has(J.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let W of this.listeners)try{W($)}catch(Z){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Z})}}inspectLoopForToolCall($,W,Z){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:W});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:Z,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let W=await this.mistakeTracker.record($);if(W.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]}),this.activeRuntime?.abort(W.reason??W.message)})}buildLegacyResult($){let{runResult:W,thrownError:Z,startedAt:Q,endedAt:J}=$,j=J.getTime()-Q.getTime(),X=Z?"error":rR(W),Y=(W?.status==="failed"?W.error?.message:void 0)||W?.outputText||"",V=W?{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens>0?W.usage.cacheReadTokens:void 0,cacheWriteTokens:W.usage.cacheWriteTokens>0?W.usage.cacheWriteTokens:void 0,totalCost:W.usage.totalCost}:this.currentRunUsage,B=W?i8(W.messages):this.conversation.getMessages(),H=SG(this.config);if(Z)throw Z;return{text:Y,usage:V,messages:B,toolCalls:this.currentRunToolCalls,iterations:W?.iterations??0,finishReason:X,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Q,endedAt:J,durationMs:j}}}function pR($,W,Z,Q){if(!$)return;if(W==="debug"){$.debug(Z,Q);return}if(W==="error"&&$.error){$.error(Z,Q);return}let J=W==="warn"?"warn":W==="error"?"error":"info";$.log(Z,{...Q,severity:J})}function rR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function iR($,W,Z,Q){let{buildInitialUserContent:J}=await Promise.resolve().then(() => CG);return J($,W,Z,Q)}function SG($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let W=t3($);if(W?.[$.modelId])return W[$.modelId];return}import{buildClineSystemPrompt as bG}from"@cline/shared";function yG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return bG({ide:W.clineIdeName?.trim()||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,rules:`# Team Teammate Role
476
+ ${Z}`,platform:W.clinePlatform,metadata:W.workspaceMetadata})}function hG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return bG({ide:W.clineIdeName||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,overridePrompt:Z,metadata:W.workspaceMetadata,platform:W.clinePlatform})}function S$($){let W={...$};return{getRuntimeConfig:()=>W,getConnectionConfig:()=>({providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature}),updateConnectionDefaults:(Z)=>{W={...W,...Z}}}}function C2($){let W=$.configProvider.getRuntimeConfig(),Z=$.kind==="teammate"?yG($.prompt,W):hG($.prompt,W);return{...$.configProvider.getConnectionConfig(),systemPrompt:Z,tools:$.tools,maxIterations:$.maxIterations??W.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:W.hooks,extensions:W.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:W.logger,role:$.role}}function b$($){let W=C2($),Z=new P$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);return Z}var oR=HJ.object({systemPrompt:HJ.string().describe("System prompt defining the sub-agent's behavior"),task:HJ.string().describe("Task for the sub-agent to complete")});function y$($){return nR({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(oR),execute:async(W,Z)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(W,Z):$.subAgentTools??[],J=b$({kind:"subagent",prompt:W.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:Z.agentId,abortSignal:Z.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=J.getAgentId(),X=J.getConversationId(),Y=Z.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:X,parentAgentId:Y,input:W})}catch{}try{let V=await J.run(W.task),B={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,result:B,agentResult:V})}catch{}return B}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as _0,TEAM_AWAIT_TIMEOUT_MS as sR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as tR,TEAM_RUN_TEXT_PREVIEW_LIMIT as eR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as $E,TeamAttachOutcomeFragmentInputSchema as kG,TeamAwaitRunsInputSchema as IG,TeamBroadcastInputSchema as xG,TeamBroadcastToolResultSchema as WE,TeamCancelRunInputSchema as gG,TeamCancelRunToolResultSchema as ZE,TeamCleanupInputSchema as mG,TeamCleanupToolResultSchema as QE,TeamCreateOutcomeInputSchema as vG,TeamCreateOutcomeToolResultSchema as JE,TeamFinalizeOutcomeInputSchema as cG,TeamFinalizeOutcomeToolResultSchema as jE,TeamListOutcomesInputSchema as uG,TeamListRunsInputSchema as dG,TeamMailboxMessageToolResultSchema as XE,TeamMissionLogInputSchema as lG,TeamMissionLogToolResultSchema as YE,TeamOutcomeFragmentToolResultSchema as pG,TeamOutcomeToolResultSchema as VE,TeamReadMailboxInputSchema as rG,TeamReviewOutcomeFragmentInputSchema as iG,TeamRunTaskInputSchema as nG,TeamRunTaskToolResultSchema as GJ,TeamRunToolSummarySchema as KJ,TeamSendMessageInputSchema as aG,TeamSendMessageToolResultSchema as BE,TeamShutdownTeammateInputSchema as oG,TeamSimpleAgentStatusToolResultSchema as sG,TeamSpawnTeammateInputSchema as tG,TeamStatusInputSchema as eG,TeamStatusToolResultSchema as HE,TeamTaskInputSchema as $K,TeamTaskToolResultSchema as J5,validateWithZod as g,zodToJsonSchema as f0}from"@cline/shared";function WK($,W){let Z=$.replace(/\s+/g," ").trim();if(Z.length<=W)return Z;return`${Z.slice(0,Math.max(0,W-3)).trimEnd()}...`}function P2($,W){if($===void 0)throw Error(`Missing required field: ${W}`);return $}function GE($){let W=$.result;if(!W)return;return{textPreview:WK(W.text,eR),iterations:W.iterations,finishReason:W.finishReason,durationMs:W.durationMs,usage:{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens,cacheWriteTokens:W.usage.cacheWriteTokens,totalCost:W.usage.totalCost}}}function HZ($){return $?.toISOString()}function FJ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:WK($.message,tR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:HZ($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:HZ($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:HZ($.heartbeatAt),lastProgressAt:HZ($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:GE($)}}function KE($){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 a8=["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 ZK($){let W=[];if($.createBaseTools)W.push(...$.createBaseTools());W.push(...S2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:C2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:W,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function o8($){let W=$.leadAgentId??"lead",Z=$.restoredFromPersistence===!0,Q=S2({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;ZK({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),J.push(j.agentId)}return{tools:Q,restoredFromPersistence:Z,restoredTeammates:J}}function S2($){let W=$.allowSpawn??!0,Z=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,J=[];if(Z)J.push(_0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:f0(tG),execute:async(X)=>{let Y=g(tG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!W)throw Error("Spawning teammates is disabled in this context.");let V={agentId:Y.agentId,rolePrompt:Y.rolePrompt};if(ZK({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!Q)$.onLeadToolsUnlocked?.(S2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return g(sG,{agentId:Y.agentId,status:"spawned"})}}));if(!Q)return J;J.push(_0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:f0(oG),execute:async(X)=>{let Y=g(oG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(Y.agentId,Y.reason),g(sG,{agentId:Y.agentId,status:"stopped"})}})),J.push(_0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:f0(eG),execute:async(X)=>{return g(eG,X),g(HE,$.runtime.getSnapshot())}})),J.push(_0({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:f0($K),execute:async(X)=>{let Y=g($K,X);switch(Y.action){case"create":{let V=new Set($E.create??[]),B=Object.entries(X).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),H=$.runtime.createTask({title:P2(Y.title,"title"),description:P2(Y.description,"description"),dependsOn:Y.dependsOn,assignee:Y.assignee,createdBy:$.requesterId});return g(J5,{action:"create",taskId:H.id,status:H.status,...B.length>0?{ignoredFields:B,note:`Ignored fields for action=create: ${B.join(", ")}`}:{}})}case"list":return g(J5,{action:"list",tasks:$.runtime.listTaskItems({status:Y.status,assignee:Y.assignee})});case"claim":{let V=$.runtime.claimTask(P2(Y.taskId,"taskId"),$.requesterId);return g(J5,{action:"claim",taskId:V.id,status:V.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 V=$.runtime.completeTask(P2(Y.taskId,"taskId"),$.requesterId,P2(Y.summary,"summary"));return g(J5,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(P2(Y.taskId,"taskId"),$.requesterId,P2(Y.reason,"reason"));return g(J5,{action:"block",taskId:V.id,status:V.status})}}}}));let j=new Map;return J.push(_0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:f0(nG),execute:async(X)=>{let Y=g(nG,X);if(Y.runMode==="async"){let H=$.runtime.startTeammateRun(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0});return g(GJ,{agentId:Y.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${Y.agentId} and queued as ${H.id}.`,runId:H.id})}let V=j.get(Y.agentId);if(V){let H=await V;return g(GJ,{...H,status:"joined",deduped:!0,message:`Task for ${Y.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let B=$.runtime.routeToTeammate(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0}).then((H)=>g(GJ,{agentId:Y.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${Y.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(Y.agentId)});return j.set(Y.agentId,B),await B}})),J.push(_0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:f0(gG),execute:async(X)=>{let Y=g(gG,X),V=$.runtime.cancelRun(Y.runId,Y.reason);return g(ZE,{runId:V.id,status:V.status})}})),J.push(_0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:f0(dG),execute:async(X)=>g(KJ.array(),$.runtime.listRuns(g(dG,X)).map(FJ))})),J.push(_0({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:f0(IG),timeoutMs:sR,execute:async(X)=>{let Y=g(IG,X);if(Y.runId){let H=await $.runtime.awaitRun(Y.runId);return KE(H),g(KJ,FJ(H))}let V=await $.runtime.awaitAllRuns(),B=V.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(B.length>0){let H=B.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return g(KJ.array(),V.map(FJ))}})),J.push(_0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:f0(aG),execute:async(X)=>{let Y=g(aG,X),V=$.runtime.sendMessage($.requesterId,Y.toAgentId,Y.subject,Y.body,Y.taskId??void 0);return g(BE,{id:V.id,toAgentId:V.toAgentId})}})),J.push(_0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:f0(xG),execute:async(X)=>{let Y=g(xG,X),V=$.runtime.broadcast($.requesterId,Y.subject,Y.body,{taskId:Y.taskId??void 0});return g(WE,{delivered:V.length})}})),J.push(_0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:f0(rG),execute:async(X)=>{let Y=g(rG,X);return g(XE.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:Y.unreadOnly,markRead:!0}))}})),J.push(_0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:f0(lG),execute:async(X)=>{let Y=g(lG,X),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:Y.taskId||void 0,kind:Y.kind,summary:Y.summary,evidence:Y.evidence?.length?Y.evidence:void 0,nextAction:Y.nextAction||void 0});return g(YE,{id:V.id})}})),J.push(_0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:f0(mG),execute:async(X)=>{if(g(mG,X),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),g(QE,{status:"cleaned"})}})),J.push(_0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:f0(vG),execute:async(X)=>{let Y=g(vG,X),V=$.runtime.createOutcome({title:Y.title,requiredSections:Y.requiredSections,createdBy:$.requesterId});return g(JE,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(_0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:f0(kG),execute:async(X)=>{let Y=g(kG,X),V=$.runtime.attachOutcomeFragment({outcomeId:Y.outcomeId,section:Y.section,sourceAgentId:$.requesterId,sourceRunId:Y.sourceRunId||void 0,content:Y.content});return g(pG,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:f0(iG),execute:async(X)=>{let Y=g(iG,X),V=$.runtime.reviewOutcomeFragment({fragmentId:Y.fragmentId,reviewedBy:$.requesterId,approved:Y.approved});return g(pG,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:f0(cG),execute:async(X)=>{let Y=g(cG,X),V=$.runtime.finalizeOutcome(Y.outcomeId);return g(jE,{outcomeId:V.id,status:V.status})}})),J.push(_0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:f0(uG),execute:async(X)=>{return g(uG,X),g(VE.array(),$.runtime.listOutcomes())}})),J}function GZ($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}function QK($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var FE=[{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:y$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...a8]}],AE={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function UE($){return $==="plan"||$==="yolo"?$:"act"}function jK($){let W=UE($.mode),Z=a0[e1({mode:W})],Q=r8($.providerId??"",$.modelId??"",W,p8);return{mode:W,flags:{...Z,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function JK($,W){if(W.disabledToolIds?.has($))return!1;let{flags:Z}=jK(W);if($==="spawn_agent")return Z.enableSpawnAgent===!0;if($==="teams")return Z.enableAgentTeams===!0;if($==="editor")return Z.enableEditor===!0||Z.enableApplyPatch===!0;let Q=AE[$];return Q?Z[Q]===!0:!1}function DE($,W){if($.id==="editor"){let{flags:Z}=jK(W),Q=Z.enableApplyPatch===!0&&Z.enableEditor!==!0;return{...$,defaultEnabled:JK($.id,W),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:JK($.id,W)}}function b2($={}){return FE.map((W)=>DE(W,$))}function KZ($={}){return b2($).filter((W)=>W.defaultEnabled).map((W)=>W.id)}function FZ($){if(!$.enabled)return new Set;let W=b2($.availabilityContext),Z=new Set(W.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(W.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!Z.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${W.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function j5($,W={}){return b2(W).filter((Z)=>$.has(Z.id)).flatMap((Z)=>Z.headlessToolNames)}function AZ($,W={}){return j5($,W)}function y2($={}){let{executorOptions:W={},executors:Z,...Q}=$,J={...l8(W),...Z??{}};return N$({...Q,executors:J})}import{mkdirSync as zE,writeFileSync as qE}from"node:fs";import{dirname as ME}from"node:path";import{normalizeUserInput as RE,stripModeNotices as EE}from"@cline/shared";import{nanoid as NE}from"nanoid";var YK={};w(YK,{sanitizeSessionToken:()=>h2,parseTeamTaskSubSessionId:()=>t8,parseSubSessionId:()=>Y5,makeTeamTaskSubSessionId:()=>X5,makeSubSessionId:()=>s8,deriveSubsessionStatus:()=>V5});import{nanoid as LE}from"nanoid";function h2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function s8($,W){let Z=h2($),Q=h2(W),J=`${Z}__${Q}`;return J.length>180?J.slice(0,180):J}function X5($,W){let Z=h2($),Q=h2(W);return`${Z}__teamtask__${Q}__${LE(6)}`}function t8($){let Z=$.indexOf("__teamtask__");if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+12),j=J.lastIndexOf("__");if(j<=0)return null;let X=J.slice(0,j),Y=J.slice(j+2);if(!Q||!X||!Y)return null;return{rootSessionId:Q,agentId:X,teamTaskId:Y}}function Y5($){if(t8($))return null;let W="__",Z=$.indexOf(W);if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+W.length);if(!Q||!J)return null;return{rootSessionId:Q,agentId:J}}function V5($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let W=String($.reason??"").toLowerCase();if(W.includes("cancel")||W.includes("abort")||W.includes("interrupt"))return"cancelled";if(W.includes("fail")||W.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as Z0}from"zod";var HK={};w(HK,{isTerminalSessionStatus:()=>BK,isNonTerminalSessionStatus:()=>K0,SessionSource:()=>F0,SESSION_STATUSES:()=>B5,NON_TERMINAL_SESSION_STATUSES:()=>VK});import{SESSION_STATUS_VALUES as TE}from"@cline/shared";var B5=TE,VK=["idle","running","pending"];function BK($){return!VK.includes($)}function K0($){return!BK($)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var OE=Z0.enum(B5),m0=Z0.object({version:Z0.literal(1),session_id:Z0.string().min(1),source:Z0.string().min(1),pid:Z0.number().int(),started_at:Z0.string().min(1),ended_at:Z0.string().min(1).optional(),exit_code:Z0.number().int().nullable().optional(),status:OE,interactive:Z0.boolean(),provider:Z0.string().min(1),model:Z0.string().min(1),cwd:Z0.string().min(1),workspace_root:Z0.string().min(1),team_name:Z0.string().min(1).optional(),enable_tools:Z0.boolean(),enable_spawn:Z0.boolean(),enable_teams:Z0.boolean(),prompt:Z0.string().optional(),metadata:Z0.record(Z0.string(),Z0.unknown()).optional(),messages_path:Z0.string().min(1).optional(),compaction_path:Z0.string().min(1).optional()});function GK($){if(!$)return!1;return Object.values($).some((W)=>typeof W==="function")}function UJ($,W){let Z=[...$??[],...W??[]];if(Z.length===0)return;let Q=[],J=new Set;for(let j of Z){if(J.has(j.name))continue;J.add(j.name),Q.push(j)}return Q}function KK($){return JSON.stringify($,(W,Z)=>{if(Z instanceof Error)return{name:Z.name,message:Z.message,stack:Z.stack};return Z})}function $$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function AJ($,W){let Z={...$};Z.id=$$(Z.id)??NE();let Q=Z.modelInfo&&typeof Z.modelInfo==="object"?{...Z.modelInfo}:void 0,J={id:$$(Q?.id)??$$(Z.modelId)??$$(W?.id),provider:$$(Q?.provider)??$$(Z.providerId)??$$(W?.provider),family:$$(Q?.family)??$$(W?.family)};if(delete Z.providerId,delete Z.modelId,J.id&&J.provider)Z.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Z.modelInfo;return Z}function UZ($){return $.map((W)=>AJ(W))}function DZ($,W,Z=[]){let Q=$.map((V,B)=>{let H=Z[B],K=H?.role===V.role&&JSON.stringify(H.content)===JSON.stringify(V.content)?{...H,...V}:{...V};return AJ(K)}),J=Z.length,j=[];for(let V=J;V<Q.length;V+=1)if(Q[V]?.role==="assistant")j.push(V);if(j.length===0){let V=[...Q].reverse().findIndex((B)=>B.role==="assistant");if(V===-1)return Q;j.push(Q.length-1-V)}let X=j[j.length-1],Y=j.some((V)=>Q[V]?.metrics);for(let V of j){let B=Q[V],H=B.metrics;if(!H&&V===X&&!Y){let G=W.usage;H={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}Q[V]={...AJ(B,{id:W.model.id,provider:W.model.provider,family:W.model.info?.family}),...H?{metrics:H}:{},ts:B.ts??W.endedAt.getTime()}}return Q}function H5($){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 wE=120;function k2($){let W=$?.trim();return W?W.slice(0,wE):void 0}function DJ($){let W=EE(RE($??"")).trim();if(!W)return;return k2(W.split(`
477
+ `)[0]?.trim())}function h$($){if(!$)return;let W={...$},Z=k2(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function G5($){let W=h$($.metadata)??{},Z=$.title!==void 0?k2($.title):DJ($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function _J($){let W=t8($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=Y5($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function fJ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:UZ($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function FK($,W,Z){zE(ME($),{recursive:!0}),qE($,`${JSON.stringify(fJ({updatedAt:W,context:Z,messages:[]}),null,2)}
478
+ `,"utf8")}function AK($,W){return m0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.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:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function UK($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}R0();var DK={};w(DK,{summarizeUsageFromMessages:()=>$6,sumUsageTotals:()=>K5,getCurrentContextSize:()=>LJ,createInitialAccumulatedUsage:()=>z0,accumulateUsageTotals:()=>L0});function z0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function L0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function K5($){let W=z0();for(let Z of $)W=L0(W,Z);return W}function e8($){return typeof $==="number"&&Number.isFinite($)?$:0}function $6($){let W=z0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=L0(W,{inputTokens:e8(Q.inputTokens),outputTokens:e8(Q.outputTokens),cacheReadTokens:e8(Q.cacheReadTokens),cacheWriteTokens:e8(Q.cacheWriteTokens),totalCost:e8(Q.cost)})}return W}function LJ($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=e8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function CE($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function TJ($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function W$($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function PE($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function SE($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function OJ($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=TJ(W),G=W$({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=CE(W.input);if(K)QW(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(T8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))JW(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")V4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")V4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=PE(W);if(B){j.turnPrimaryUsage=L0(j.turnPrimaryUsage??z0(),K);let A=L0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),L8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),WW(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=SE({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),D=j.turnUsageByAgent??new Map;j.turnUsageByAgent=D,D.set(A,L0(D.get(A)??z0(),K))}let F=L0(j.turnPrimaryUsage??z0(),K5(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,L0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:KK(W),ts:Date.now()}})}function Z$($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as mw}from"@cline/llms";import{hasRuntimeConfigExtension as vw}from"@cline/shared";X1();import{existsSync as zZ,readFileSync as fN,statSync as LN}from"node:fs";import{basename as TN,dirname as TZ,join as qZ,resolve as OZ}from"node:path";import{discoverPluginModulePaths as ON,resolveConfiguredPluginModulePaths as xK,resolvePluginConfigSearchPaths as zN,SKILLS_CONFIG_DIRECTORY_NAME as qN}from"@cline/shared/storage";import{resolve as sE}from"node:path";import{normalizePluginManifest as tE}from"@cline/shared";import{existsSync as w0,readFileSync as Z6}from"node:fs";import{builtinModules as bE,createRequire as RJ}from"node:module";import{dirname as k$,extname as A5,isAbsolute as yE,resolve as o}from"node:path";import{fileURLToPath as fK}from"node:url";import{PLUGIN_FILE_EXTENSIONS as hE}from"@cline/shared";var LK=k$(fK(import.meta.url)),kE=RJ(import.meta.url),IE=o(LK,"..","..","..","..",".."),zJ=mE(IE),xE=["@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"],EJ=new Set(bE.flatMap(($)=>[$,$.replace(/^node:/,"")])),F5=new Set(hE),gE=["development","node","import","require","default"];function mE($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(w0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!w0(j))continue;try{let X=JSON.parse(Z6(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(w0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=vE(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function vE($,W){let Z=NJ(W);if(!Z)return null;let Q=TK($,Z);for(let J of Q)if(w0(J))return J;return null}function NJ($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of gE){let J=NJ(Z[Q],W);if(J)return J}return null}function TK($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function cE($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function _Z($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function W6($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function uE($){let W=W6($);if($===W)return".";return`.${$.slice(W.length)}`}function OK($){return W6($).startsWith("@cline/")}function qJ($,W){let Z=W6(W),Q=k$($);while(!0){let J=o(Q,"node_modules",Z);if(w0(J)||w0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function _K($){return MJ($)!==null}function MJ($){try{return kE.resolve($)}catch{}return dE($)}function dE($){let W=W6($),Z=zK(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse(Z6(Q,"utf8")),j=uE($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=NJ(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...TK(Z,Y).filter((H)=>H!==V)];for(let H of B)if(w0(H))return H;return null}catch{return null}}function lE(){let $=[LK],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(k$(k$(W)));let Z=process.execPath?.trim();if(Z)$.push(k$(Z));return[...new Set($.map((Q)=>o(Q)))]}function pE($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(w0(Q))try{if(JSON.parse(Z6(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(w0(J))return k$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function zK($){for(let W of lE()){let Z=pE(W,$);if(Z)return Z}return null}function rE($){let Z=k$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(w0(J))try{let X=JSON.parse(Z6(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function qK($,W){let Z=W.startsWith("file:")?fK(W):yE(W)?W:o(k$($),W);if(w0(Z)&&F5.has(A5(Z)))return Z;for(let Q of F5){let J=`${Z}${Q}`;if(w0(J))return J}for(let Q of F5){let J=o(Z,`index${Q}`);if(w0(J))return J}return null}function MK($){let W=new Set,Z=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function iE($){return A5($)!==".ts"}function RK($,W,Z=new Set){if(Z.has($)||!w0($))return;if(Z.add($),!F5.has(A5($)))return;let Q=Z6($,"utf8"),J=iE($);for(let j of MK(Q)){if(j.startsWith("node:")||EJ.has(j))continue;if(_Z(j)){if(!J)continue;if(Object.hasOwn(zJ,j)||Object.hasOwn(zJ,W6(j))||qJ($,j)||OK(j)&&_K(j)||W&&_K(j))continue;throw Error(`Cannot find module '${W6(j)}'`)}let X=qK($,j);if(X)RK(X,W,Z)}}function EK($,W=new Set,Z=new Set){if(W.has($)||!w0($))return Z;if(W.add($),!F5.has(A5($)))return Z;let Q=Z6($,"utf8");for(let J of MK(Q)){if(Z.add(J),_Z(J))continue;let j=qK($,J);if(j)EK(j,W,Z)}return Z}function nE($,W){let Z=RJ($),Q={},J=EK($),j=new Set(xE);for(let[X,Y]of Object.entries(zJ)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if(_Z(X)&&(OK(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||qJ($,X))continue;let Y=MJ(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!_Z(X)||Object.hasOwn(Q,X)||qJ($,X)||X.startsWith("node:")||EJ.has(X))continue;let Y=MJ(X);if(Y)Q[X]=Y}return Q}function aE($){let W=A5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var I2;function oE(){if(I2!==void 0)return I2;let $=zK("jiti");if(!$)return I2=null,null;let W=o($,"dist","babel.cjs");if(!w0(W))return I2=null,null;try{let Q=RJ(W)(W);I2=typeof Q==="function"?Q:null}catch{I2=null}return I2}async function NK($,W={}){let Z=!rE($);RK($,Z);let Q=nE($,Z),J=cE(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>aE(G)).map(([G])=>G),V=oE(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...EJ],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function wK($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function CK($){return typeof $==="object"&&$!==null}function wJ($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function eE($,W){if(!CK($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!wJ($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!wJ($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!wJ($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function $N($,W){if(!CK($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);eE($,W)}async function U5($,W={}){let Z=sE(W.cwd??process.cwd(),$),Q=await NK(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];$N(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:tE(X.manifest),setup:V}}async function fZ($,W={}){return(await x2($,W)).plugins}async function x2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await U5(Y,W);if(!wK(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as bJ}from"node:fs";import{createRequire as IK}from"node:module";import{dirname as LZ,join as J6}from"node:path";import{fileURLToPath as jN}from"node:url";var hK={};w(hK,{resolveSubprocessRuntimeExecutable:()=>CJ,buildSubprocessSandboxCommand:()=>yK,SubprocessSandbox:()=>Q6,CLINE_JS_RUNTIME_PATH_ENV:()=>bK});import{spawn as WN}from"node:child_process";import{basename as ZN}from"node:path";import{augmentNodeCommandForDebug as QN,withResolvedClineBuildEnv as JN}from"@cline/shared";function PK($){if($ instanceof Error)return $;return Error(String($))}var bK="CLINE_JS_RUNTIME_PATH";function SK($){let W=$?.trim();if(!W)return!1;let Z=ZN(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function CJ($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[bK]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(SK(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&SK(j))return j}return"node"}function yK($,W={}){let Z=CJ({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return QN([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class Q6{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=yK($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=WN(W[0]??CJ(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:JN(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${PK(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${PK(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),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 W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function XN($){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 D5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function YN(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function VN(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=IK($).resolve(`${YN()}/package.json`),Q=J6(LZ(Z),"extensions","plugin-sandbox-bootstrap.js");return bJ(Q)?Q:void 0}catch{return}}function BN(){let $=process.execPath?.trim();if(!$)return;let W=J6(LZ(LZ($)),"extensions","plugin-sandbox-bootstrap.js");return bJ(W)?W:void 0}function HN(){let $=LZ(jN(import.meta.url)),W=IK(import.meta.url),Z=[J6($,"plugin-sandbox-bootstrap.js"),J6($,"extensions","plugin-sandbox-bootstrap.js"),J6($,"agents","plugin-sandbox-bootstrap.js"),VN(),BN()];for(let j of Z.filter((X)=>typeof X==="string"))if(bJ(j))return{file:j};let Q=J6($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
479
+ `)}}var PJ=HN();function SJ($,W,Z){if(typeof $==="number"&&$>0)return $;if(Z){let Q=process.env[Z];if(Q){let J=Number(Q);if(Number.isInteger(J)&&J>0)return J}}return W}async function j6($){let W=new Q6({name:"plugin-sandbox",..."file"in PJ?{bootstrapFile:PJ.file}:{bootstrapScript:PJ.script},onEvent:$.onEvent}),Z=SJ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=SJ($.hookTimeoutMs,3000),J=SJ($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},X,Y=()=>{return X??=W.call("initialize",j,{timeoutMs:Z}).finally(()=>{X=void 0}),X},V;try{V=await W.call("initialize",j,{timeoutMs:Z})}catch(G){throw await W.shutdown().catch(()=>{}),G}let B=V.plugins.map(XN);return{extensions:B.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{GN(F,W,G,J,Y),KN(F,W,G,J,Y),FN(F,W,G,J,Y),UN(F,W,G,J,Y),AN(F,G)}};return K.hooks=_N(W,G,Q,Y),K}),failures:V.failures,pluginPaths:B.map((G)=>G.pluginPath),shutdown:async()=>{await W.shutdown()},warnings:V.warnings}}function GN($,W,Z,Q,J){for(let j of Z.contributions?.tools??[]){let X={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(Y,V)=>{try{return await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}catch(B){if(!D5(B))throw B;return await J(),await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}}};$.registerTool(X)}}function KN($,W,Z,Q,J){for(let j of Z.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(X)=>{try{return await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}catch(Y){if(!D5(Y))throw Y;return await J(),await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}}})}function FN($,W,Z,Q,J){for(let j of Z.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}catch(X){if(!D5(X))throw X;return await J(),await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}}:j.content??""})}function AN($,W){for(let Z of W.contributions?.providers??[])$.registerProvider({name:Z.name,description:Z.description,metadata:Z.metadata});for(let Z of W.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Z.eventType,source:Z.source,description:Z.description,attributesSchema:Z.attributesSchema,payloadSchema:Z.payloadSchema,examples:Z.examples,metadata:Z.metadata});for(let Z of W.contributions?.mcpServers??[])$.registerMcpServer(Z)}function UN($,W,Z,Q,J){for(let j of Z.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(X){try{let Y=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return kK(Y)?Y:X}catch(Y){if(!D5(Y))throw Y;await J();let V=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return kK(V)?V:X}}})}function kK($){return Array.isArray($)&&$.every((W)=>typeof W==="object"&&W!==null&&("role"in W)&&("content"in W))}function DN($,W,Z,Q,J){return async(j)=>{try{return await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}catch(X){if(!D5(X))throw X;return await J(),await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}}}function _N($,W,Z,Q){let J={};for(let j of W.hooks??[])J[j]=DN($,W.pluginId,j,Z,Q);return Object.keys(J).length>0?J:void 0}var hJ="package.json",MN="package";function _5($){return zN($)}function f5($){return ON($)}function RN($){try{return zZ($)&&LN($).isDirectory()}catch{return!1}}function kJ($){let W=[],Z=new Set;for(let Q of $){let J=OZ(Q);if(Z.has(J))continue;Z.add(J),W.push(J)}return W}function gK($){let W=kJ($);return DW(W)}function mK($){return _5($).flatMap((W)=>f5(W)).filter((W)=>zZ(W))}function EN($,W){let Z=[];for(let Q of $)try{Z.push(...xK([Q],W))}catch{}return Z}function yJ($){return typeof $==="object"&&$!==null}function NN($){try{let W=JSON.parse(fN(qZ($,hJ),"utf8"));if(!yJ(W)||!yJ(W.cline))return[];let Z=W.cline.plugins;if(!Array.isArray(Z))return[];let Q=[];for(let J of Z){if(typeof J==="string"){Q.push(J);continue}if(!yJ(J)||!Array.isArray(J.paths))continue;for(let j of J.paths)if(typeof j==="string")Q.push(j)}return Q}catch{return[]}}function vK($,W){let Z=OZ(W);return NN($).some((Q)=>OZ($,Q)===Z)}function wN($,W){return TN($)===MN&&zZ(qZ(TZ($),hJ))&&vK(TZ($),W)}function CN($){let W=OZ($),Z=[],Q=TZ(W);while(!0){if(wN(Q,W)){Z.push(Q);break}if(zZ(qZ(Q,hJ))){if(vK(Q,W))Z.push(Q);break}let J=TZ(Q);if(J===Q)break;Q=J}return kJ(Z)}function Q$($={}){let W=$.cwd??process.cwd(),Z=mK($.workspacePath),Q=xK($.pluginPaths??[],W);return gK([...Q,...Z])}function PN($={}){let W=$.cwd??process.cwd(),Z=mK($.workspacePath),Q=EN($.pluginPaths??[],W);return gK([...Q,...Z])}function J$($){let W=[];for(let Z of $)for(let Q of CN(Z)){let J=qZ(Q,qN);if(RN(J))W.push(J)}return kJ(W)}function cK($={}){return J$(PN($))}async function X6($={}){let W=Q$($);if(W.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await x2(W,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let Z=await j6({pluginPaths:W,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:Z.extensions??[],shutdown:Z.shutdown,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}import{execFile as SN}from"node:child_process";import{promisify as bN}from"node:util";var yN=bN(SN);function IJ($,W){$?.log(W,{severity:"warn"})}function hN($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))return;let Z=W;if(!Z.latest||!Array.isArray(Z.history))return;let Q=Z.latest,J=Z.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:J}}async function g2($,W){let Z=await yN("git",["-C",$,...W],{windowsHide:!0});return{stdout:Z.stdout.trim(),stderr:Z.stderr.trim()}}async function xJ($,W){if(!$)return;let Z=`refs/cline/checkpoints/${W}/`;try{let{stdout:Q}=await g2($,["for-each-ref","--format=%(refname)",Z]),J=Q.trim().split(`
480
+ `).filter(Boolean);await Promise.allSettled(J.map((j)=>g2($,["update-ref","-d",j])))}catch{}}async function uK($,W,Z){if(!$||Z.length===0)return;await Promise.allSettled(Z.map((Q)=>g2($,["update-ref",`refs/cline/checkpoints/${W}/${Q.runCount}`,Q.ref])))}function kN($,W){let Z=$.findIndex((Q)=>Q.runCount===W.runCount);if(Z<0)return[...$,W];return $.map((Q,J)=>J===Z?W:Q)}function dK($){let W=$.initialRunCount??0,Z,Q=async()=>{if(Z!==void 0)return Z;try{Z=(await g2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Z=!1}return Z},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:W});if(!await Q())return;let j=async(B)=>{try{let G=(await g2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:W,kind:"commit"}}catch(H){IJ($.logger,`${B}: ${H instanceof Error?H.message:String(H)}`);return}},X=`cline checkpoint session=${$.sessionId} run=${W}`,Y="";try{Y=(await g2($.cwd,["stash","create",X])).stdout.trim()}catch(B){return IJ($.logger,`Checkpoint snapshot failed: ${B instanceof Error?B.message:String(B)}`),j("Checkpoint HEAD fallback failed")}if(!Y)return j("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${W}`;try{await g2($.cwd,["update-ref",V,Y])}catch(B){IJ($.logger,`Checkpoint store failed: ${B instanceof Error?B.message:String(B)}`);return}return{ref:Y,createdAt:Date.now(),runCount:W,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;W+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||W<1)return;let X=await J();if(!X)return;let Y=await $.readSessionMetadata(),V=hN(Y);if(V?.latest.ref===X.ref)return;let B=kN(V?.history??[],X);await $.writeSessionMetadata({...Y??{},checkpoint:{latest:X,history:B}});return}}}import{spawn as lN}from"node:child_process";import{appendFileSync as pN,readFileSync as rN}from"node:fs";import{join as iN}from"node:path";import{augmentNodeCommandForDebug as rK,withResolvedClineBuildEnv as vJ}from"@cline/shared";import{ensureHookLogDir as lK}from"@cline/shared/storage";function Y6($,W){if(!W)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:W}}import{existsSync as IN,readdirSync as xN}from"node:fs";import{basename as gN,extname as mN,join as vN}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as MZ,resolveHooksConfigSearchPaths as cN}from"@cline/shared/storage";function L5($){return cN($)}var V6;((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"})(V6||={});var T5={["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"},uN=new Map(Object.values(V6).map(($)=>[$.toLowerCase(),$])),dN=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function O5($){let W=mN($).toLowerCase();if(!dN.has(W))return;let Z=gN($,W).trim().toLowerCase();return uN.get(Z)}function I$($){let W=[],Z=new Set,Q=L5($).filter((J)=>IN(J));for(let J of Q)try{for(let j of xN(J,{withFileTypes:!0})){if(!j.isFile())continue;let X=O5(j.name);if(!X)continue;let Y=vN(J,j.name);if(Z.has(Y))continue;Z.add(Y),W.push({fileName:X,hookEventName:T5[X],path:Y})}}catch{}return W.sort((J,j)=>J.path.localeCompare(j.path))}function EZ($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))W[Z]=typeof Q==="string"?Q:JSON.stringify(Q);return W}function RZ($,W,Z){let Q=Z instanceof Error?`: ${Z.message}`:"",J=`${W}${Q}`;if($){try{$.log(J,{severity:"warn",...Z!==void 0?{error:Z}:{}})}catch{}return}console.warn(J)}function nN($,W){if(!W)return $;if(!$)return{...W};let Z=[$.context,W.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
481
+ `),Q=[...$.appendMessages??[],...W.appendMessages??[]];return{cancel:$.cancel===!0||W.cancel===!0?!0:void 0,review:$.review===!0||W.review===!0?!0:void 0,context:Z||void 0,overrideInput:W.overrideInput!==void 0?W.overrideInput:$.overrideInput,systemPrompt:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function aN($){if(!$||typeof $!=="object")return;let W=$,Z=typeof W.context==="string"?W.context:typeof W.contextModification==="string"?W.contextModification:typeof W.errorMessage==="string"?W.errorMessage:void 0;return{cancel:typeof W.cancel==="boolean"?W.cancel:void 0,review:typeof W.review==="boolean"?W.review:void 0,context:Z,overrideInput:Object.hasOwn(W,"overrideInput")?W.overrideInput:void 0}}function gJ($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function C0($,W){let Z=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:W.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:W.workspacePath?[W.workspacePath]:[],workspaceInfo:W.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function oN($){let W=$.trim();if(!W)return{};let Q=W.split(`
482
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function sN($,W){let Z=$.stdin;if(!Z)throw Error("hook command failed to create stdin");await new Promise((Q,J)=>{let j=!1,X=()=>{Z.off("error",V),Z.off("finish",B),$.off("close",H)},Y=(G)=>{if(j)return;if(j=!0,X(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){Q();return}J(G);return}Q()},V=(G)=>Y(G),B=()=>Y(),H=()=>Y();Z.on("error",V),Z.once("finish",B),$.once("close",H);try{Z.end(W)}catch(G){Y(G)}})}async function iK($,W){if(W.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await pK($,W)}catch(Z){let Q=$w(W.command,process.platform,Z);if(!Q)throw Z;return await pK($,{...W,command:Q})}}async function pK($,W){let Z=rK(W.command,{env:W.env,debugRole:"hook"}),Q=lN(Z[0],Z.slice(1),{cwd:W.cwd,env:vJ(W.env),stdio:W.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W.detached,windowsHide:!0}),J=new Promise((K)=>{Q.once("spawn",()=>K())}),j=new Promise((K,F)=>{Q.once("error",(A)=>F(A))}),X=JSON.stringify($);if(await Promise.race([J,j]),await sN(Q,X),W.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let Y="",V="",B=!1,H;Q.stdout.on("data",(K)=>{Y+=K.toString()}),Q.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,Q.kill("SIGKILL")},W.timeoutMs);Q.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=oN(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,j])}function tN($){try{let Z=rN($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Z?.startsWith("#!"))return;let Q=Z.slice(2).trim();if(!Q)return;let J=Q.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function eN($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function $w($,W=process.platform,Z){if(W!=="win32"||!eN(Z))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function nK($){if($.length===0)return;let[W,...Z]=$,Q=W.replace(/\\/g,"/").toLowerCase(),J=Q.split("/").at(-1)??Q;if(J==="env")return nK(Z);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Z];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Z]:[J,...Z];return $}function Ww($){let W=tN($);if(W&&W.length>0)return[...nK(W)??W,$];let Z=$.toLowerCase();if(Z.endsWith(".sh")||Z.endsWith(".bash")||Z.endsWith(".zsh"))return["bash",$];if(Z.endsWith(".js")||Z.endsWith(".mjs")||Z.endsWith(".cjs"))return rK(["node",$],{debugRole:"hook"});if(Z.endsWith(".ts")||Z.endsWith(".mts")||Z.endsWith(".cts"))return["bun","run",$];if(Z.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Z.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function Zw($){let W={};for(let Z of I$($)){if(!Z.hookEventName)continue;let Q=Z.hookEventName,J=W[Q]??[];J.push(Ww(Z.path)),W[Q]=J}return W}async function Qw($){let W;for(let Z of $.commands){let Q=Z.join(" ");try{let J=await iK($.payload,{command:Z,cwd:$.cwd,env:vJ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){RZ($.logger,`hook command timed out: ${Q}`);continue}if(J?.parseError){RZ($.logger,`hook command returned invalid JSON control output: ${Q} (${J.parseError})`);continue}W=nN(W,aN(J?.parsedJson))}catch(J){RZ($.logger,`hook command failed: ${Q}`,J)}}return W}function m2($){for(let W of $.commands){let Z=W.join(" ");iK($.payload,{command:W,cwd:$.cwd,env:vJ(process.env),detached:!0}).catch((Q)=>{RZ($.logger,`hook command failed: ${Z}`,Q)})}}function x$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function mJ($,W){return{...x$($.snapshot),userMessage:W}}function aK($){return{...x$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function oK($){return{...x$($.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 sK($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function Jw($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}function B6($){let W={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Z=(Q)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
483
+ `,X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??iN(lK(),"hooks.jsonl");lK(X),pN(X,J,"utf8")};return{beforeRun:async(Q)=>{let J=mJ(Q,"");Z({...C0(J,W),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let J=aK(Q);Z({...C0(J,W),hookName:"tool_call",iteration:J.iteration,tool_call:{id:J.call.id,name:J.call.name,input:J.call.input},preToolUse:{toolName:J.call.name,parameters:EZ(J.call.input)}});return},afterTool:async(Q)=>{let J=oK(Q);Z({...C0(J,W),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:EZ(J.record.input),result:typeof J.record.output==="string"?J.record.output:JSON.stringify(J.record.output),success:!J.record.error,executionTimeMs:J.record.durationMs}});return},afterRun:async({snapshot:Q,result:J})=>{let j=x$(Q);if(J.status==="completed"){Z({...C0(j,W),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||gJ(J.error?.message)){Z({...C0(j,W),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Z({...C0(j,W),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let J=mJ({snapshot:Q.snapshot},sK(Q.message.content));Z({...C0(J,W),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function z5($){let W=Zw($.workspacePath);if(!Object.values(W).some((G)=>G.length>0))return;let Q=async(G,K)=>{let F=W[K]??[];if(F.length===0)return;m2({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...C0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...C0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=W.prompt_submit??[];if(K.length>0)m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},j=async(G)=>{let K=W.tool_call??[];if(K.length===0)return;return Qw({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...C0(G,$),hookName:"tool_call",iteration:G.iteration,tool_call:{id:G.call.id,name:G.call.name,input:G.call.input},preToolUse:{toolName:G.call.name,parameters:EZ(G.call.input)}}})},X=async(G)=>{let K=W.tool_result??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:EZ(G.record.input),result:typeof G.record.output==="string"?G.record.output:JSON.stringify(G.record.output),success:!G.record.error,executionTimeMs:G.record.durationMs}}})},Y=async(G)=>{let K=W.agent_end??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=W.agent_error??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},B=async(G)=>{if(gJ(G.reason)){let F=W.agent_abort??[];if(F.length>0)m2({commands:F,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=W.session_shutdown??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"session_shutdown",reason:G.reason}})},H={};if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0||(W.prompt_submit?.length??0)>0){if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0)H.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(x$(G.snapshot),K);return};if((W.prompt_submit?.length??0)>0)H.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(mJ({snapshot:G.snapshot},sK(G.message.content)))}}if((W.tool_call?.length??0)>0)H.beforeTool=async(G)=>{let K=await j(aK(G));return Jw(K)};if((W.tool_result?.length??0)>0)H.afterTool=async(G)=>{await X(oK(G));return};if((W.agent_end?.length??0)>0)H.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await Y({...x$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((W.agent_error?.length??0)>0||(W.agent_abort?.length??0)>0||(W.session_shutdown?.length??0)>0){let G=H.afterRun;H.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||gJ(A.error?.message)){await B({...x$(F),reason:A.error?.message});return}if(A.error)await V({...x$(F),iteration:A.iterations,error:A.error})}}return H}function H6($){return Y6("core.hook_config_files",z5($))}function v2($,W){let Z=$.map((Q)=>Q[W]).filter((Q)=>typeof Q==="function");if(Z.length===0)return;return async(Q)=>{let J;for(let j of Z){let X=await j(Q);if(!X||typeof X!=="object")continue;let Y=X;J={...J??{},...Y,stop:J?.stop===!0||Y.stop===!0?!0:Y.stop,options:J?.options||Y.options?{...J?.options??{},...Y.options??{}}:void 0}}return J}}function c2($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return;return{beforeRun:v2(W,"beforeRun"),afterRun:v2(W,"afterRun"),beforeModel:v2(W,"beforeModel"),afterModel:v2(W,"afterModel"),beforeTool:v2(W,"beforeTool"),afterTool:v2(W,"afterTool"),onEvent:v2(W,"onEvent")}}var tK={};w(tK,{normalizeRuntimeCapabilities:()=>P0});function P0(...$){let W,Z;for(let J of $){if(!J)continue;if(J.toolExecutors)W={...W??{},...J.toolExecutors};if(J.requestToolApproval)Z=J.requestToolApproval}let Q=W&&Object.keys(W).length>0;if(!Q&&!Z)return;return{...Q?{toolExecutors:W}:{},...Z?{requestToolApproval:Z}:{}}}var YF={};w(YF,{toProviderConfig:()=>s0,emptyStoredProviderSettings:()=>v$,StoredProviderSettingsSchema:()=>A6,StoredProviderSettingsEntrySchema:()=>aZ,ProviderSettingsSchemaTyped:()=>F6});import{z as m$}from"zod";var XF={};w(XF,{toProviderConfig:()=>s0,safeParseSettings:()=>nZ,safeCreateProviderConfig:()=>oJ,parseSettings:()=>iZ,normalizeProviderId:()=>K6,isBuiltInProviderId:()=>nJ,createProviderConfig:()=>aJ,SapSettingsSchema:()=>lZ,ReasoningSettingsSchema:()=>vZ,ProviderSettingsSchema:()=>g$,ProviderProtocolSchema:()=>xZ,ProviderIdSchema:()=>N5,ProviderClientSchema:()=>gZ,OcaSettingsSchema:()=>pZ,ModelCatalogSettingsSchema:()=>rZ,GcpSettingsSchema:()=>uZ,BUILT_IN_PROVIDER_IDS:()=>iJ,BUILT_IN_PROVIDER:()=>E5,AzureSettingsSchema:()=>dZ,AwsSettingsSchema:()=>cZ,AuthSettingsSchema:()=>mZ});import*as o0 from"@cline/llms";import{z as N}from"zod";var jF={};w(jF,{resolveProviderConfig:()=>R5,getProviderConfig:()=>IZ,getLiveModelsCatalog:()=>G6,clearPublicModelsCatalogCache:()=>Nw,clearPrivateModelsCatalogCache:()=>rJ,clearLiveModelsCatalogCache:()=>pJ,OPENAI_COMPATIBLE_PROVIDERS:()=>M5,DEFAULT_MODELS_CATALOG_URL:()=>bZ});import*as $0 from"@cline/llms";function cJ($){if(!Array.isArray($))return[];return $.map((W)=>{if(typeof W==="string")return W.trim();if(W&&typeof W==="object"){let Z=W;for(let Q of[Z.id,Z.name,Z.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((W)=>W.length>0)}function jw($,W){let Z=cJ($);if(Z.length>0)return Z;if(!$||typeof $!=="object")return[];let Q=$,J=cJ(Q.data??Q.models);if(J.length>0)return J;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let X=Object.keys(Q.models).filter((Y)=>Y.trim().length>0);if(X.length>0)return X}let j=Q.providers?.[W];if(j&&typeof j==="object"){let Y=cJ(j.models??j);if(Y.length>0)return Y}return[]}async function NZ($,W){let Z=await fetch($,{method:"GET"});if(!Z.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Z.status}`);return jw(await Z.json(),W)}function eK($){return $.replace(/\/+$/,"")}function wZ($,W,Z){let Q=Z?.trim();if(!Q)return;let J=$?.trim();if(!J||!W?.trim())return Q;try{let j=new URL(Q),X=new URL(W),Y=new URL(J);if(j.origin!==X.origin)return Q;let V=eK(X.pathname),B=eK(Y.pathname);if(V&&j.pathname.startsWith(`${V}/`)){let H=j.pathname.slice(V.length);Y.pathname=`${B}${H}`}else Y.pathname=j.pathname;return Y.search=j.search,Y.hash=j.hash,Y.toString()}catch{return Q}}function Xw($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{...Z}]))}function Yw($){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 Vw=Object.values($0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:Xw($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),WF=Object.fromEntries(Vw.map(($)=>[$.id,$]));function Bw($){return WF[$]}function Hw(){return Object.fromEntries(Object.entries(WF).filter(([,$])=>Yw($)))}function ZF($=[]){let W=$.flatMap((Z)=>{switch(Z){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Z];default:return[]}});return W.length>0?W:void 0}var bZ="https://models.dev/api.json",Gw=600000,QF=300000,Kw=5000,SZ=new Map,q5=new Map,uJ=new Map,CZ=new Map;async function Fw(){return $0.getGeneratedProviderModels()}async function Aw($,W={},Z={},Q={},J={},j={}){if($==="litellm")return $0.sortModelsByReleaseDate(Q);let X=await Fw(),Y=$0.resolveProviderModelCatalogKeys($),V=Object.assign({},...Y.map((G)=>X[G]??{}));if(Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl))return $0.sortModelsByReleaseDate({...J,...j});if($==="openai-codex")return $0.sortModelsByReleaseDate({...W,...$0.filterOpenAICodexModels(Z),...J,...j});if($==="cline-pass"&&Object.keys(Z).length>0)return{...Z,...j};let H=$0.sortModelsByReleaseDate({...V,...W,...Z,...Q,...J});if($==="cline")return $0.sortModelsByReleaseDate({...$0.preferCanonicalModelIds(H,$0.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...j});return $0.sortModelsByReleaseDate({...H,...j})}function Uw($,W){let Z=$0.resolveProviderModelCatalogKeys($);return Object.assign({},...Z.map((Q)=>W[Q]??{}))}function yZ($){let W=$?.trim();return W&&W.length>0?W:""}function lJ($){let W=$.apiKey?.trim()||$.accessToken?.trim();return W&&W.length>0?W:void 0}function Dw($){let W=2166136261;for(let Z=0;Z<$.length;Z+=1)W^=$.charCodeAt(Z),W+=(W<<1)+(W<<4)+(W<<7)+(W<<8)+(W<<24);return(W>>>0).toString(16)}function _w($,W){return`${$}:${yZ(W.baseUrl)}:${Dw(lJ(W)??"")}`}async function hZ($,W,Z=Kw){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await fetch($,{...W,signal:Q.signal})}finally{clearTimeout(J)}}function u2($,W,Z){if(Z&&!$.includes(W))$.push(W)}function kZ($,W){let Z=["streaming","tools"];return u2(Z,"images",Boolean(W.supportsImages)),u2(Z,"prompt-cache",Boolean(W.supportsPromptCache)),u2(Z,"reasoning",Boolean(W.supportsReasoning)),{id:$,name:W.name??$,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxTokens:W.maxTokens,capabilities:Z,releaseDate:W.releaseDate,status:"active"}}async function fw($,W){let Z=await hZ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"}});if(!Z.ok)throw Error(`Baseten model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;if(Y.includes("whisper")||Y.includes("tts")||Y.includes("embedding"))continue;let V=X.supported_features??[];j[Y]=kZ(Y,{name:Y,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return j}function $F($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let W=Number($);return Number.isFinite(W)?W:void 0}return}async function Lw($,W){let Z=await hZ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":W}});if(!Z.ok)throw Error(`Hicap model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;j[Y]=kZ(Y,{name:Y,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function Tw($,W){let Q=`${(yZ($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await hZ(Q,{method:"GET",headers:{Authorization:`Bearer ${W}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let X=(await J.json())?.data??[],Y={};for(let V of X){let B=V.id?.trim();if(!B)continue;let H=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];u2(F,"tools",H.includes("tools")),u2(F,"reasoning",H.includes("reasoning")),u2(F,"temperature",G.includes("temperature")),u2(F,"images",K.includes("image"));let A={input:$F(V.pricing?.prompt),output:$F(V.pricing?.completion)};Y[B]={id:B,name:V.name??B,description:V.description,contextWindow:V.context_length,maxInputTokens:V.context_length,maxTokens:V.max_completion_tokens,capabilities:F,pricing:A.input!==void 0||A.output!==void 0?A:void 0,status:"active"}}return Y}function Ow($){let W=yZ($).replace(/\/+$/,"");if(!W)return"http://localhost:4000";return W.endsWith("/v1")?W.slice(0,-3):W}function zw($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function qw($){let W=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Z=500,Q=W?`: ${W.slice(0,500)}${W.length>500?"...":""}`:"";return`HTTP ${$.status}${Q}`}async function Mw($,W){let Z=Ow($.baseUrl),Q=[],J=[["x-litellm-api-key",{"x-litellm-api-key":W}],["Authorization",{Authorization:`Bearer ${W}`}]];for(let j of zw(Z))for(let[X,Y]of J)try{let V=await hZ(j,{method:"GET",headers:{accept:"application/json",...Y}});if(V.ok){let H=(await V.json())?.data??[],G={};for(let K of H){let F=K.model_name?.trim(),D=K.litellm_params?.model?.trim()||F;if(!D)continue;let U=K.model_info,f=kZ(D,{name:F??D,maxTokens:U?.max_output_tokens??U?.max_tokens,maxInputTokens:U?.max_input_tokens??U?.max_tokens,supportsImages:U?.supports_vision,supportsPromptCache:U?.supports_prompt_caching,supportsReasoning:U?.supports_reasoning});if(G[D]=f,F)G[F]={...f,id:F,name:F}}return G}Q.push(`${new URL(j).pathname} (${X}): ${await qw(V)}`)}catch(V){let B=V instanceof Error?V.message:String(V);Q.push(`${new URL(j).pathname} (${X}): ${B}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${Q.join("; ")}`)}var JF={baseten:fw,hicap:Lw,litellm:Mw,poolside:Tw},dJ=new Map,PZ=new Map;function Rw($,W){return`${$}:${yZ(W.baseUrl)}`}async function Ew($,W,Z){let Q=$0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=wZ(Z.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!J)return{};let j=W?.cacheTtlMs??QF,X=Rw($,Z),Y=Date.now(),V=dJ.get(X);if(V&&V.expiresAt>Y)return V.data;let B=PZ.get(X);if(B)return B;let H=NZ(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,kZ(F,{name:F})]));return dJ.set(X,{data:K,expiresAt:Y+j}),K}).finally(()=>{PZ.delete(X)});return PZ.set(X,H),H}function Nw(){dJ.clear(),PZ.clear()}async function ww($,W){let Z=lJ(W);if(!Z)return{};let Q=JF[$];if(!Q)return{};return Q(W,Z)}function Cw($,W,Z){if(!Z)return!1;if(!JF[$])return!1;if(W?.loadPrivateOnAuth===!1)return!1;return Boolean(lJ(Z))}async function Pw($,W,Z){let Q=W?.cacheTtlMs??QF,J=_w($,Z),j=Date.now(),X=uJ.get(J);if(X&&X.expiresAt>j)return X.data;let Y=CZ.get(J);if(Y)return Y;let V=ww($,Z).then((B)=>{return uJ.set(J,{data:B,expiresAt:j+Q}),B}).finally(()=>{CZ.delete(J)});return CZ.set(J,V),V}async function Sw($){return $0.fetchLiveProviderModels($,globalThis.fetch)}async function G6($={}){let W=$.url??bZ,Z=$.cacheTtlMs??Gw,Q=Date.now(),J=SZ.get(W);if(J&&J.expiresAt>Q)return J.data;let j=q5.get(W);if(j)return j;let X=Sw(W).then((Y)=>{return SZ.set(W,{data:Y,expiresAt:Q+Z}),Y}).finally(()=>{q5.delete(W)});return q5.set(W,X),X}function pJ($){if($){SZ.delete($),q5.delete($);return}SZ.clear(),q5.clear()}function rJ(){uJ.clear(),CZ.clear()}function bw($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{baseUrl:Z.baseUrl,modelId:Z.modelId,capabilities:ZF(Z.capabilities)}]))}var M5=bw(Hw());function IZ($){let W=Bw($);if(!W)return;return{baseUrl:W.baseUrl||void 0,modelId:W.modelId,knownModels:W.knownModels,capabilities:ZF(W.capabilities)}}async function R5($,W,Z){let Q=IZ($);if(!Q)return;try{let J=W?.loadLatestOnInit?await G6(W):void 0,j=J?Uw($,J):{},X=Z&&Cw($,W,Z)?await Pw($,W,Z):{},V=Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Z??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:Z,B=V?await Ew($,W,V).catch(()=>({})):{},H=await Aw($,Q.knownModels,j,X,B,Z?.knownModels);return{...Q,knownModels:H}}catch(J){if(W?.failOnError)throw J;if($==="litellm")return{...Q,knownModels:{}};return Q}}var E5=o0.BUILT_IN_PROVIDER,iJ=o0.BUILT_IN_PROVIDER_IDS,nJ=o0.isBuiltInProviderId,K6=o0.normalizeProviderId,N5=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),xZ=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),gZ=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),mZ=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional(),organizationId:N.string().optional(),organizationName:N.string().optional(),memberId:N.string().optional(),metadata:N.record(N.string(),N.unknown()).optional()}),yw=N.enum(["none","low","medium","high","xhigh"]),vZ=N.object({enabled:N.boolean().optional(),effort:yw.optional(),budgetTokens:N.number().int().positive().optional()}),cZ=N.object({accessKey:N.string().optional(),secretKey:N.string().optional(),sessionToken:N.string().optional(),region:N.string().optional(),profile:N.string().optional(),authentication:N.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:N.boolean().optional(),useCrossRegionInference:N.boolean().optional(),useGlobalInference:N.boolean().optional(),endpoint:N.string().url().optional(),customModelBaseId:N.string().optional()}),uZ=N.object({projectId:N.string().optional(),region:N.string().optional()}),dZ=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),lZ=N.object({clientId:N.string().optional(),clientSecret:N.string().optional(),tokenUrl:N.string().url().optional(),resourceGroup:N.string().optional(),deploymentId:N.string().optional(),useOrchestrationMode:N.boolean().optional(),api:N.enum(["orchestration","foundation-models"]).optional(),defaultSettings:N.record(N.string(),N.unknown()).optional()}),pZ=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),rZ=N.object({loadLatestOnInit:N.boolean().optional(),loadPrivateOnAuth:N.boolean().optional(),url:N.string().url().optional(),cacheTtlMs:N.number().int().positive().optional(),failOnError:N.boolean().optional()}),g$=N.object({provider:N5,apiKey:N.string().optional(),auth:mZ.optional(),model:N.string().optional(),protocol:xZ.optional(),client:gZ.optional(),routingProviderId:N5.optional(),maxTokens:N.number().int().positive().optional(),contextWindow:N.number().int().positive().optional(),baseUrl:N.string().url().optional(),headers:N.record(N.string(),N.string()).optional(),timeout:N.number().int().positive().optional(),reasoning:vZ.optional(),aws:cZ.optional(),gcp:uZ.optional(),azure:dZ.optional(),sap:lZ.optional(),oca:pZ.optional(),region:N.string().optional(),apiLine:N.enum(["china","international"]).optional(),capabilities:N.array(N.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:rZ.optional()});function iZ($){return g$.parse($)}function nZ($){return g$.safeParse($)}function hw($){return $.protocol==="openai-responses"||$.client==="openai"}function s0($,W={}){let Z=$.provider,Q=K6(Z),J=W.includeKnownModels!==!1,j=$.reasoning?.effort||"none",X=j==="none"?void 0:j,Y=M5[Q],V=Object.assign({},...o0.resolveProviderModelCatalogKeys(Q).map((D)=>o0.getGeneratedModelsForProvider(D))),B=Object.keys(V)[0],H=h8(Q,$),G=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?xW:gW:Y?.baseUrl),K=$.routingProviderId??(hw($)&&Q!==E5.OPENAI_NATIVE?E5.OPENAI_NATIVE:void 0),F=J?Y?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Z,clientType:$.client,routingProviderId:K,modelId:$.model??Y?.modelId??B??"default",...J?{knownModels:F}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:X,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??Y?.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(A).filter(([D,U])=>U!==void 0))}function aJ($){let W=iZ($);return s0(W)}function oJ($){let W=nZ($);if(W.success)return{success:!0,config:s0(W.data)};return{success:!1,error:W.error}}var F6=g$;var aZ=m$.object({settings:g$,updatedAt:m$.string().datetime(),tokenSource:m$.enum(["manual","oauth","migration"]).default("manual")}),A6=m$.object({version:m$.literal(1),lastUsedProvider:m$.string().min(1).optional(),providers:m$.record(m$.string(),aZ)});function v$(){return{version:1,providers:{}}}X1();var VF={};w(VF,{InMemoryWorkspaceManager:()=>U6});import{upsertWorkspaceInfo as kw,WorkspaceManifestSchema as sJ}from"@cline/shared";class U6{manifest;listeners=new Set;constructor($){this.manifest=sJ.parse($??{workspaces:{}})}async addWorkspacePath($){let W=await _8($);return this.manifest=kw(this.manifest,W),this.emit({type:"workspace_added",workspace:W}),W}async switchWorkspace($){let W=_1($),Z=this.manifest.workspaces[W];if(Z)return this.manifest=sJ.parse({...this.manifest,currentWorkspacePath:W}),this.emit({type:"workspace_switched",workspace:Z}),Z;let Q=await this.addWorkspacePath(W);return this.manifest=sJ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let W=_1($);return this.manifest.workspaces[W]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let W of this.listeners)W($)}}R0();import{createHash as Iw}from"node:crypto";var BF=new Set,HF=new Set;function xw($){return Iw("sha256").update($).digest("hex")}function gw($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function GF($){if(!$.telemetry)return;let W=xw($.rootPath),Z=$.rootCount??1;if(!BF.has(W))BF.add(W),s9($.telemetry,{root_count:Z,vcs_types:gw($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!HF.has(W)){HF.add(W);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",t9($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:Z})}}function cw($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function uw($,W,Z){if(W.length>0)for(let j of W)Z?.log(j.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(cw).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Z?.log(`Some plugins failed to initialize. ${Q}${J}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Z?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function dw($,W){let Z=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!Z&&!Q)return W;return{...W??{},...Z?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function KF($,W){return vw($,W)}function lw($){let W=0;for(let Z of $??[]){if(Z.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0)?.kind==="recovery_notice")continue;W+=1}return W}function pw($,W,Z,Q,J,j){let X=Q.getProviderSettings($.providerId),Y=J||X?.modelCatalog?{...J??{},...X?.modelCatalog??{}}:void 0,V=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,B=mw({providerId:$.providerId,sessionId:W,source:Z,defaultSource:F0.CLI,client:{name:$.extensionContext?.client?.name,version:$.extensionContext?.client?.version,versionHeaderFallback:$.headers?.["X-CLIENT-VERSION"],platform:$.extensionContext?.client?.platform,platformVersion:$.extensionContext?.client?.platformVersion,isMultiRoot:$.extensionContext?.client?.isMultiRoot},coreVersion:R8,openAiCodex:{accountId:V?.accountId??X?.auth?.accountId,accessToken:V?.accessToken??$.apiKey??X?.auth?.accessToken??X?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:X?.headers,config:$.headers,session:V?.headers}}),H={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:void 0,reasoning:dw($,X?.reasoning),modelCatalog:Y},G={...s0(H),...V??{}};if(B)G.headers=B;if($.knownModels)G.knownModels=$.knownModels;if($.extensionContext)G.extensionContext=$.extensionContext;let F=$.fetch??G.fetch??j;if(F)G.fetch=F;return G}async function FF($){let{input:W,sessionId:Z,providerSettingsManager:Q,defaultTelemetry:J,defaultCapabilities:j,defaultToolPolicies:X,defaultFetch:Y,onPluginEvent:V,onTeamEvent:B,createSubAgentLifecycleCallbacks:H,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,D=Z$(W.config),{modelCatalogDefaults:U,userInstructionService:f,configExtensions:_,onTeamRestored:R,...O}=K??{},T=Object.keys(O).length>0?O:void 0,{workspaceInfo:L,workspaceMetadata:C,gitState:E,durationMs:p,vcsType:x,initError:P}=await b7(D),r=T?.extensionContext,d={...r??{},workspace:{...L,...r?.workspace??{}},session:{...r?.session??{},sessionId:Z},logger:r?.logger??T?.logger,telemetry:r?.telemetry??T?.telemetry??J};GF({telemetry:d.telemetry,rootPath:L.rootPath,workspaceInfo:L,rootCount:1,vcsType:x,durationMs:p,initError:P,featureFlagEnabled:!0});let I1=H6({cwd:W.config.cwd,workspacePath:D,rootSessionId:Z,logger:T?.logger,workspaceInfo:L}),$2=GK(T?.hooks)?void 0:B6({rootSessionId:Z,workspacePath:D,workspaceInfo:L}),A$=c2([T?.hooks,$2]),I0;if(KF(_,"plugins"))try{I0=await X6({pluginPaths:T?.pluginPaths,workspacePath:D,cwd:W.config.cwd,onEvent:V,providerId:W.config.providerId,modelId:W.config.modelId,workspaceInfo:L,session:d.session,client:d.client,user:d.user,logger:d.logger,telemetry:d.telemetry,automation:d.automation}),uw(I0.failures,I0.warnings,T?.logger)}catch(t6){let F8=t6 instanceof Error?t6.message:String(t6);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${F8})`)}let D1=UJ(I1?[I1]:void 0,UJ(T?.extensions,_W(I0?.extensions))),K8=KF(_,"plugins")?J$(I0?.pluginPaths??[]):void 0,V0={...W.config,...T??{},sessionId:Z,hooks:A$,extensions:D1,extensionContext:d,telemetry:d.telemetry},d0=pw(V0,Z,W.source,Q,U,Y),J1=c2([V0.hooks,V0.checkpoint?.enabled===!0?dK({cwd:V0.cwd,sessionId:Z,logger:V0.logger,createCheckpoint:V0.checkpoint?.createCheckpoint,initialRunCount:lw(W.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),y={...V0,providerConfig:d0,workspaceMetadata:C,hooks:J1},j1=W.toolPolicies??V0.toolPolicies??X,k=P0(j,W.capabilities),W0=k?.requestToolApproval,T0=k?.toolExecutors,q0=H?.(y),d9=new U6({currentWorkspacePath:L.rootPath,workspaces:{[L.rootPath]:L}});return{effectiveInput:W,config:y,providerConfig:d0,workspaceMetadata:C,workspaceInfo:L,gitState:E,extensions:D1,hooks:J1,toolPolicies:j1,requestToolApproval:W0,pluginSandboxShutdown:I0?.shutdown,runtimeBuilderInput:{config:y,hooks:J1,extensions:D1,onTeamEvent:B,createSpawnTool:G,onTeamRestored:R,onSubAgentEvent:q0?.onSubAgentEvent,onSubAgentStart:q0?.onSubAgentStart,onSubAgentEnd:q0?.onSubAgentEnd,userInstructionService:f,pluginSkillDirectories:K8,configExtensions:_,toolExecutors:T0,toolPolicies:j1,workspaceManager:d9,logger:y.logger,telemetry:y.telemetry,requestToolApproval:W0}}}import{existsSync as oZ,mkdirSync as rw,readdirSync as iw,rmdirSync as nw,rmSync as aw,unlinkSync as ow}from"node:fs";import{dirname as AF,join as w5}from"node:path";function X0(){return new Date().toISOString()}function C5($){if(!$||!oZ($))return;try{ow($)}catch{}}function sw($){let W=t8($);if(W)return{rootSessionId:W.rootSessionId,fileStem:`${W.agentId}__${W.teamTaskId}`};let Z=Y5($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:Z.agentId};return{rootSessionId:$,fileStem:$}}class tJ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return w5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let W=this.sessionArtifactsDir($);if(!oZ(W))rw(W,{recursive:!0});return W}sessionMessagesPath($){return w5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionCompactionPath($){return w5(this.sessionArtifactsDir($),`${$}.compaction.json`)}sessionManifestPath($,W=!1){let Z=W?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return w5(Z,`${$}.json`)}removeSessionDirIfEmpty($){let W=this.sessionArtifactsDir($),Z=this.ensureSessionsDir();while(W.startsWith(Z)&&W!==Z){if(!oZ(W)){W=AF(W);continue}try{if(iw(W).length>0)break;nw(W)}catch{break}W=AF(W)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!oZ($))return;try{aw($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,W,Z){let{rootSessionId:Q,fileStem:J}=sw($),j=this.sessionArtifactsDir(Q);return{messagesPath:w5(j,`${J}.messages.json`)}}}import{resolveDocumentsExtensionPath as tw}from"@cline/shared/storage";R0();function UF($,W,Z,Q,J){if(Z)$W($.telemetry,{ulid:W,apiProvider:$.providerId,...J});else e9($.telemetry,{ulid:W,apiProvider:$.providerId,...J});ew($.telemetry,{workspacePath:Q})}function ew($,W){let Z=tw("Hooks"),Q=I$(W.workspacePath),J=new Map;for(let j of Q){let X=j.hookEventName??"unknown",Y=J.get(X)??{global:0,workspace:0};if(j.path===Z||j.path.startsWith(`${Z}/`))Y.global+=1;else Y.workspace+=1;J.set(X,Y)}for(let[j,X]of J.entries())BW($,j,X.global,X.workspace)}function DF($,W){for(let Z of W.mentions)YW($,Z,W.matchedFiles.includes(Z)?1:0,"file",!W.matchedFiles.includes(Z));for(let Z of W.matchedFiles)jW($,"file",Z.length);for(let Z of W.ignoredMentions)XW($,"file","not_found",Z)}var U_={};w(U_,{ProviderSettingsManager:()=>k1});import{chmodSync as O_,existsSync as UY,mkdirSync as hg,readFileSync as kg,renameSync as Ig,rmSync as xg,writeFileSync as gg}from"node:fs";import{basename as z_,dirname as DY}from"node:path";import{resolveProviderSettingsPath as mg}from"@cline/shared/storage";var q={};w(q,{writeModelsFileSync:()=>w9,writeHubDiscovery:()=>OW,writeGlobalSettings:()=>f1,withHubStartupLock:()=>zW,verifyHubConnection:()=>z1,updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,updateLocalProvider:()=>Y7,uninstallPlugin:()=>T9,uninstallMarketplaceSkill:()=>rQ,uninstallMarketplacePlugin:()=>iQ,uninstallMarketplaceMcpServerFromSettings:()=>lQ,uninstallMarketplaceEntry:()=>NX,truncateNotificationBody:()=>k9,truncateCommandOutput:()=>L2,toggleDisabledTool:()=>UW,toTeamProgressLifecycleEvent:()=>S6,toProviderConfig:()=>s0,toHubStatusUrl:()=>s7,toHubHealthUrl:()=>qW,toHookConfigFileName:()=>O5,syncStoredProviderRegistration:()=>vX,syncPluginMcpServersToSettings:()=>f9,summarizeUsageFromMessages:()=>$6,stopLocalHubServerGracefully:()=>B3,startLocalOAuthServer:()=>H1,startHubWebSocketServer:()=>g9,startHubServer:()=>f_,startClineDeviceAuth:()=>O3,splitCoreSessionConfig:()=>D4,spawnDetachedHubServerWithRetry:()=>N8,spawnDetachedHubServer:()=>Q3,setTelemetryOptOutGlobally:()=>CV,setSdkLogger:()=>U3,setMcpServerDisabled:()=>p2,setDisabledTools:()=>l7,setDisabledPlugin:()=>xV,setCompactionStrategyGlobally:()=>yV,setAutoUpdateEnabledGlobally:()=>SV,sendHubCommand:()=>AB,sdkDebug:()=>s,saveProviderOAuthCredentials:()=>F2,saveLocalProviderSettings:()=>iX,saveLocalProviderOAuthCredentials:()=>sX,sanitizeSessionToken:()=>h2,safeParseSettings:()=>nZ,safeCreateProviderConfig:()=>oJ,runSubprocessEvent:()=>g6,runHook:()=>v6,reviveTeamStateDates:()=>GZ,restartLocalHubIfIdleAfterStartupTimeout:()=>wW,resolveWorkspaceHubOwnerContext:()=>sV,resolveWorkflowsConfigSearchPaths:()=>v5,resolveSkillsConfigSearchPaths:()=>g5,resolveSharedHubOwnerContext:()=>V1,resolveSessionBackend:()=>oj,resolveRulesConfigSearchPaths:()=>m5,resolveProviderConfig:()=>R5,resolveProviderApiKeyFromSettings:()=>w3,resolveProductionHubOwnerContext:()=>O1,resolvePluginSkillDirectoriesFromPaths:()=>J$,resolvePluginConfigSearchPaths:()=>_5,resolveModelsRegistryPath:()=>h1,resolveMcpServerRegistrations:()=>t0,resolveMarketplaceMcpServerName:()=>z9,resolveLocalClineAuthToken:()=>eX,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>r1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>TW,resolveHooksConfigSearchPaths:()=>L5,resolveDisabledToolNames:()=>L1,resolveDisabledPluginPaths:()=>G4,resolveDefaultMcpSettingsPath:()=>J0,resolveDefaultHubPort:()=>E8,resolveDefaultHubPathname:()=>Z3,resolveDefaultHubHost:()=>W3,resolveCoreSelectedToolIds:()=>FZ,resolveCoreDistinctId:()=>x0,resolveCompatibleLocalHubUrl:()=>T4,resolveClineDir:()=>iV,resolveClineDataDir:()=>Y2,resolveAndLoadAgentPlugins:()=>X6,resolveAgentPluginPaths:()=>Q$,requestHubShutdown:()=>L4,requestDesktopToolApproval:()=>GX,removePluginMcpServersFromSettings:()=>L9,rememberRecoverableLocalHubUrl:()=>O$,registerRemoteConfigSessionBlobUpload:()=>kQ,registerMcpServersFromSettingsFile:()=>n2,registerDisposable:()=>Pg,refreshProviderModelsFromSource:()=>nX,refreshOpenAICodexToken:()=>IW,refreshOcaToken:()=>vW,refreshClineToken:()=>hW,readSessionCheckpointHistory:()=>Z8,readRemoteConfigSessionBlobUploadMetadata:()=>ZX,readModelsFileSync:()=>n6,readHubDiscovery:()=>D0,readGlobalSettings:()=>E0,readCompactionStrategyGlobally:()=>bV,readBearerToken:()=>f7,projectSessionCompactionState:()=>A2,probeHubServer:()=>i1,probeHubConnection:()=>FB,prewarmFileIndex:()=>WZ,prewarmDetachedHubServer:()=>RW,prepareRemoteConfigCoreIntegration:()=>JX,parseWorkflowConfigFromMarkdown:()=>x5,parseUserCommandEnvelope:()=>Cg,parseSkillConfigFromMarkdown:()=>k5,parseSettings:()=>iZ,parseSessionCompactionState:()=>G1,parseRuleConfigFromMarkdown:()=>I5,parsePluginSource:()=>Z7,parseMcpInstallArgs:()=>_9,parseHookEventPayload:()=>m6,parseConfiguredAgentConfig:()=>Y9,normalizeWorkspacePath:()=>_1,normalizeUserInput:()=>wg,normalizeSdkError:()=>Ng,normalizeRuntimeCapabilities:()=>P0,normalizeProviderId:()=>K6,normalizeOAuthProvider:()=>aX,normalizeHubWebSocketUrl:()=>z$,noopBasicLogger:()=>Eg,migrateLegacyProviderSettings:()=>y9,mergeRulesForSystemPrompt:()=>D8,mergeAgentHooks:()=>c2,marketplaceEntryKey:()=>EX,markLocalProviderEnabled:()=>lX,makeTeamTaskSubSessionId:()=>X5,makeSubSessionId:()=>s8,loginOpenAICodex:()=>q4,loginOcaOAuth:()=>N4,loginLocalProvider:()=>oX,loginClineOAuth:()=>O4,loginAndSaveProviderOAuthCredentials:()=>C4,loginAndSaveLocalProviderOAuthCredentials:()=>tX,loadOpenTelemetryAdapter:()=>ex,loadMcpSettingsFile:()=>l2,loadLlmsConfigFromFile:()=>GY,loadConfiguredAgentConfigs:()=>w6,loadAgentPluginsFromPathsWithDiagnostics:()=>x2,loadAgentPluginsFromPaths:()=>fZ,loadAgentPluginFromPath:()=>U5,listSessionHistoryFromBackend:()=>Cj,listPluginToolsWithDiagnostics:()=>DQ,listPluginTools:()=>o5,listMcpServerOAuthStatuses:()=>n5,listLocalProviders:()=>pX,listHookConfigFiles:()=>I$,isToolDisabledGlobally:()=>hV,isTelemetryOptedOutGlobally:()=>AW,isSessionNotFoundError:()=>p1,isRuleEnabled:()=>l9,isPluginDisabledGlobally:()=>IV,isOfficialPluginSlug:()=>W7,isOAuthProvider:()=>K2,isMarketplaceSkillInstalled:()=>pQ,isLocalHubOrigin:()=>AY,isLocalHubHostName:()=>L7,isHubReconnectableTransportError:()=>Y3,isHubCommandTimeoutError:()=>NW,isDiscoveryFilePresent:()=>aV,isClinePassLimitMessage:()=>Fg,isClinePassLimitError:()=>Kg,isClineOrgIndividualInferenceSubscriptionMessage:()=>Gg,isClineOrgIndividualInferenceSubscriptionError:()=>Hg,isClineNotSubscribedMessage:()=>Bg,isClineNotSubscribedError:()=>Vg,isClineAccountActionRequest:()=>sZ,isBuiltInProviderId:()=>nJ,isAutoUpdateEnabledGlobally:()=>PV,installPlugin:()=>yX,installMcpServer:()=>KX,identifyAccount:()=>c1,hashSecret:()=>N0,hasMcpSettingsFile:()=>X$,getValidOpenAICodexCredentials:()=>M4,getValidOcaCredentials:()=>w4,getValidClineCredentials:()=>z4,getProviderOAuthCredentialsFromSettings:()=>P4,getProviderConfigFields:()=>$Y,getProviderConfig:()=>IZ,getProviderAuthStorageId:()=>N3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>h8,getMcpServerOAuthState:()=>r2,getMarketplaceSkillCandidates:()=>q9,getLocalProviderModels:()=>rX,getLiveModelsCatalog:()=>G6,getGlobalMarketplaceSkillPaths:()=>M9,getFileIndex:()=>t1,getCurrentContextSize:()=>LJ,getCoreHeadlessToolNames:()=>j5,getCoreDefaultEnabledToolIds:()=>KZ,getCoreBuiltinToolCatalog:()=>b2,getCoreAcpToolNames:()=>AZ,getClinePassSubscriptionUrl:()=>Yg,getClineOrgIndividualInferenceSubscriptionMessage:()=>Xg,getClineNotSubscribedMessage:()=>jg,getClineDefaultSystemPrompt:()=>Ag,generateWorkspaceInfoWithDiagnostics:()=>$4,generateWorkspaceInfo:()=>_8,formatRulesForSystemPrompt:()=>U8,formatProviderOAuthApiKey:()=>C3,formatDisplayUserInput:()=>Rg,findInstalledGlobalMarketplaceSkillName:()=>R9,findCheckpointForRun:()=>I6,filterExtensionToolRegistrations:()=>_W,filterDisabledTools:()=>u1,filterDisabledPluginPaths:()=>DW,fetchClineRecommendedModels:()=>BY,extractClinePassLimitMessage:()=>Jg,executeClineAccountAction:()=>tZ,ensureHubWebSocketServer:()=>T7,ensureHubServer:()=>L_,ensureDetachedHubServer:()=>QB,ensureCustomProvidersLoadedSync:()=>S9,ensureCustomProvidersLoaded:()=>b9,ensureCompatibleLocalHubUrl:()=>H2,enrichPromptWithMentions:()=>d8,emptyWorkspaceManifest:()=>zg,emptyStoredProviderSettings:()=>v$,discoverPluginModulePaths:()=>f5,disablePluginMcpServersInSettings:()=>DX,deriveSubsessionStatus:()=>V5,deleteLocalProvider:()=>V7,defineLlmsConfig:()=>HY,createWorkflowsConfigDefinition:()=>d5,createUserInstructionConfigService:()=>c$,createToolPoliciesWithPreset:()=>QZ,createTool:()=>Og,createTeamName:()=>gQ,createSubprocessHooks:()=>SQ,createSpawnAgentTool:()=>y$,createSkillsConfigDefinition:()=>c5,createShellTool:()=>o4,createShellExecutor:()=>T2,createSessionHost:()=>h6,createSessionCompactionState:()=>k8,createRuntimeHost:()=>h6,createRulesConfigDefinition:()=>u5,createRemoteConfigSessionMessagesArtifactUploader:()=>QX,createProviderConfig:()=>aJ,createOpenTelemetryTelemetryService:()=>U4,createOAuthClientCallbacks:()=>D6,createMcpTools:()=>M6,createLocalHubScheduleRuntimeHandlers:()=>__,createLlmsSdk:()=>FY,createInitialAccumulatedUsage:()=>z0,createInMemoryHubOwnerContext:()=>nV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>LW,createHookConfigFileHooks:()=>z5,createHookConfigFileExtension:()=>H6,createHookAuditHooks:()=>B6,createEditorExecutor:()=>M2,createDisabledMcpToolPolicy:()=>a5,createDisabledMcpToolPolicies:()=>UQ,createDelegatedAgentConfigProvider:()=>S$,createDelegatedAgent:()=>b$,createDefaultToolsWithPreset:()=>JZ,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>$5,createDefaultMcpServerClientFactory:()=>z6,createDefaultExecutors:()=>l8,createCoreSettingsService:()=>o2,createCoreSessionSnapshot:()=>N1,createContributionRegistry:()=>Tg,createContextCompactionPrepareTurn:()=>m4,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,createConfiguredAgentTools:()=>C6,createCompactionStateAwarePrepareTurn:()=>v4,createClineTelemetryServiceMetadata:()=>Lg,createClineTelemetryServiceConfig:()=>fg,createCheckpointComparePlan:()=>NQ,createBuiltinTools:()=>y2,createApplyPatchExecutor:()=>q2,createAgentTeamsTools:()=>S2,createAgentRuntime:()=>yg,createAgentHooksExtension:()=>Y6,connectToHub:()=>CW,computePatchChanges:()=>c8,completeClineDeviceAuth:()=>z3,compareCheckpointToWorkspace:()=>A9,collectPluginMcpOAuthCandidates:()=>Q7,clearPrivateModelsCatalogCache:()=>rJ,clearLiveModelsCatalogCache:()=>pJ,clearHubDiscovery:()=>g0,captureWorkspacePathResolved:()=>zV,captureWorkspaceInitialized:()=>s9,captureWorkspaceInitError:()=>t9,captureToolUsage:()=>T8,captureTokenUsage:()=>WW,captureTaskRestarted:()=>$W,captureTaskCreated:()=>e9,captureTaskCompleted:()=>Y4,captureSubagentExecution:()=>B4,captureSkillUsed:()=>QW,captureSdkError:()=>_g,captureProviderConfigured:()=>qV,captureProviderApiError:()=>V4,captureModeSwitch:()=>ZW,captureMentionUsed:()=>jW,captureMentionSearchResults:()=>YW,captureMentionFailed:()=>XW,captureHookDiscovery:()=>BW,captureExtensionActivated:()=>OV,captureDiffEditFailure:()=>JW,captureConversationTurnEvent:()=>L8,captureCompactionSkipped:()=>GW,captureCompactionExecuted:()=>HW,captureAuthSucceeded:()=>m1,captureAuthStarted:()=>g1,captureAuthLoggedOut:()=>L$,captureAuthFailed:()=>v1,captureAgentUnexpectedReasoningTokens:()=>TV,captureAgentTeamCreated:()=>VW,captureAgentCreated:()=>T$,buildWorkspaceMetadata:()=>W4,buildTeamProgressSummary:()=>P6,buildSdkErrorProperties:()=>Ug,buildRemoteConfigSessionBlobUploadMetadata:()=>yQ,buildMcpInstallTransport:()=>mQ,buildDelegatedAgentConfig:()=>C2,buildConnectionUpdate:()=>jJ,buildConfiguredAgentToolName:()=>V9,buildConfiguredAgentToolDescriptors:()=>B9,buildCheckpointWorkspaceDiff:()=>wQ,bootstrapAgentTeams:()=>o8,authorizeMcpServerOAuth:()=>GQ,addLocalProvider:()=>dX,accumulateUsageTotals:()=>L0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>h5,UnifiedConfigFileWatcher:()=>d2,ToolPresets:()=>a0,TelemetryService:()=>z8,TelemetryLoggerSink:()=>A4,TEAM_TOOL_NAMES:()=>a8,SubprocessSandbox:()=>Q6,StructuredCommandInputSchema:()=>_2,StoredProviderSettingsSchema:()=>A6,StoredProviderSettingsEntrySchema:()=>aZ,SqliteTeamStore:()=>j8,SqliteSessionStore:()=>C1,SessionVersioningService:()=>o$,SessionVersioningError:()=>c0,SessionSource:()=>F0,SessionNotFoundError:()=>l1,SapSettingsSchema:()=>lZ,SKILLS_CONFIG_DIRECTORY_NAME:()=>y5,SESSION_STATUSES:()=>B5,SESSION_NOT_FOUND_ERROR_CODE:()=>X2,SDK_ERROR_TELEMETRY_EVENT:()=>Sg,RpcClineAccountService:()=>S5,RemoteRuntimeHost:()=>N6,ReasoningSettingsSchema:()=>vZ,RULES_CONFIG_DIRECTORY_NAME:()=>jQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>hQ,ProviderSettingsSchema:()=>g$,ProviderSettingsManager:()=>k1,ProviderProtocolSchema:()=>xZ,ProviderIdSchema:()=>N5,ProviderClientSchema:()=>gZ,PatchActionType:()=>z2,OpenTelemetryProvider:()=>q8,OcaSettingsSchema:()=>pZ,OPENAI_COMPATIBLE_PROVIDERS:()=>M5,NodeHubClient:()=>B1,NoOpFeatureFlagsProvider:()=>W8,NativeHubTransportAdapter:()=>x9,ModelCatalogSettingsSchema:()=>rZ,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$,MAX_COMMAND_OUTPUT_CHARS:()=>a1,LocalRuntimeHost:()=>b1,Llms:()=>$g,InMemoryWorkspaceManager:()=>U6,InMemoryMcpManager:()=>a2,HubUIClient:()=>F3,HubTransportError:()=>y0,HubSessionClient:()=>K3,HubServerTransport:()=>o6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>A8,HubRuntimeHost:()=>Y$,HubCommandError:()=>w8,HookEventPayloadSchema:()=>PQ,HookEventNameSchema:()=>CQ,HookConfigFileName:()=>V6,HOOK_CONFIG_FILE_EVENT_MAP:()=>T5,HOOKS_CONFIG_DIRECTORY_NAME:()=>MZ,GlobalSettingsSchema:()=>H4,GcpSettingsSchema:()=>uZ,FileTeamPersistenceStore:()=>G7,FeatureFlagsService:()=>$8,FeatureFlagDefaultValue:()=>Mg,FEATURE_FLAGS:()=>qg,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>_7,DefaultToolNames:()=>O0,DefaultRuntimeBuilder:()=>d6,DefaultLlmsSdk:()=>h9,DEFAULT_MODELS_CATALOG_URL:()=>bZ,DEFAULT_HUB_PORT:()=>e7,DEFAULT_HUB_PATHNAME:()=>$3,DEFAULT_HUB_HOST:()=>t7,CoreSettingsService:()=>l$,CoreSessionService:()=>S1,ContributionRegistry:()=>Dg,CommandExitError:()=>o1,ClinePassLimitError:()=>Qg,ClineOrgIndividualInferenceSubscriptionError:()=>Zg,ClineNotSubscribedError:()=>Wg,ClineCore:()=>U9,ClineAccountService:()=>P5,ChatViewStateSchema:()=>XY,ChatSummarySchema:()=>D7,ChatSessionStatusSchema:()=>F7,ChatSessionConfigSchema:()=>K7,ChatMessageSchema:()=>U7,ChatMessageRoleSchema:()=>A7,CORE_TELEMETRY_EVENTS:()=>v,CORE_BUILD_VERSION:()=>YY,BrowserWebSocketHubAdapter:()=>I9,BUILT_IN_PROVIDER_IDS:()=>iJ,BUILT_IN_PROVIDER:()=>E5,AzureSettingsSchema:()=>dZ,AwsSettingsSchema:()=>cZ,AuthSettingsSchema:()=>mZ,AgentTeamsRuntime:()=>e2,AgentTeam:()=>y6,Agent:()=>bg,ALL_DEFAULT_TOOL_NAMES:()=>D$});M(q,f00);import*as $g from"@cline/llms";import{ClineNotSubscribedError as Wg,ClineOrgIndividualInferenceSubscriptionError as Zg,ClinePassLimitError as Qg,extractClinePassLimitMessage as Jg,getClineNotSubscribedMessage as jg,getClineOrgIndividualInferenceSubscriptionMessage as Xg,getClinePassSubscriptionUrl as Yg,isClineNotSubscribedError as Vg,isClineNotSubscribedMessage as Bg,isClineOrgIndividualInferenceSubscriptionError as Hg,isClineOrgIndividualInferenceSubscriptionMessage as Gg,isClinePassLimitError as Kg,isClinePassLimitMessage as Fg}from"@cline/llms";import{buildClineSystemPrompt as Ag,buildSdkErrorProperties as Ug,ContributionRegistry as Dg,captureSdkError as _g,createClineTelemetryServiceConfig as fg,createClineTelemetryServiceMetadata as Lg,createContributionRegistry as Tg,createTool as Og,emptyWorkspaceManifest as zg,FEATURE_FLAGS as qg,FeatureFlagDefaultValue as Mg,formatDisplayUserInput as Rg,noopBasicLogger as Eg,normalizeSdkError as Ng,normalizeUserInput as wg,parseUserCommandEnvelope as Cg,registerDisposable as Pg,SDK_ERROR_TELEMETRY_EVENT as Sg}from"@cline/shared";import"@cline/shared/storage";var fF={};w(fF,{isClineAccountActionRequest:()=>sZ,executeClineAccountAction:()=>tZ,RpcClineAccountService:()=>S5,ClineAccountService:()=>P5});function $C($){if(typeof $!=="object"||$===null||!("error"in $))return;let W=$.error;return typeof W==="string"&&W.trim()?W:void 0}function _F($,W,Z){let Q=$C(Z);if(Q)return Q;let J=W.trim();if(J){let j=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class P5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let W=$.apiBaseUrl.trim();if(!W)throw Error("apiBaseUrl is required");this.apiBaseUrl=W,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 W=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(W)}/balance`)}async fetchUsageTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/usages`)).items??[]}async fetchPaymentTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let W=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)W.searchParams.set("type",$.type);return this.request(`${W.pathname}${W.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}`)}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}/balance`)}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");let Z=await this.resolveOrganizationMemberId(W,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(W)}/members/${encodeURIComponent(Z)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let W=$?.trim();if(W)return W;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,W){let Z=W?.trim();if(Z)return Z;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let X=(await this.fetchUserOrganizations()).find((Y)=>Y.organizationId===$)?.memberId;if(!X?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return X}async request($,W){let Z=(await this.getAuthTokenFn())?.trim();if(!Z)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,j=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let X=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:W?.method??"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json",...Q??{}},body:W?.body!==void 0?JSON.stringify(W.body):void 0,signal:J.signal});if(X.status===204||W?.expectNoContent){if(!X.ok)throw Error(`Cline account request failed with status ${X.status}`);return}let Y=await X.text(),V;if(Y.trim())try{V=JSON.parse(Y)}catch{if(!X.ok)throw Error(_F(X.status,Y,void 0));throw Error("Cline account response was not valid JSON")}if(!X.ok)throw Error(_F(X.status,Y,V));if(typeof V==="object"&&V!==null){let B=V;if(typeof B.success==="boolean"){if(!B.success)throw Error(B.error||"Cline account request failed");return B.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(j)}}}function sZ($){return $.action==="clineAccount"}async function tZ($,W){switch($.operation){case"fetchMe":return W.fetchMe();case"fetchBalance":return W.fetchBalance($.userId);case"fetchUsageTransactions":return W.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return W.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return W.fetchUserOrganizations();case"fetchOrganizationBalance":return W.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return W.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await W.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return W.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class S5{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 W=$.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:W})}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:W,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var LF={};w(LF,{createOAuthClientCallbacks:()=>D6});function D6($){return{onAuth:({url:W,instructions:Z})=>{if($.onOutput?.(Z??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(W)).catch((Q)=>{$.onOpenUrlError?.({url:W,error:Q})})}catch(Q){$.onOpenUrlError?.({url:W,error:Q})}$.onOutput?.(W)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var dU={};w(dU,{ClineCore:()=>U9});function TF($){if($===!0)return{};if(!$)return;return $}function OF($){if($==="user")return"global";return $}class eJ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let W=this.getService().ingestEvent($);return{event:W.event,duplicate:W.duplicate,matchedSpecIds:W.matchedSpecs.map((Z)=>Z.specId),queuedRuns:W.queuedRuns,suppressions:W.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function zF($){let{host:W}=$;return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:K6(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:QC(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content),delivery:Q.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:ZC(J)}},async abortSession(Z){return await W.abort(Z,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}function eZ($){let W=WC($.automationService,$.automation),Z=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!W&&!Z&&!Q&&!J&&!j)return $.context;return{...$.context??{},...Z?{client:Z}:{},...Q?{user:Q}:{},...J?{logger:J}:{},...j?{telemetry:j}:{},...W?{automation:W}:{}}}function WC($,W){if(!$)return;return{ingestEvent:(Z)=>{W.ingestEvent(Z)}}}function ZC($){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((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function QC($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var MA={};w(MA,{createCoreSettingsService:()=>o2,CoreSettingsService:()=>l$});import{existsSync as t5,readFileSync as uP}from"node:fs";import{basename as Uj,dirname as _A,extname as dP,isAbsolute as TA,join as lP,relative as OA,resolve as fA}from"node:path";var kF={};w(kF,{resolveWorkflowsConfigSearchPaths:()=>v5,resolveSkillsConfigSearchPaths:()=>g5,resolveRulesConfigSearchPaths:()=>m5,parseWorkflowConfigFromMarkdown:()=>x5,parseSkillConfigFromMarkdown:()=>k5,parseRuleConfigFromMarkdown:()=>I5,createWorkflowsConfigDefinition:()=>d5,createUserInstructionConfigService:()=>c$,createSkillsConfigDefinition:()=>c5,createRulesConfigDefinition:()=>u5,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>h5,UnifiedConfigFileWatcher:()=>d2,SKILLS_CONFIG_DIRECTORY_NAME:()=>y5,RULES_CONFIG_DIRECTORY_NAME:()=>jQ});import{createHash as JC}from"node:crypto";import{watch as jC}from"node:fs";import{readdir as XC,readFile as YC}from"node:fs/promises";import{join as VC}from"node:path";function BC($){return JC("sha1").update($).digest("hex")}function RF($){return Boolean($&&typeof $==="object"&&"code"in $)}function qF($){return RF($)&&$.code==="ENOENT"}function MF($){return RF($)&&($.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($,W){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=W?.debounceMs??75,this.emitParseErrors=W?.emitParseErrors??!1;for(let Z of $){if(this.definitionsByType.has(Z.type))throw Error(`Duplicate unified config definition type '${Z.type}'.`);this.definitionsByType.set(Z.type,Z),this.recordsByType.set(Z.type,new Map),this.discoveredDirectoriesByType.set(Z.type,new Set);for(let Q of Z.directories){let J=this.baseTypesByDirectory.get(Q);if(J)J.add(Z.type);else this.baseTypesByDirectory.set(Q,new Set([Z.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 W=this.definitionsByType.get($);if(!W)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(W)})}getSnapshot($){let W=this.recordsByType.get($);return new Map([...W?.entries()??[]].map(([Z,Q])=>[Z,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[W,Z]of this.recordsByType.entries())$.set(W,new Map([...Z.entries()].map(([Q,J])=>[Q,{...J}])));return $}emit($){for(let W of this.listeners)W($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[W,Z]of this.watchersByDirectory.entries()){if($.has(W))continue;Z.close(),this.watchersByDirectory.delete(W)}this.watchedTypesByDirectory=$;for(let W of $.keys()){if(this.watchersByDirectory.has(W))continue;try{let Z=jC(W,()=>{let Q=this.watchedTypesByDirectory.get(W);if(!Q)return;for(let J of Q)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(W,Z),Z.on("error",(Q)=>{let J=this.watchedTypesByDirectory.get(W);if(!J)return;for(let j of J)this.emit({kind:"error",type:j,error:Q,filePath:W})})}catch(Z){if(!qF(Z)&&!MF(Z)){let Q=$.get(W);if(!Q)continue;for(let J of Q)this.emit({kind:"error",type:J,error:Z,filePath:W})}}}}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 W of $){let Z=this.definitionsByType.get(W);if(!Z)continue;await this.refreshTypeInternal(Z)}})},this.debounceMs)}async refreshTypeInternal($){let{records:W,discoveredDirectories:Z}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[J,j]of Q.entries()){if(W.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:j.filePath})}for(let[J,j]of W.entries()){let X=Q.get(J);if(X&&X.filePath===j.filePath&&X.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:J,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,W),this.discoveredDirectoriesByType.set($.type,Z),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let W=new Map,Z=new Set;for(let Q of $.directories){Z.add(Q);let J=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let j of J){let{fileName:X,filePath:Y}=j;if(Z.add(j.directoryPath),$.includeFile&&!$.includeFile(X,Y))continue;try{let V=await YC(Y,"utf8"),B={type:$.type,directoryPath:j.directoryPath,fileName:X,filePath:Y,content:V},H=$.parseFile(B),G=$.resolveId(H,B).trim();if(!G)continue;W.set(G,{type:$.type,id:G,item:H,filePath:Y,fingerprint:BC(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:Y})}}}return{records:W,discoveredDirectories:Z}}buildDesiredTypesByDirectory(){let $=new Map;for(let[W,Z]of this.baseTypesByDirectory.entries())$.set(W,new Set(Z));for(let[W,Z]of this.discoveredDirectoriesByType.entries())for(let Q of Z){let J=$.get(Q);if(J)J.add(W);else $.set(Q,new Set([W]))}return $}async readDirectoryFileCandidates($){try{return(await XC($,{withFileTypes:!0})).filter((Z)=>Z.isFile()).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:VC($,Z.name)})).sort((Z,Q)=>Z.fileName.localeCompare(Q.fileName))}catch(W){if(qF(W)||MF(W))return[];throw W}}}import{readdir as Wj,readFile as HC,stat as $j}from"node:fs/promises";import{basename as j$,dirname as GC,extname as WQ,join as v0,resolve as b5}from"node:path";import{AGENTS_RULES_FILE_NAME as EF,RULES_CONFIG_DIRECTORY_NAME as jQ,resolveGlobalAgentsRulesPath as KC,resolveRulesConfigSearchPaths as FC,resolveSkillsConfigSearchPaths as AC,resolveWorkflowsConfigSearchPaths as UC,SKILLS_CONFIG_DIRECTORY_NAME as y5,WORKFLOWS_CONFIG_DIRECTORY_NAME as h5}from"@cline/shared/storage";import DC from"yaml";var $Q="SKILL.md",_C="managed.json",fC=new Set([".md",".markdown",".txt"]);function Zj($){return $.trim().toLowerCase()}function _6($){let W=$;return W?.code==="ENOENT"||W?.code==="EACCES"||W?.code==="EPERM"||W?.code==="ELOOP"}function ZQ($){return fC.has(WQ($).toLowerCase())}function NF($){let W=[],Z=new Set;for(let Q of $){let J=b5(Q);if(Z.has(J))continue;Z.add(J),W.push(Q)}return W}function LC($){let W=[...$?.directories??g5($?.workspacePath)];if($?.pluginSkillDirectories)W.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)W.push(...cK({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return NF(W)}async function Qj($){try{let W=await Wj($,{withFileTypes:!0}),Z=[];for(let Q of W){if(!Q.isDirectory())continue;let J=v0($,Q.name),j=v0(J,_C);try{let X=await HC(j,"utf8"),Y=JSON.parse(X);if(Y&&typeof Y==="object")Z.push(J)}catch(X){if(_6(X))continue;if(X?.name==="SyntaxError")continue;throw X}}return Z.sort((Q,J)=>Q.localeCompare(J))}catch(W){if(_6(W))return[];throw W}}function Jj($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z;try{let j=DC.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}catch(j){let X=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:X}}}function QQ($,W,Z){if($===void 0||$===null){if(Z)throw Error(`Missing required frontmatter field '${W}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${W}' must be a string.`);let Q=$.trim();if(!Q&&Z)throw Error(`Frontmatter field '${W}' cannot be empty.`);return Q||void 0}function f6($,W){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${W}' must be a boolean.`);return $}function TC($,W){if(j$($.filePath).toLowerCase()!==EF.toLowerCase())return j$($.filePath,WQ($.filePath));if(W&&b5($.filePath)===b5(W,EF))return"Workspace AGENTS.md";if(b5($.filePath)===b5(KC()))return"Global AGENTS.md";return j$($.filePath,WQ($.filePath))}function k5($,W){let{data:Z,body:Q,parseError:J}=Jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in skill file.");let Y=QQ(Z.name,"name",!1)??W.trim();if(!Y)throw Error("Missing skill name.");return{name:Y,description:QQ(Z.description,"description",!1),disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function I5($,W){let{data:Z,body:Q,parseError:J}=Jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in rule file.");let X=QQ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing rule name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function x5($,W){let{data:Z,body:Q,parseError:J}=Jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in workflow file.");let X=QQ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing workflow name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function g5($){return AC($)}function m5($){return FC($)}function v5($){return UC($)}async function wF($){if(j$($)===".cline"){let W=await Qj($);return(await Promise.all(W.map((Q)=>wF(v0(Q,y5))))).flat()}try{let W=await Wj($,{withFileTypes:!0}),Z=[];for(let Q of W){if(Q.isFile()&&Q.name===$Q){Z.push({directoryPath:$,fileName:Q.name,filePath:v0($,Q.name)});continue}let J=v0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await $j(J).then((X)=>X.isDirectory()).catch((X)=>{if(_6(X))return!1;throw X}))Z.push({directoryPath:J,fileName:$Q,filePath:v0(J,$Q)})}return Z}catch(W){if(_6(W))return[];throw W}}async function JQ($){if(j$($)===".cline"){let W=await Qj($);return(await Promise.all(W.map((Q)=>JQ(v0(Q,"rules.md"))))).flat()}try{if((await $j($)).isFile())return[{directoryPath:GC($),fileName:j$($),filePath:$}]}catch(W){if(!_6(W))throw W}try{let Z=(await Wj($,{withFileTypes:!0})).filter((J)=>J.isFile()&&ZQ(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:v0($,J.name)})),Q=v0($,"AGENTS.md");try{if((await $j(Q)).isFile()){if(!Z.some((X)=>X.fileName==="AGENTS.md"))Z.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return Z}catch(W){if(_6(W))return[];throw W}}async function OC($){if(j$($)===".cline"){let W=await Qj($);return(await Promise.all(W.map((Q)=>JQ(v0(Q,h5))))).flat()}return JQ($)}function c5($){let W=LC($),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Z?NF([...W,Z]):W,discoverFiles:wF,includeFile:(Q)=>Q===$Q,parseFile:(Q)=>k5(Q.content,j$(Q.directoryPath)),resolveId:(Q)=>Zj(Q.name)}}function u5($){let W=$?.directories??m5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Z?[...W,Z]:W,discoverFiles:JQ,includeFile:(Q,J)=>Q===".clinerules"||ZQ(Q)||ZQ(J),parseFile:(Q)=>I5(Q.content,TC(Q,$?.workspacePath)),resolveId:(Q)=>Zj(Q.name)}}function d5($){let W=$?.directories??v5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Z?[...W,Z]:W,discoverFiles:OC,includeFile:(Q)=>ZQ(Q),parseFile:(Q)=>x5(Q.content,j$(Q.filePath,WQ(Q.filePath))),resolveId:(Q)=>Zj(Q.name)}}function CF($){let W=[c5($?.skills),u5($?.rules),d5($?.workflows)];return new d2(W,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as PF}from"@cline/shared";function zC($,W){if($.description?.trim())return PF($.description,".");if(W==="workflow")return;return PF($.instructions,".")}function qC($){return $.disabled!==!0}function SF($,W){return[...$.getSnapshot(W).entries()].map(([Z,Q])=>({id:Z,record:Q})).filter(({record:Z})=>qC(Z.item)).map(({id:Z,record:Q})=>({id:Z,name:Q.item.name,instructions:Q.item.instructions,description:zC(Q.item,W),kind:W})).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function l5($){let W=new Map;for(let Z of[...SF($,"workflow"),...SF($,"skill")])if(!W.has(Z.name))W.set(Z.name,Z);return[...W.values()].sort((Z,Q)=>Z.name.localeCompare(Q.name))}function bF($,W){if(!$.startsWith("/")||$.length<2)return $;let Z=$.match(/^\/(\S+)/);if(!Z)return $;let Q=Z[1];if(!Q)return $;let J=Q.length+1,j=$.slice(J),X=l5(W).find((Y)=>Y.name===Q);return X?`${X.instructions}${j}`:$}function XQ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function MC($){if(!$||$.length===0)return;let W=$.map(XQ).filter((Z)=>Z.length>0);return W.length>0?new Set(W):void 0}function RC($,W,Z){if(!Z)return!0;let Q=XQ($),J=XQ(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function p5($,W){let Z=MC(W);return[...$.getSnapshot("skill").entries()].map(([J,j])=>{let X=j.item;return{id:J,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0,skill:X}}).filter((J)=>RC(J.id,J.name,Z))}function EC($,W){return p5($,W).filter((Z)=>!Z.disabled).map((Z)=>Z.name.trim()).filter((Z)=>Z.length>0).sort((Z,Q)=>Z.localeCompare(Q))}function NC($,W,Z){let Q=XQ(W);if(!Q)return{error:"Missing skill name."};let J=p5($,Z),j=J.find((H)=>H.id===Q);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 X=Q.includes(":")?Q.split(":").at(-1)??Q:Q,Y=J.filter(({id:H})=>{if(H===X)return!0;return H.endsWith(`:${X}`)}),V=Y.filter(({skill:H})=>H.disabled!==!0);if(V.length===1){let{id:H,skill:G}=V[0];return{id:H,skill:G}}if(V.length>1)return{error:`Skill "${W}" is ambiguous. Use one of: ${V.map(({id:H})=>H).join(", ")}`};if(Y.length===1){let{skill:H}=Y[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(Y.length>1)return{error:`Skill "${W}" is ambiguous, and all matches are disabled: ${Y.map(({id:H})=>H).join(", ")}`};let B=EC($,Z);return{error:B.length>0?`Skill "${W}" not found. Available skills: ${B.join(", ")}`:"No skills are currently available."}}function jj($,W=Promise.resolve(),Z){let Q=new Set,J=async(j,X)=>{await W;let Y=NC($,j,Z);if("error"in Y)return Y.error;let{id:V,skill:B}=Y;if(Q.has(V))return`Skill "${B.name}" is already running.`;Q.add(V);try{let H=X?.trim(),G=H?`
484
484
  <command-args>${H}</command-args>`:"",K=B.description?.trim()?`Description: ${B.description.trim()}
485
485
 
486
486
  `:"";return`<command-name>${B.name}</command-name>${G}
487
487
  <command-instructions>
488
488
  ${K}${B.instructions}
489
- </command-instructions>`}finally{Q.delete(V)}};return Object.defineProperty(J,"configuredSkills",{get:()=>d5($,Z).map(({skill:j,...X})=>X),enumerable:!0,configurable:!1}),J}function MF($){let W=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await W,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>M7($.watcher)});if($.registerSkillsTool)Q.registerTool(T2($j($.watcher,W,$.allowedSkillNames)));for(let J of u5($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:J.name,description:J.description,handler:(j)=>{let X=j.trim();return X?`${J.instructions}
489
+ </command-instructions>`}finally{Q.delete(V)}};return Object.defineProperty(J,"configuredSkills",{get:()=>p5($,Z).map(({skill:j,...X})=>X),enumerable:!0,configurable:!1}),J}function yF($){let W=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await W,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>C7($.watcher)});if($.registerSkillsTool)Q.registerTool(O2(jj($.watcher,W,$.allowedSkillNames)));for(let J of l5($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:J.name,description:J.description,handler:(j)=>{let X=j.trim();return X?`${J.instructions}
490
490
 
491
- ${X}`:J.instructions}})}}}class RF{watcher;ready;stopped=!1;constructor($){this.watcher=TF($)}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(([W,Z])=>({type:$,id:W,filePath:Z.filePath,item:Z.item}))}listRuntimeCommands(){return u5(this.watcher)}resolveRuntimeSlashCommand($){return qF($,this.watcher)}hasConfiguredSkills($){return d5(this.watcher,$).some((W)=>!W.disabled)}createSkillsExecutor($){return $j(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return MF({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function v$($){return new RF($)}import{readFile as TC,writeFile as OC}from"node:fs/promises";import wF from"yaml";function zC($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z,j=wF.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}function EF($,W){return`---
492
- ${wF.stringify($).trimEnd()}
491
+ ${X}`:J.instructions}})}}}class hF{watcher;ready;stopped=!1;constructor($){this.watcher=CF($)}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(([W,Z])=>({type:$,id:W,filePath:Z.filePath,item:Z.item}))}listRuntimeCommands(){return l5(this.watcher)}resolveRuntimeSlashCommand($){return bF($,this.watcher)}hasConfiguredSkills($){return p5(this.watcher,$).some((W)=>!W.disabled)}createSkillsExecutor($){return jj(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return yF({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function c$($){return new hF($)}import{readFile as wC,writeFile as CC}from"node:fs/promises";import xF from"yaml";function PC($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z,j=xF.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}function IF($,W){return`---
492
+ ${xF.stringify($).trimEnd()}
493
493
  ---
494
- ${W}`}function qC($,W){let{data:Z,body:Q,hadFrontmatter:J}=zC($);if(!J&&W)return $;if(W){if(delete Z.disabled,Z.enabled===!1)delete Z.enabled;if(Object.keys(Z).length===0)return Q;return EF(Z,Q)}return Z.disabled=!0,EF(Z,Q)}async function CF({filePath:$,enabled:W}){let Z=await TC($,"utf8"),Q=qC(Z,W);return await OC($,Q),{filePath:$,enabled:W,disabled:!W}}var JA={};w(JA,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>_6,updateMcpServerOAuthStateAsync:()=>p5,updateMcpServerOAuthState:()=>r2,setMcpServerDisabled:()=>l2,resolvePluginMcpServerRegistrations:()=>JQ,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>i2,normalizePluginMcpServerRegistration:()=>Bj,loadMcpSettingsFile:()=>d2,listMcpServerOAuthStatuses:()=>r5,hasMcpSettingsFile:()=>j$,getMcpServerOAuthState:()=>p2,createMcpTools:()=>z6,createDisabledMcpToolPolicy:()=>i5,createDisabledMcpToolPolicies:()=>XQ,createDefaultMcpServerClientFactory:()=>T6,authorizeMcpServerOAuth:()=>ZQ,McpSettingsUpdateSkippedError:()=>D6,McpSettingsMutatorPurityError:()=>c$,McpSettingsLockTimeoutError:()=>u$,InMemoryMcpManager:()=>n2});import{spawn as VP}from"node:child_process";import{StringDecoder as tF}from"node:string_decoder";import{UnauthorizedError as nF}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as BP}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as tC}from"node:crypto";import{UnauthorizedError as eC}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as $P}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as WP}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as ZP}from"@modelcontextprotocol/sdk/client/streamableHttp.js";eZ();var QP="/mcp/oauth/callback",JP=[1456,1457,1458],jP=300000;function XP($){if($ instanceof Error){let W=$.message.trim();if(W.length>0)return W}return String($)}function YP($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function WQ($){let W={};try{W=p2($.serverName,{filePath:$.settingsPath})??{}}catch{W={}}let Z,Q,J=async(X)=>{let Y=L6(X(W))??{};try{W=r2($.serverName,()=>Y,{filePath:$.settingsPath})}catch{W=Y}};return{provider:{get redirectUrl(){return W.redirectUrl??$.redirectUrl},get clientMetadata(){return YP(W.redirectUrl??$.redirectUrl)},state:()=>{return Q=tC(),Q},clientInformation:()=>W.clientInformation,saveClientInformation:async(X)=>{await J((Y)=>({...Y,clientInformation:X,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>W.tokens,saveTokens:async(X)=>{let Y=Date.now();await J((V)=>({...V,tokens:X,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Y}))},redirectToAuthorization:async(X)=>{Z=X.toString(),await $.onAuthorizationUrl?.(Z)},saveCodeVerifier:async(X)=>{await J((Y)=>({...Y,codeVerifier:X,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!W.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return W.codeVerifier},invalidateCredentials:async(X)=>{await J((Y)=>{if(X==="all")return{lastError:Y.lastError,redirectUrl:Y.redirectUrl};return{...Y,...X==="client"?{clientInformation:void 0}:{},...X==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...X==="verifier"?{codeVerifier:void 0}:{},...X==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(X)=>{await J((Y)=>({...Y,discoveryState:X}))},discoveryState:()=>W.discoveryState},getLastAuthorizationUrl:()=>Z,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await J((X)=>({...X,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(X)=>{await J((Y)=>({...Y,lastError:X}))},clearError:async()=>{await J((X)=>({...X,lastError:void 0}))}}}function $Q($){let W=$.registration.transport;if(W.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Z=W.headers?{headers:W.headers}:void 0;if(W.type==="sse")return new WP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch});return new ZP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch})}function iF($){return new $P({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function ZQ($){let W=$.serverName.trim();if(!W)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Z}=await Promise.resolve().then(() => (eZ(),rF)),Q=Z({filePath:$.filePath}).find((V)=>V.name===W);if(!Q)throw Error(`MCP server "${W}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${W}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${W}" uses stdio transport and does not support OAuth browser flow.`);let J=await H1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:JP,callbackPath:$.callbackPath??QP,timeoutMs:$.timeoutMs??jP,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=WQ({settingsPath:$.filePath,serverName:W,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await j.resetInteractiveState();let X=iF($),Y;try{let V=$Q({registration:Q,oauthProvider:j.provider,fetch:$.fetch});try{return await X.connect(V),await X.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" is already authorized.`}}catch(B){if(!(B instanceof eC))throw B;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${W}" did not provide an authorization URL.`);let G=await J.waitForCallback();if(!G)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(G.error)throw Error(`OAuth authorization failed: ${G.error}`);if(!G.code)throw Error("OAuth callback did not include an authorization code.");let K=j.getLastOAuthState();if(!K)throw Error(`MCP server "${W}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),Y=iF($);let F=$Q({registration:Q,oauthProvider:j.provider,fetch:$.fetch});return await Y.connect(F),await Y.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" OAuth authorization completed.`}}}catch(V){let B=XP(V);throw await j.markError(B),Error(B)}finally{await X.close().catch(()=>{return}),await Y?.close().catch(()=>{return}),J.close()}}var HP="2024-11-05",GP=5000,KP=1500,aF="http://127.0.0.1:1456/mcp/oauth/callback";function QQ($){return $ instanceof Error?$.message:String($)}function oF($){let W=Buffer.from(JSON.stringify($),"utf8"),Z=Buffer.from(`Content-Length: ${W.byteLength}\r
494
+ ${W}`}function SC($,W){let{data:Z,body:Q,hadFrontmatter:J}=PC($);if(!J&&W)return $;if(W){if(delete Z.disabled,Z.enabled===!1)delete Z.enabled;if(Object.keys(Z).length===0)return Q;return IF(Z,Q)}return Z.disabled=!0,IF(Z,Q)}async function gF({filePath:$,enabled:W}){let Z=await wC($,"utf8"),Q=SC(Z,W);return await CC($,Q),{filePath:$,enabled:W,disabled:!W}}var FA={};w(FA,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,setMcpServerDisabled:()=>p2,resolvePluginMcpServerRegistrations:()=>FQ,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>n2,normalizePluginMcpServerRegistration:()=>Aj,loadMcpSettingsFile:()=>l2,listMcpServerOAuthStatuses:()=>n5,hasMcpSettingsFile:()=>X$,getMcpServerOAuthState:()=>r2,createMcpTools:()=>M6,createDisabledMcpToolPolicy:()=>a5,createDisabledMcpToolPolicies:()=>UQ,createDefaultMcpServerClientFactory:()=>z6,authorizeMcpServerOAuth:()=>GQ,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$,InMemoryMcpManager:()=>a2});import{spawn as DP}from"node:child_process";import{StringDecoder as YA}from"node:string_decoder";import{UnauthorizedError as QA}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as _P}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as XP}from"node:crypto";import{UnauthorizedError as YP}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as VP}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as BP}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as HP}from"@modelcontextprotocol/sdk/client/streamableHttp.js";VQ();var GP="/mcp/oauth/callback",KP=[1456,1457,1458],FP=300000;function AP($){if($ instanceof Error){let W=$.message.trim();if(W.length>0)return W}return String($)}function UP($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function HQ($){let W={};try{W=r2($.serverName,{filePath:$.settingsPath})??{}}catch{W={}}let Z,Q,J=async(X)=>{let Y=O6(X(W))??{};try{W=i2($.serverName,()=>Y,{filePath:$.settingsPath})}catch{W=Y}};return{provider:{get redirectUrl(){return W.redirectUrl??$.redirectUrl},get clientMetadata(){return UP(W.redirectUrl??$.redirectUrl)},state:()=>{return Q=XP(),Q},clientInformation:()=>W.clientInformation,saveClientInformation:async(X)=>{await J((Y)=>({...Y,clientInformation:X,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>W.tokens,saveTokens:async(X)=>{let Y=Date.now();await J((V)=>({...V,tokens:X,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Y}))},redirectToAuthorization:async(X)=>{Z=X.toString(),await $.onAuthorizationUrl?.(Z)},saveCodeVerifier:async(X)=>{await J((Y)=>({...Y,codeVerifier:X,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!W.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return W.codeVerifier},invalidateCredentials:async(X)=>{await J((Y)=>{if(X==="all")return{lastError:Y.lastError,redirectUrl:Y.redirectUrl};return{...Y,...X==="client"?{clientInformation:void 0}:{},...X==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...X==="verifier"?{codeVerifier:void 0}:{},...X==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(X)=>{await J((Y)=>({...Y,discoveryState:X}))},discoveryState:()=>W.discoveryState},getLastAuthorizationUrl:()=>Z,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await J((X)=>({...X,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(X)=>{await J((Y)=>({...Y,lastError:X}))},clearError:async()=>{await J((X)=>({...X,lastError:void 0}))}}}function BQ($){let W=$.registration.transport;if(W.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Z=W.headers?{headers:W.headers}:void 0;if(W.type==="sse")return new BP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch});return new HP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch})}function ZA($){return new VP({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function GQ($){let W=$.serverName.trim();if(!W)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Z}=await Promise.resolve().then(() => (VQ(),WA)),Q=Z({filePath:$.filePath}).find((V)=>V.name===W);if(!Q)throw Error(`MCP server "${W}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${W}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${W}" uses stdio transport and does not support OAuth browser flow.`);let J=await H1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:KP,callbackPath:$.callbackPath??GP,timeoutMs:$.timeoutMs??FP,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=HQ({settingsPath:$.filePath,serverName:W,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await j.resetInteractiveState();let X=ZA($),Y;try{let V=BQ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});try{return await X.connect(V),await X.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" is already authorized.`}}catch(B){if(!(B instanceof YP))throw B;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${W}" did not provide an authorization URL.`);let G=await J.waitForCallback();if(!G)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(G.error)throw Error(`OAuth authorization failed: ${G.error}`);if(!G.code)throw Error("OAuth callback did not include an authorization code.");let K=j.getLastOAuthState();if(!K)throw Error(`MCP server "${W}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),Y=ZA($);let F=BQ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});return await Y.connect(F),await Y.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" OAuth authorization completed.`}}}catch(V){let B=AP(V);throw await j.markError(B),Error(B)}finally{await X.close().catch(()=>{return}),await Y?.close().catch(()=>{return}),J.close()}}var fP="2024-11-05",LP=5000,TP=1500,JA="http://127.0.0.1:1456/mcp/oauth/callback";function KQ($){return $ instanceof Error?$.message:String($)}function jA($){let W=Buffer.from(JSON.stringify($),"utf8"),Z=Buffer.from(`Content-Length: ${W.byteLength}\r
495
495
  \r
496
- `,"utf8");return Buffer.concat([Z,W])}function sF($){return Buffer.from(`${JSON.stringify($)}
497
- `,"utf8")}class Yj{buffer="";decoder=new tF("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`\r
496
+ `,"utf8");return Buffer.concat([Z,W])}function XA($){return Buffer.from(`${JSON.stringify($)}
497
+ `,"utf8")}class Kj{buffer="";decoder=new YA("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`\r
498
498
  \r
499
- `);if(Z<0)break;let J=this.buffer.slice(0,Z).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!J)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(J[1],10),X=Z+4,Y=X+j;if(this.buffer.length<Y)break;W.push(this.buffer.slice(X,Y)),this.buffer=this.buffer.slice(Y)}return W}}class Vj{buffer="";decoder=new tF("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`
500
- `);if(Z<0)break;let Q=this.buffer.slice(0,Z).trim();if(this.buffer=this.buffer.slice(Z+1),Q.length>0)W.push(Q)}return W}}class eF{registration;process;nextRequestId=1;pending=new Map;framedParser=new Yj;newlineParser=new Vj;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"],W;for(let Z of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Z);try{await this.request("initialize",{protocolVersion:HP,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},KP),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Z;return}catch(Q){W=Q instanceof Error?Q:Error(String(Q))}}throw W??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((W)=>typeof W?.name==="string"&&typeof W.inputSchema==="object"&&W.inputSchema!==null).map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let W=this.registration.transport;if(W.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${W.type}`);this.framedParser=new Yj,this.newlineParser=new Vj,this.stderrBuffer="",this.protocolMode=$;let Z=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=VP(W.command,W.args??[],{cwd:W.cwd,env:{...process.env,...W.env??{}},stdio:["pipe","pipe","pipe"],...Z});this.process=Q,Q.stdout.on("data",(J)=>this.handleStdout(J)),Q.stderr.on("data",(J)=>{if(this.process!==Q)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(J)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${QQ(J)}`))}),Q.once("exit",(J,j)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let X=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${j??"null"}).${X}`))})}handleStdout($){try{let W=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Z of W){let Q=JSON.parse(Z);if(typeof Q.id!=="number")continue;let J=this.pending.get(Q.id);if(!J)continue;if(this.pending.delete(Q.id),clearTimeout(J.timeout),Q.error){let j=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;J.reject(Error(j));continue}J.resolve(Q.result)}}catch(W){this.handleProtocolFailure(W)}}handleProtocolFailure($){let W=this.process;if(!W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${QQ($)}.${Z}`)),W.kill()}async request($,W,Z=GP){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,j={jsonrpc:"2.0",id:J,method:$,...W?{params:W}:{}},X=new Promise((Y,V)=>{let B=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Z);this.pending.set(J,{resolve:Y,reject:V,timeout:B})});try{Q.stdin.write(this.protocolMode==="framed"?oF(j):sF(j))}catch(Y){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw Y}return X}notify($,W){let Z=this.process;if(!Z?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...W?{params:W}:{}};Z.stdin.write(this.protocolMode==="framed"?oF(Q):sF(Q))}failAllPending($){for(let[W,Z]of this.pending)clearTimeout(Z.timeout),this.pending.delete(W),Z.reject($)}}class $A{registration;options;client;authContext;constructor($,W){this.registration=$;this.options=W}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 $=WQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??aF});this.authContext=$;try{let W=new BP({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Z=$Q({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await W.connect(Z),await $.clearError(),this.client=W}catch(W){let Z=W instanceof nF?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):QQ(W);throw await $.markError(Z),Error(Z)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema&&typeof Z.inputSchema==="object"&&!Array.isArray(Z.inputSchema)?Z.inputSchema:{}}))}catch(W){return await this.handleOperationError(W)}}async callTool($){let W=await this.ensureConnectedClient();try{return await W.callTool({name:$.name,arguments:$.arguments??{}})}catch(Z){return await this.handleOperationError(Z)}}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 W=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${W} Run authorizeMcpServerOAuth for this server.`;return`${W} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let W=this.authContext??WQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??aF}),Z=$ instanceof nF?this.formatUnauthorizedMessage(W.getLastAuthorizationUrl()):QQ($);throw await W.markError(Z),Error(Z)}}function T6($={}){return(W)=>W.transport.type==="stdio"?new eF(W):new $A(W,$)}eZ();function e0(){return Date.now()}function FP($){return $.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}class n2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let W=this.servers.get($.name);if(!W){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:e0()});return}let Z=JSON.stringify(W.registration.transport)!==JSON.stringify($.transport);if(W.registration={...$},W.updatedAt=e0(),Z)await this.disconnectState(W),W.client=void 0,W.toolCache=void 0,W.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.connectState(W)})}async disconnectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W)})}async setServerDisabled($,W){await this.runExclusive($,async()=>{let Z=this.requireServer($);if(Z.registration={...Z.registration,disabled:W},Z.updatedAt=e0(),W)await this.disconnectState(Z)})}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(($,W)=>$.name.localeCompare(W.name))}async listTools($){let W=this.requireServer($),Z=W.toolCacheUpdatedAt??0;if(W.toolCache&&e0()-Z<=this.toolsCacheTtlMs)return W.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let W=this.requireServer($),Q=await(await this.ensureConnectedClient(W)).listTools(),J=FP(Q);return W.toolCache=J,W.toolCacheUpdatedAt=e0(),W.updatedAt=e0(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let W=this.requireServer($.serverName),Z=await this.ensureConnectedClient(W);return W.updatedAt=e0(),Z.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let W of $)await this.unregisterServer(W)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=e0();try{let W=$.client??await this.clientFactory($.registration);await W.connect(),$.client=W,$.status="connected",$.lastError=void 0,$.updatedAt=e0()}catch(W){throw $.status="disconnected",$.lastError=W instanceof Error?W.message:String(W),$.updatedAt=e0(),W}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=e0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=e0()}}requireServer($){let W=this.servers.get($);if(!W)throw Error(`Unknown MCP server: ${$}`);return W}async runExclusive($,W){let Z=this.operationLocks.get($)??Promise.resolve(),Q,J=new Promise((X)=>{Q=X}),j=Z.catch(()=>{return}).then(()=>J);this.operationLocks.set($,j),await Z.catch(()=>{return});try{return await W()}finally{if(Q?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function O6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function WA($){return O6($)&&Object.values($).every((W)=>typeof W==="string")}function AP($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function UP($){if(!O6($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function fP($){let W=$.env?Object.entries($.env):[];if(W.length===0)return{ok:!0};let Z={};for(let[Q,J]of W){if(typeof J==="string"){Z[Q]=J;continue}let j=J.fromEnv?.trim()||Q,X=process.env[j];if(typeof X==="string"&&X.length>0){Z[Q]=X;continue}if(typeof J.value==="string"){Z[Q]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Z).length>0?Z:void 0}}function Bj($){if(!O6($))return{name:"",loadError:"invalid MCP server registration"};let W=typeof $.name==="string"?$.name.trim():"";if(!W)return{name:W,loadError:"empty MCP server name"};let Z=$.env,Q=Z===void 0?void 0:Z;if(Q!==void 0){if(!O6(Q))return{name:W,loadError:"invalid env"};for(let[V,B]of Object.entries(Q))if(typeof B!=="string"&&!UP(B))return{name:W,loadError:`invalid env "${V}"`}}let J=$.transport;if(!O6(J))return{name:W,loadError:"invalid MCP transport"};let j=J.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:W,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Q!==void 0)return{name:W,loadError:"top-level env is only supported for stdio MCP transports"};let X=O6($.metadata)?$.metadata:void 0;if(j==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:W,loadError:"stdio MCP transport requires command"};let B=J.args;if(B!==void 0&&!AP(B))return{name:W,loadError:"stdio MCP transport args must be strings"};let H=J.cwd;if(H!==void 0&&typeof H!=="string")return{name:W,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!WA(G))return{name:W,loadError:"stdio MCP transport env must be strings"};let K=fP({name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:G},env:Q,metadata:X});if(!K.ok)return{name:W,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:W,registration:{name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:F},metadata:X}}}if(typeof J.url!=="string"||!J.url.trim())return{name:W,loadError:`${j} MCP transport requires url`};let Y=J.headers;if(Y!==void 0&&!WA(Y))return{name:W,loadError:`${j} MCP transport headers must be strings`};return{name:W,registration:{name:W,transport:j==="sse"?{type:"sse",url:J.url,headers:Y}:{type:"streamableHttp",url:J.url,headers:Y},metadata:X}}}function JQ($){let W=new Map;return $.map(({server:Z,owner:Q,ownerLabel:J})=>{let j=Bj(Z);if(!j.registration)return{owner:Q,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let X=W.get(j.registration.name);if(W.has(j.registration.name)){let Y=X?` already registered by ${X}`:"";return{owner:Q,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${Y}`}}return W.set(j.registration.name,J),{owner:Q,name:j.registration.name,registration:j.registration}})}import{createHash as DP}from"node:crypto";var ZA=64,_P=/[^a-zA-Z0-9_-]+/g,QA=8,LP=1,TP="mcp_tool";function OP($){return DP("sha1").update($).digest("hex").slice(0,QA)}function zP($){return $.replace(_P,"_")}var jQ=({serverName:$,toolName:W})=>{let Z=`${$}__${W}`,Q=zP(Z);if(Q===Z&&Z.length<=ZA)return Z;let J=OP(Z),j=ZA-LP-QA;return`${Q.slice(0,j)||TP}_${J}`};function i5($){return{[($.nameTransform??jQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function XQ($){let W={};for(let Z of $.toolNames)Object.assign(W,i5({serverName:$.serverName,toolName:Z,nameTransform:$.nameTransform}));return W}import{createTool as qP}from"@cline/shared";function MP($,W){let Z=W.description?.trim();if(Z)return Z;return`Execute MCP tool "${W.name}" from server "${$}".`}async function z6($){let W=await $.provider.listTools($.serverName),Z=$.nameTransform??jQ;return W.map((Q)=>{let J=Z({serverName:$.serverName,toolName:Q.name});return qP({name:J,description:MP($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,X)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:X})})})}X1();var YA={};w(YA,{listPluginToolsWithDiagnostics:()=>YQ,listPluginTools:()=>n5});import{stat as RP}from"node:fs/promises";import{isAbsolute as NP,relative as EP,resolve as jA}from"node:path";X1();function wP($,W){let Z=EP(jA($),jA(W));return Z===""||!Z.startsWith("..")&&!NP(Z)}var CP=32,q6=new Map;function PP($,W){if(!q6.has($)&&q6.size>=CP){let Z=q6.keys().next().value;if(Z)q6.delete(Z)}q6.set($,W)}async function SP($){let W=await Promise.all($.pluginPaths.map(async(Z)=>{try{let Q=await RP(Z);return`${Z}:${Q.mtimeMs}:${Q.size}`}catch{return`${Z}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:W})}function XA($,W){return $.map((Z)=>({...Z,enabled:!W.has(Z.name)}))}function bP($){return $.sort((W,Z)=>{let Q=W.name.localeCompare(Z.name);if(Q!==0)return Q;return W.path.localeCompare(Z.path)})}async function yP($,W){if(!$.setup)return{tools:[]};let Z=[],Q={registerTool:(J)=>Z.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Q,{workspaceInfo:W}),{tools:Z}}async function YQ($){let W=Z$({workspacePath:$.workspacePath,cwd:$.cwd}),Z=L1($.disabledToolNames);if(W.length===0)return{tools:[],failures:[],warnings:[]};let Q=await SP({pluginPaths:W,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=q6.get(Q);if(J)return{tools:XA(J.tools,Z),failures:J.failures,warnings:J.warnings};let j=[],X=[],Y=[],V;try{V=await Q6({pluginPaths:W,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),X=[...V.failures],Y=[...V.warnings];for(let H of V.extensions??[]){let G=H.__clinePluginPath;if(!G)continue;let K=wP($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await yP(H,{rootPath:$.workspacePath})}catch(A){X.push({pluginPath:G,pluginName:H.name,phase:"setup",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0});continue}for(let A of F.tools)j.push({name:A.name,pluginName:H.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(H){X=W.map((G)=>({pluginPath:G,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let B=bP(j);return PP(Q,{tools:B,failures:X,warnings:Y}),{tools:XA(B,Z),failures:X,warnings:Y}}async function n5($){return(await YQ($)).tools}function s5($,W){if(!W)return"global";let Z=KA(W,$);return!Z.startsWith("..")&&!GA(Z)?"workspace":"global"}function xP($,W){return s5($,W)==="workspace"?"workspace-plugin":"global-plugin"}function gP($,W){let Z=KA(BA($),BA(W));return Z===""||!Z.startsWith("..")&&!GA(Z)}function mP($){try{let W=JSON.parse(hP($,"utf8"));return typeof W.name==="string"&&W.name.trim()?W.name.trim():void 0}catch{return}}function vP($){let W=VA($);while(!0){let Z=IP(W,"package.json");if(o5(Z)){let J=mP(Z);if(J)return J;break}let Q=VA(W);if(Q===W)break;W=Q}return Hj($,kP($))}function cP($){let W=[];for(let Z of Z$({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let Q of Q$([Z]))W.push({directory:Q,pluginName:vP(Z),pluginPath:Z,source:$.workspaceRoot?xP(Z,$.workspaceRoot):"global-plugin"});return W.sort((Z,Q)=>Q.directory.length-Z.directory.length)}function uP($,W){return W.find((Z)=>gP(Z.directory,$))}function a5($){return[...$].sort((W,Z)=>{let Q=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(W.source!==Z.source)return Q(W.source)-Q(Z.source);return W.name.localeCompare(Z.name)})}function FA($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function AA($,W){return $.cwd?.trim()||W||process.cwd()}async function HA($,W){if($.userInstructionService)return await W($.userInstructionService);let Z=FA($),Q=AA($,Z),J=v$({skills:{workspacePath:Z||void 0,includePluginSkills:!0,cwd:Q},rules:{workspacePath:Z||void 0},workflows:{workspacePath:Z||void 0}});try{return await J.start(),await W(J)}finally{J.stop()}}function dP($,W){if(!$)return;let Z=$.listRecords("skill");if(W.id){let Q=Z.find((J)=>J.id===W.id);if(Q)return Q}for(let Q of Z)if(Q.filePath===W.path||Q.item.name===W.name||Q.id===W.name)return Q;return}class d${async list($={}){return await HA($,async(W)=>{let Z=FA($),Q=cP({workspaceRoot:Z,cwd:AA($,Z)}),J=[],j=[],X=[],Y=[],V=[];if(W){for(let H of W.listRecords("workflow")){let G=H.item;J.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"workflow",source:s5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("rule")){let G=H.item;j.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"rule",source:s5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("skill")){let G=H.item,K=uP(H.filePath,Q);X.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??s5(H.filePath,Z),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Z)try{for(let H of await n5({workspacePath:Z,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))Y.push({id:`${H.pluginName}:${H.name}:${H.path}`,name:H.name,path:H.path,enabled:H.enabled,kind:"tool",source:H.source,description:H.description,toggleable:!0})}catch{}let B=J0();if(j$({filePath:B}))try{for(let H of t0({filePath:B}))V.push({id:H.name,name:H.name,path:B,enabled:H.disabled!==!0,kind:"mcp",source:s5(B,Z),description:H.transport.type,toggleable:!0})}catch{}return{workflows:a5(J.filter((H)=>o5(H.path))),rules:a5(j.filter((H)=>o5(H.path))),skills:a5(X.filter((H)=>o5(H.path))),tools:a5(Y),mcp:a5(V.filter((H)=>o5(H.path)))}})}async toggle($){if($.type==="skills")return await HA($,async(W)=>{let Z=dP(W,$),Q=Z?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??Hj($.path??"")}'.`);let J=Z?.item&&"disabled"in Z.item?Z.item.disabled!==!0:void 0,j=$.enabled??(J!==void 0?!J:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??Hj($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await CF({filePath:Q,enabled:j}),await W?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:W}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)Y9($.name);else RV($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let W=$.name?.trim()||$.id?.trim();if(!W)throw Error("MCP server settings toggle requires a server name.");let Z=$.path?.trim()||J0(),Q=$.enabled;if(Q===void 0){let J=t0({filePath:Z}).find((j)=>j.name===W);if(!J)throw Error(`Unknown MCP server: ${W}`);Q=J.disabled===!0}return l2({filePath:Z,name:W,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function a2(){return new d$}function fA($){return{async list(W){let Z=$;if(Z.listSettings)return await Z.listSettings(W);return await a2().list(W)},async toggle(W){let Z=$;if(Z.toggleSetting)return await Z.toggleSetting(W);return await a2().toggle(W)}}}function DA($){function W(){let Z=$.pendingPrompts;if(!Z)throw Error("Pending prompt service is not available.");return Z}return{list(Z){return W().list(Z)},update(Z){return W().update(Z)},delete(Z){return W().delete(Z)}}}function _A($){let W=$.config;return"providerId"in W?{...$,config:{...W,...lP($.localRuntime)},localRuntime:$.localRuntime}:$}function Gj($,W={}){let Z=A4($.config),Q=C0(W.defaultCapabilities,$.capabilities),J=pP(Z.localRuntime,$.localRuntime),j=W.withExtensionContext?.(J?.extensionContext);if(j)J={...J??{},extensionContext:j};return{...$,...Z,...J?{localRuntime:J}:{},...Q?{capabilities:Q}:{}}}function lP($){if(!$)return{};let{modelCatalogDefaults:W,userInstructionService:Z,configExtensions:Q,onTeamRestored:J,...j}=$;return j}function pP(...$){let W={};for(let Z of $)if(Z)Object.assign(W,Z);return Object.keys(W).length>0?W:void 0}M0();function LA($){let W=$.input.config.telemetry??$.telemetry;if(!W)return;W.capture({event:v.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??F0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function t5($){return!!$&&typeof $==="object"&&!Array.isArray($)}function Kj($){let W=$?.trim();return W?W:void 0}function rP($,W){let Z=$?.trim();if(!Z)return W;let Q=Date.parse(Z);if(!Number.isFinite(Q))return W;return new Date(Q).toISOString()}function TA($,W){return new Date(new Date($).getTime()+Math.max(0,Math.floor(W))*1000).toISOString()}function OA($,W){return new Date(new Date($).getTime()-Math.max(0,Math.floor(W))*1000).toISOString()}function iP($,W){if(!$)return W;return new Date($).getTime()>=new Date(W).getTime()?$:W}function nP($,W){let Z=$.eventId.trim(),Q=$.eventType.trim(),J=$.source.trim(),j=Kj($.subject),X=Kj($.dedupeKey)??`${Q}:${J}:${j??Z}`;return{eventId:Z,eventType:Q,source:J,subject:j,occurredAt:rP($.occurredAt,W),workspaceRoot:Kj($.workspaceRoot),payload:t5($.payload)?$.payload:void 0,attributes:t5($.attributes)?$.attributes:void 0,dedupeKey:X}}function Fj($,W){if(!W)return;let Z=W.split("."),Q=$;for(let J of Z){if(!t5(Q))return;Q=Q[J]}return Q}function aP($,W){if($.attributes&&Object.hasOwn($.attributes,W))return $.attributes[W];if($.payload&&Object.hasOwn($.payload,W))return $.payload[W];let Z={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=Fj(Z,W);if(Q!==void 0)return Q;if($.attributes){let J=Fj($.attributes,W);if(J!==void 0)return J}if($.payload)return Fj($.payload,W);return}function VQ($,W){if(Array.isArray(W))return W.some((Z)=>VQ($,Z));if(Array.isArray($))return $.some((Z)=>VQ(Z,W));if(t5(W)){if(!t5($))return!1;return Object.entries(W).every(([Z,Q])=>VQ($[Z],Q))}return Object.is($,W)}function oP($,W){if(!W||Object.keys(W).length===0)return!0;return Object.entries(W).every(([Z,Q])=>VQ(aP($,Z),Q))}class Aj{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let W=new Date(this.nowFn()).toISOString(),Z=nP($,W),Q=this.store.insertEventLog(Z,{receivedAtIso:W});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Z.eventType),j=[],X=[],Y=[];for(let H of J){if(!oP(Z,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Z.dedupeKey});continue}X.push(H);let G=this.materializeForSpec(H,Z,Q.record.receivedAt);if(G.run)Y.push(G.run);else j.push({specId:H.specId,externalId:H.externalId,reason:G.reason,dedupeKey:Z.dedupeKey})}let V=X.length===0?"unmatched":Y.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:V,matchedSpecCount:X.length,queuedRunCount:Y.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let B=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:V,matchedSpecCount:X.length,queuedRunCount:Y.length}),{event:B??Q.record,duplicate:!1,matchedSpecs:X,queuedRuns:Y,suppressions:j}}catch(J){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:J});throw J}}materializeForSpec($,W,Z){let Q=W.dedupeKey??W.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(V){let B=iP(V.scheduledFor,TA(Z,J)),H=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:W.eventId,scheduledFor:B});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:OA(Z,j)}))return{reason:"dedupe_window"};let X=$.cooldownSeconds??0;if(X>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:OA(Z,X)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:W.eventId,scheduledFor:J>0?TA(Z,J):Z}),reason:"dedupe_window"}}}import{existsSync as KS,readdirSync as FS,readFileSync as AS,statSync as US}from"node:fs";import{relative as fS}from"node:path";import{resolveCronSpecsDir as DS}from"@cline/shared/storage";import{createHash as sP}from"node:crypto";import tP from"yaml";function eP($){let W=$.replace(/\\/g,"/");if(W.startsWith("events/")&&W.endsWith(".event.md"))return"event";if(W.endsWith(".cron.md"))return"schedule";return"one_off"}function $S($){let W=$.replace(/\r\n/g,`
499
+ `);if(Z<0)break;let J=this.buffer.slice(0,Z).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!J)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(J[1],10),X=Z+4,Y=X+j;if(this.buffer.length<Y)break;W.push(this.buffer.slice(X,Y)),this.buffer=this.buffer.slice(Y)}return W}}class Fj{buffer="";decoder=new YA("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`
500
+ `);if(Z<0)break;let Q=this.buffer.slice(0,Z).trim();if(this.buffer=this.buffer.slice(Z+1),Q.length>0)W.push(Q)}return W}}class VA{registration;process;nextRequestId=1;pending=new Map;framedParser=new Kj;newlineParser=new Fj;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"],W;for(let Z of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Z);try{await this.request("initialize",{protocolVersion:fP,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},TP),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Z;return}catch(Q){W=Q instanceof Error?Q:Error(String(Q))}}throw W??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((W)=>typeof W?.name==="string"&&typeof W.inputSchema==="object"&&W.inputSchema!==null).map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let W=this.registration.transport;if(W.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${W.type}`);this.framedParser=new Kj,this.newlineParser=new Fj,this.stderrBuffer="",this.protocolMode=$;let Z=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=DP(W.command,W.args??[],{cwd:W.cwd,env:{...process.env,...W.env??{}},stdio:["pipe","pipe","pipe"],...Z});this.process=Q,Q.stdout.on("data",(J)=>this.handleStdout(J)),Q.stderr.on("data",(J)=>{if(this.process!==Q)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(J)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${KQ(J)}`))}),Q.once("exit",(J,j)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let X=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${j??"null"}).${X}`))})}handleStdout($){try{let W=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Z of W){let Q=JSON.parse(Z);if(typeof Q.id!=="number")continue;let J=this.pending.get(Q.id);if(!J)continue;if(this.pending.delete(Q.id),clearTimeout(J.timeout),Q.error){let j=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;J.reject(Error(j));continue}J.resolve(Q.result)}}catch(W){this.handleProtocolFailure(W)}}handleProtocolFailure($){let W=this.process;if(!W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${KQ($)}.${Z}`)),W.kill()}async request($,W,Z=LP){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,j={jsonrpc:"2.0",id:J,method:$,...W?{params:W}:{}},X=new Promise((Y,V)=>{let B=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Z);this.pending.set(J,{resolve:Y,reject:V,timeout:B})});try{Q.stdin.write(this.protocolMode==="framed"?jA(j):XA(j))}catch(Y){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw Y}return X}notify($,W){let Z=this.process;if(!Z?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...W?{params:W}:{}};Z.stdin.write(this.protocolMode==="framed"?jA(Q):XA(Q))}failAllPending($){for(let[W,Z]of this.pending)clearTimeout(Z.timeout),this.pending.delete(W),Z.reject($)}}class BA{registration;options;client;authContext;constructor($,W){this.registration=$;this.options=W}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 $=HQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??JA});this.authContext=$;try{let W=new _P({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Z=BQ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await W.connect(Z),await $.clearError(),this.client=W}catch(W){let Z=W instanceof QA?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):KQ(W);throw await $.markError(Z),Error(Z)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema&&typeof Z.inputSchema==="object"&&!Array.isArray(Z.inputSchema)?Z.inputSchema:{}}))}catch(W){return await this.handleOperationError(W)}}async callTool($){let W=await this.ensureConnectedClient();try{return await W.callTool({name:$.name,arguments:$.arguments??{}})}catch(Z){return await this.handleOperationError(Z)}}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 W=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${W} Run authorizeMcpServerOAuth for this server.`;return`${W} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let W=this.authContext??HQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??JA}),Z=$ instanceof QA?this.formatUnauthorizedMessage(W.getLastAuthorizationUrl()):KQ($);throw await W.markError(Z),Error(Z)}}function z6($={}){return(W)=>W.transport.type==="stdio"?new VA(W):new BA(W,$)}VQ();function e0(){return Date.now()}function OP($){return $.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}class a2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let W=this.servers.get($.name);if(!W){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:e0()});return}let Z=JSON.stringify(W.registration.transport)!==JSON.stringify($.transport);if(W.registration={...$},W.updatedAt=e0(),Z)await this.disconnectState(W),W.client=void 0,W.toolCache=void 0,W.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.connectState(W)})}async disconnectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W)})}async setServerDisabled($,W){await this.runExclusive($,async()=>{let Z=this.requireServer($);if(Z.registration={...Z.registration,disabled:W},Z.updatedAt=e0(),W)await this.disconnectState(Z)})}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(($,W)=>$.name.localeCompare(W.name))}async listTools($){let W=this.requireServer($),Z=W.toolCacheUpdatedAt??0;if(W.toolCache&&e0()-Z<=this.toolsCacheTtlMs)return W.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let W=this.requireServer($),Q=await(await this.ensureConnectedClient(W)).listTools(),J=OP(Q);return W.toolCache=J,W.toolCacheUpdatedAt=e0(),W.updatedAt=e0(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let W=this.requireServer($.serverName),Z=await this.ensureConnectedClient(W);return W.updatedAt=e0(),Z.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let W of $)await this.unregisterServer(W)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=e0();try{let W=$.client??await this.clientFactory($.registration);await W.connect(),$.client=W,$.status="connected",$.lastError=void 0,$.updatedAt=e0()}catch(W){throw $.status="disconnected",$.lastError=W instanceof Error?W.message:String(W),$.updatedAt=e0(),W}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=e0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=e0()}}requireServer($){let W=this.servers.get($);if(!W)throw Error(`Unknown MCP server: ${$}`);return W}async runExclusive($,W){let Z=this.operationLocks.get($)??Promise.resolve(),Q,J=new Promise((X)=>{Q=X}),j=Z.catch(()=>{return}).then(()=>J);this.operationLocks.set($,j),await Z.catch(()=>{return});try{return await W()}finally{if(Q?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function q6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function HA($){return q6($)&&Object.values($).every((W)=>typeof W==="string")}function zP($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function qP($){if(!q6($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function MP($){let W=$.env?Object.entries($.env):[];if(W.length===0)return{ok:!0};let Z={};for(let[Q,J]of W){if(typeof J==="string"){Z[Q]=J;continue}let j=J.fromEnv?.trim()||Q,X=process.env[j];if(typeof X==="string"&&X.length>0){Z[Q]=X;continue}if(typeof J.value==="string"){Z[Q]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Z).length>0?Z:void 0}}function Aj($){if(!q6($))return{name:"",loadError:"invalid MCP server registration"};let W=typeof $.name==="string"?$.name.trim():"";if(!W)return{name:W,loadError:"empty MCP server name"};let Z=$.env,Q=Z===void 0?void 0:Z;if(Q!==void 0){if(!q6(Q))return{name:W,loadError:"invalid env"};for(let[V,B]of Object.entries(Q))if(typeof B!=="string"&&!qP(B))return{name:W,loadError:`invalid env "${V}"`}}let J=$.transport;if(!q6(J))return{name:W,loadError:"invalid MCP transport"};let j=J.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:W,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Q!==void 0)return{name:W,loadError:"top-level env is only supported for stdio MCP transports"};let X=q6($.metadata)?$.metadata:void 0;if(j==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:W,loadError:"stdio MCP transport requires command"};let B=J.args;if(B!==void 0&&!zP(B))return{name:W,loadError:"stdio MCP transport args must be strings"};let H=J.cwd;if(H!==void 0&&typeof H!=="string")return{name:W,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!HA(G))return{name:W,loadError:"stdio MCP transport env must be strings"};let K=MP({name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:G},env:Q,metadata:X});if(!K.ok)return{name:W,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:W,registration:{name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:F},metadata:X}}}if(typeof J.url!=="string"||!J.url.trim())return{name:W,loadError:`${j} MCP transport requires url`};let Y=J.headers;if(Y!==void 0&&!HA(Y))return{name:W,loadError:`${j} MCP transport headers must be strings`};return{name:W,registration:{name:W,transport:j==="sse"?{type:"sse",url:J.url,headers:Y}:{type:"streamableHttp",url:J.url,headers:Y},metadata:X}}}function FQ($){let W=new Map;return $.map(({server:Z,owner:Q,ownerLabel:J})=>{let j=Aj(Z);if(!j.registration)return{owner:Q,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let X=W.get(j.registration.name);if(W.has(j.registration.name)){let Y=X?` already registered by ${X}`:"";return{owner:Q,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${Y}`}}return W.set(j.registration.name,J),{owner:Q,name:j.registration.name,registration:j.registration}})}import{createHash as RP}from"node:crypto";var GA=64,EP=/[^a-zA-Z0-9_-]+/g,KA=8,NP=1,wP="mcp_tool";function CP($){return RP("sha1").update($).digest("hex").slice(0,KA)}function PP($){return $.replace(EP,"_")}var AQ=({serverName:$,toolName:W})=>{let Z=`${$}__${W}`,Q=PP(Z);if(Q===Z&&Z.length<=GA)return Z;let J=CP(Z),j=GA-NP-KA;return`${Q.slice(0,j)||wP}_${J}`};function a5($){return{[($.nameTransform??AQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function UQ($){let W={};for(let Z of $.toolNames)Object.assign(W,a5({serverName:$.serverName,toolName:Z,nameTransform:$.nameTransform}));return W}import{createTool as SP}from"@cline/shared";function bP($,W){let Z=W.description?.trim();if(Z)return Z;return`Execute MCP tool "${W.name}" from server "${$}".`}async function M6($){let W=await $.provider.listTools($.serverName),Z=$.nameTransform??AQ;return W.map((Q)=>{let J=Z({serverName:$.serverName,toolName:Q.name});return SP({name:J,description:bP($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,X)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:X})})})}X1();var DA={};w(DA,{listPluginToolsWithDiagnostics:()=>DQ,listPluginTools:()=>o5});import{stat as yP}from"node:fs/promises";import{isAbsolute as hP,relative as kP,resolve as AA}from"node:path";X1();function IP($,W){let Z=kP(AA($),AA(W));return Z===""||!Z.startsWith("..")&&!hP(Z)}var xP=32,R6=new Map;function gP($,W){if(!R6.has($)&&R6.size>=xP){let Z=R6.keys().next().value;if(Z)R6.delete(Z)}R6.set($,W)}async function mP($){let W=await Promise.all($.pluginPaths.map(async(Z)=>{try{let Q=await yP(Z);return`${Z}:${Q.mtimeMs}:${Q.size}`}catch{return`${Z}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:W})}function UA($,W){return $.map((Z)=>({...Z,enabled:!W.has(Z.name)}))}function vP($){return $.sort((W,Z)=>{let Q=W.name.localeCompare(Z.name);if(Q!==0)return Q;return W.path.localeCompare(Z.path)})}async function cP($,W){if(!$.setup)return{tools:[]};let Z=[],Q={registerTool:(J)=>Z.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Q,{workspaceInfo:W}),{tools:Z}}async function DQ($){let W=Q$({workspacePath:$.workspacePath,cwd:$.cwd}),Z=L1($.disabledToolNames);if(W.length===0)return{tools:[],failures:[],warnings:[]};let Q=await mP({pluginPaths:W,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=R6.get(Q);if(J)return{tools:UA(J.tools,Z),failures:J.failures,warnings:J.warnings};let j=[],X=[],Y=[],V;try{V=await j6({pluginPaths:W,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),X=[...V.failures],Y=[...V.warnings];for(let H of V.extensions??[]){let G=H.__clinePluginPath;if(!G)continue;let K=IP($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await cP(H,{rootPath:$.workspacePath})}catch(A){X.push({pluginPath:G,pluginName:H.name,phase:"setup",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0});continue}for(let A of F.tools)j.push({name:A.name,pluginName:H.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(H){X=W.map((G)=>({pluginPath:G,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let B=vP(j);return gP(Q,{tools:B,failures:X,warnings:Y}),{tools:UA(B,Z),failures:X,warnings:Y}}async function o5($){return(await DQ($)).tools}function e5($,W){if(!W)return"global";let Z=OA(W,$);return!Z.startsWith("..")&&!TA(Z)?"workspace":"global"}function pP($,W){return e5($,W)==="workspace"?"workspace-plugin":"global-plugin"}function rP($,W){let Z=OA(fA($),fA(W));return Z===""||!Z.startsWith("..")&&!TA(Z)}function iP($){try{let W=JSON.parse(uP($,"utf8"));return typeof W.name==="string"&&W.name.trim()?W.name.trim():void 0}catch{return}}function nP($){let W=_A($);while(!0){let Z=lP(W,"package.json");if(t5(Z)){let J=iP(Z);if(J)return J;break}let Q=_A(W);if(Q===W)break;W=Q}return Uj($,dP($))}function aP($){let W=[];for(let Z of Q$({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let Q of J$([Z]))W.push({directory:Q,pluginName:nP(Z),pluginPath:Z,source:$.workspaceRoot?pP(Z,$.workspaceRoot):"global-plugin"});return W.sort((Z,Q)=>Q.directory.length-Z.directory.length)}function oP($,W){return W.find((Z)=>rP(Z.directory,$))}function s5($){return[...$].sort((W,Z)=>{let Q=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(W.source!==Z.source)return Q(W.source)-Q(Z.source);return W.name.localeCompare(Z.name)})}function zA($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function qA($,W){return $.cwd?.trim()||W||process.cwd()}async function LA($,W){if($.userInstructionService)return await W($.userInstructionService);let Z=zA($),Q=qA($,Z),J=c$({skills:{workspacePath:Z||void 0,includePluginSkills:!0,cwd:Q},rules:{workspacePath:Z||void 0},workflows:{workspacePath:Z||void 0}});try{return await J.start(),await W(J)}finally{J.stop()}}function sP($,W){if(!$)return;let Z=$.listRecords("skill");if(W.id){let Q=Z.find((J)=>J.id===W.id);if(Q)return Q}for(let Q of Z)if(Q.filePath===W.path||Q.item.name===W.name||Q.id===W.name)return Q;return}class l${async list($={}){return await LA($,async(W)=>{let Z=zA($),Q=aP({workspaceRoot:Z,cwd:qA($,Z)}),J=[],j=[],X=[],Y=[],V=[];if(W){for(let H of W.listRecords("workflow")){let G=H.item;J.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"workflow",source:e5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("rule")){let G=H.item;j.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"rule",source:e5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("skill")){let G=H.item,K=oP(H.filePath,Q);X.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??e5(H.filePath,Z),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Z)try{for(let H of await o5({workspacePath:Z,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))Y.push({id:`${H.pluginName}:${H.name}:${H.path}`,name:H.name,path:H.path,enabled:H.enabled,kind:"tool",source:H.source,description:H.description,toggleable:!0})}catch{}let B=J0();if(X$({filePath:B}))try{for(let H of t0({filePath:B}))V.push({id:H.name,name:H.name,path:B,enabled:H.disabled!==!0,kind:"mcp",source:e5(B,Z),description:H.transport.type,toggleable:!0})}catch{}return{workflows:s5(J.filter((H)=>t5(H.path))),rules:s5(j.filter((H)=>t5(H.path))),skills:s5(X.filter((H)=>t5(H.path))),tools:s5(Y),mcp:s5(V.filter((H)=>t5(H.path)))}})}async toggle($){if($.type==="skills")return await LA($,async(W)=>{let Z=sP(W,$),Q=Z?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??Uj($.path??"")}'.`);let J=Z?.item&&"disabled"in Z.item?Z.item.disabled!==!0:void 0,j=$.enabled??(J!==void 0?!J:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??Uj($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await gF({filePath:Q,enabled:j}),await W?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:W}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)UW($.name);else kV($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let W=$.name?.trim()||$.id?.trim();if(!W)throw Error("MCP server settings toggle requires a server name.");let Z=$.path?.trim()||J0(),Q=$.enabled;if(Q===void 0){let J=t0({filePath:Z}).find((j)=>j.name===W);if(!J)throw Error(`Unknown MCP server: ${W}`);Q=J.disabled===!0}return p2({filePath:Z,name:W,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function o2(){return new l$}function RA($){return{async list(W){let Z=$;if(Z.listSettings)return await Z.listSettings(W);return await o2().list(W)},async toggle(W){let Z=$;if(Z.toggleSetting)return await Z.toggleSetting(W);return await o2().toggle(W)}}}function EA($){function W(){let Z=$.pendingPrompts;if(!Z)throw Error("Pending prompt service is not available.");return Z}return{list(Z){return W().list(Z)},update(Z){return W().update(Z)},delete(Z){return W().delete(Z)}}}function NA($){let W=$.config;return"providerId"in W?{...$,config:{...W,...tP($.localRuntime)},localRuntime:$.localRuntime}:$}function Dj($,W={}){let Z=D4($.config),Q=P0(W.defaultCapabilities,$.capabilities),J=eP(Z.localRuntime,$.localRuntime),j=W.withExtensionContext?.(J?.extensionContext);if(j)J={...J??{},extensionContext:j};return{...$,...Z,...J?{localRuntime:J}:{},...Q?{capabilities:Q}:{}}}function tP($){if(!$)return{};let{modelCatalogDefaults:W,userInstructionService:Z,configExtensions:Q,onTeamRestored:J,...j}=$;return j}function eP(...$){let W={};for(let Z of $)if(Z)Object.assign(W,Z);return Object.keys(W).length>0?W:void 0}R0();function wA($){let W=$.input.config.telemetry??$.telemetry;if(!W)return;W.capture({event:v.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??F0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function $9($){return!!$&&typeof $==="object"&&!Array.isArray($)}function _j($){let W=$?.trim();return W?W:void 0}function $S($,W){let Z=$?.trim();if(!Z)return W;let Q=Date.parse(Z);if(!Number.isFinite(Q))return W;return new Date(Q).toISOString()}function CA($,W){return new Date(new Date($).getTime()+Math.max(0,Math.floor(W))*1000).toISOString()}function PA($,W){return new Date(new Date($).getTime()-Math.max(0,Math.floor(W))*1000).toISOString()}function WS($,W){if(!$)return W;return new Date($).getTime()>=new Date(W).getTime()?$:W}function ZS($,W){let Z=$.eventId.trim(),Q=$.eventType.trim(),J=$.source.trim(),j=_j($.subject),X=_j($.dedupeKey)??`${Q}:${J}:${j??Z}`;return{eventId:Z,eventType:Q,source:J,subject:j,occurredAt:$S($.occurredAt,W),workspaceRoot:_j($.workspaceRoot),payload:$9($.payload)?$.payload:void 0,attributes:$9($.attributes)?$.attributes:void 0,dedupeKey:X}}function fj($,W){if(!W)return;let Z=W.split("."),Q=$;for(let J of Z){if(!$9(Q))return;Q=Q[J]}return Q}function QS($,W){if($.attributes&&Object.hasOwn($.attributes,W))return $.attributes[W];if($.payload&&Object.hasOwn($.payload,W))return $.payload[W];let Z={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=fj(Z,W);if(Q!==void 0)return Q;if($.attributes){let J=fj($.attributes,W);if(J!==void 0)return J}if($.payload)return fj($.payload,W);return}function _Q($,W){if(Array.isArray(W))return W.some((Z)=>_Q($,Z));if(Array.isArray($))return $.some((Z)=>_Q(Z,W));if($9(W)){if(!$9($))return!1;return Object.entries(W).every(([Z,Q])=>_Q($[Z],Q))}return Object.is($,W)}function JS($,W){if(!W||Object.keys(W).length===0)return!0;return Object.entries(W).every(([Z,Q])=>_Q(QS($,Z),Q))}class Lj{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let W=new Date(this.nowFn()).toISOString(),Z=ZS($,W),Q=this.store.insertEventLog(Z,{receivedAtIso:W});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Z.eventType),j=[],X=[],Y=[];for(let H of J){if(!JS(Z,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Z.dedupeKey});continue}X.push(H);let G=this.materializeForSpec(H,Z,Q.record.receivedAt);if(G.run)Y.push(G.run);else j.push({specId:H.specId,externalId:H.externalId,reason:G.reason,dedupeKey:Z.dedupeKey})}let V=X.length===0?"unmatched":Y.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:V,matchedSpecCount:X.length,queuedRunCount:Y.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let B=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:V,matchedSpecCount:X.length,queuedRunCount:Y.length}),{event:B??Q.record,duplicate:!1,matchedSpecs:X,queuedRuns:Y,suppressions:j}}catch(J){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:J});throw J}}materializeForSpec($,W,Z){let Q=W.dedupeKey??W.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(V){let B=WS(V.scheduledFor,CA(Z,J)),H=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:W.eventId,scheduledFor:B});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:PA(Z,j)}))return{reason:"dedupe_window"};let X=$.cooldownSeconds??0;if(X>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:PA(Z,X)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:W.eventId,scheduledFor:J>0?CA(Z,J):Z}),reason:"dedupe_window"}}}import{existsSync as TS,readdirSync as OS,readFileSync as zS,statSync as qS}from"node:fs";import{relative as MS}from"node:path";import{resolveCronSpecsDir as RS}from"@cline/shared/storage";import{createHash as jS}from"node:crypto";import XS from"yaml";function YS($){let W=$.replace(/\\/g,"/");if(W.startsWith("events/")&&W.endsWith(".event.md"))return"event";if(W.endsWith(".cron.md"))return"schedule";return"one_off"}function VS($){let W=$.replace(/\r\n/g,`
501
501
  `);if(!W.startsWith(`---
502
502
  `))return{frontmatter:void 0,body:$};let Z=W.slice(4),Q=Z.indexOf(`
503
503
  ---`);if(Q===-1)return{frontmatter:void 0,body:$};let J=Z.slice(0,Q),j=Z.slice(Q+4);if(j.startsWith(`
504
- `))j=j.slice(1);return{frontmatter:J,body:j}}function $1($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function WS($){if(!Array.isArray($))return;let W=$.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);return W.length>0?W:void 0}function Dj($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function ZS($){let W=Dj($);if(!W)return;let Z=$1(W.providerId),Q=$1(W.modelId);if(Z===void 0&&Q===void 0)return;return{providerId:Z,modelId:Q}}function QS($){if(typeof $!=="string")return;let W=$.trim().toLowerCase();if(W==="act"||W==="plan"||W==="yolo")return W;return}function qA($,W={}){let Z=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Z)return;let Q=[...new Set(Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&W.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var JS=new Set(U$);function jS($){let W=qA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!JS.has(Q));if(Z.length>0)throw Error(`unknown tool(s): ${Z.join(", ")}`);return W}var XS=new Set(["rules","skills","plugins"]);function YS($){let W=qA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!XS.has(Q));if(Z.length>0)throw Error(`unknown extension(s): ${Z.join(", ")}`);return W}function Uj($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function fj($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function _j($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Z)=>_j(Z)).join(",")}]`;let W=Object.entries($).filter(([,Z])=>Z!==void 0);return W.sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0),`{${W.map(([Z,Q])=>`${JSON.stringify(Z)}:${_j(Q)}`).join(",")}}`}function MA($,W){let Z=sP("sha256");return Z.update(_j($)),Z.update(`
505
- `),Z.update(W),Z.digest("hex")}function VS($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var BS=["schedule","timezone"],HS=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],GS=["cwd"];function zA($,W,Z,Q,J){return{externalId:$,relativePath:$,triggerKind:W,body:Z,contentHash:MA(Q,Z),error:J}}function N1($,W,Z,Q,J,j){return{externalId:$,relativePath:W,triggerKind:Z,body:Q,contentHash:J,error:j}}function RA($){let W=$.relativePath.replace(/\\/g,"/"),Z=eP(W),{frontmatter:Q,body:J}=$S($.raw),j={};if(Q!==void 0&&Q.trim().length>0)try{let D=tP.parse(Q);if(D&&typeof D==="object"&&!Array.isArray(D))j=D;else if(D!==null&&D!==void 0)return zA(W,Z,J,{},"frontmatter must be a YAML mapping")}catch(D){return zA(W,Z,J,{},D instanceof Error?`failed to parse frontmatter: ${D.message}`:"failed to parse frontmatter")}let X=MA(j,J),Y=$1(j.id),V=Y??W;if(Z!=="schedule"){for(let D of BS)if(j[D]!==void 0)return N1(V,W,Z,J,X,`field "${D}" is only allowed on *.cron.md specs`)}for(let D of GS)if(j[D]!==void 0)return N1(V,W,Z,J,X,`field "${D}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Z!=="event"){for(let D of HS)if(j[D]!==void 0)return N1(V,W,Z,J,X,`field "${D}" is only allowed on .event.md specs`)}let B=$1(j.prompt),H=J.trim(),G=B??(H.length>0?H:void 0);if(!G)return N1(V,W,Z,J,X,"prompt is required (frontmatter `prompt` or markdown body)");let K=$1(j.workspaceRoot);if(!K)return N1(V,W,Z,J,X,"workspaceRoot is required");let F,A;try{F=jS(j.tools),A=YS(j.extensions)}catch(D){return N1(V,W,Z,J,X,D instanceof Error?D.message:String(D))}let f=QS(j.mode);if(j.mode!==void 0&&f===void 0)return N1(V,W,Z,J,X,"mode must be one of: act, plan, yolo");let U={id:Y,title:$1(j.title)??Y??VS(W),prompt:G,workspaceRoot:K,mode:f??"yolo",systemPrompt:$1(j.systemPrompt),modelSelection:ZS(j.modelSelection),maxIterations:Uj(j.maxIterations),timeoutSeconds:Uj(j.timeoutSeconds),tools:F,notesDirectory:$1(j.notesDirectory),extensions:A,source:$1(j.source)??"user",tags:WS(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:Dj(j.metadata)},_;if(Z==="schedule"){let D=$1(j.schedule);if(!D)return N1(V,W,Z,J,X,"schedule is required for *.cron.md specs");let M=$1(j.timezone);try{WV(D,M)}catch(T){return N1(V,W,Z,J,X,T instanceof Error?T.message:String(T))}_={...U,triggerKind:"schedule",schedule:D,timezone:M}}else if(Z==="event"){let D=$1(j.event);if(!D)return N1(V,W,Z,J,X,"event is required for .event.md specs");_={...U,triggerKind:"event",event:D,filters:Dj(j.filters),debounceSeconds:fj(j.debounceSeconds),dedupeWindowSeconds:fj(j.dedupeWindowSeconds),cooldownSeconds:fj(j.cooldownSeconds),maxParallel:Uj(j.maxParallel)}}else _={...U,triggerKind:"one_off"};return{externalId:V,relativePath:W,triggerKind:Z,body:J,contentHash:X,spec:_}}function _S($,W){return fS($,W).replace(/\\/g,"/")}function LS($){if(!KS($))return[];let W=[],Z=[$];while(Z.length>0){let Q=Z.pop();if(!Q)continue;let J;try{J=FS(Q,{withFileTypes:!0})}catch{continue}for(let j of J){let X=`${Q}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Z.push(X);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;W.push(X)}}return W}class Lj{store;cronDir;constructor($){this.store=$.store,this.cronDir=DS($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},W=LS(this.cronDir),Z=new Set;for(let J of W){let j=_S(this.cronDir,J);Z.add(j),$.scanned+=1;let X=await this.reconcileFile(j,J);if(X){if($.changes.push(X),$.upserted+=1,X.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of Q)if(!Z.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,W){let Z=this.store.getSpecBySourcePath($),Q,J;try{Q=AS(W,"utf8"),J=US(W).mtimeMs}catch{return}let X=RA({relativePath:$,raw:Q}),Y=this.store.upsertSpec({externalId:X.externalId,sourcePath:$,triggerKind:X.triggerKind,sourceMtimeMs:J,sourceHash:X.contentHash,parseStatus:X.error?"invalid":"valid",parseError:X.error,spec:X.spec});if(!X.error&&X.triggerKind==="schedule"&&Y.record.enabled)this.applyScheduleNextRunAt(Y.record,{forceReset:!Z||Z.removed||!Z.enabled||Z.scheduleExpr!==Y.record.scheduleExpr||Z.timezone!==Y.record.timezone});return{relativePath:$,result:Y,parse:X}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of $)this.applyScheduleNextRunAt(W,{forceReset:!1})}applyScheduleNextRunAt($,W){if(!$.scheduleExpr)return;if(!W.forceReset&&$.nextRunAt)return;try{let Z=Date.now(),Q=$.lastRunAt?Math.max(Z,new Date($.lastRunAt).getTime()):Z,J=Z2($.scheduleExpr,Q,$.timezone),j=new Date(J).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as TS,mkdirSync as OS,watch as zS}from"node:fs";import{relative as qS,resolve as MS}from"node:path";var RS=250;class Tj{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??RS),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{OS($,{recursive:!0}),this.watcher=zS($,{recursive:!0},(W,Z)=>{if(!Z)return;let Q=String(Z).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(W){this.onError(W)}}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 W=this.pending.get($);if(W)clearTimeout(W);let Z=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Z)}async reconcileNow($){try{let W=MS(this.reconciler.getCronDir(),$);if(!TS(W)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Z=qS(this.reconciler.getCronDir(),W).replace(/\\/g,"/");await this.reconciler.reconcileFile(Z,W),await this.onReconciled()}catch(W){this.onError(W)}}}class e5{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new J4({dbPath:$.dbPath});let W=$.specs;this.reconciler=new Lj({store:this.store,specs:W}),this.materializer=new s6({store:this.store}),this.eventIngress=new Aj({store:this.store,logger:$.logger}),this.runner=new $4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:W,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new Tj({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Z)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:Z});else Q.log("cron.watcher.failed",{error:Z})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var bA={};w(bA,{manifestToSessionRecord:()=>HQ,listSessionHistoryFromBackend:()=>Mj,listSessionHistory:()=>GQ,hydrateSessionHistory:()=>SA});import{readdir as wS,readFile as wA}from"node:fs/promises";import{join as CA}from"node:path";import{formatDisplayUserInput as CS,normalizeUserInput as PS}from"@cline/shared";import{resolveSessionDataDir as PA}from"@cline/shared/storage";import{existsSync as NS}from"node:fs";import{readFile as ES}from"node:fs/promises";class $W{listeners=new Set;subscribe($,W){let Z={listener:$,sessionId:W?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let W=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==W)continue;Z.listener($)}}get size(){return this.listeners.size}}async function l$($){let W=$?.trim();if(!W||!NS(W))return[];try{let Z=(await ES(W,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function Oj($){return $?{...$}:void 0}async function NA($,W){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await W.queueSpawnRequest($);let Q=await W.upsertSubagentSessionFromHook($);if(!Q)return;await W.appendSubagentHookAudit(Q,$),await W.applySubagentStatus(Q,$)}function WW($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function W1($){let W=WW($);if(!W)return;return W.toLowerCase()==="unknown"?void 0:W}function BQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function SS($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function qj($){let W=$??200;return Number.isFinite(W)?Math.max(0,Math.floor(W)):200}function bS($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function yS($){return $.isSubagent!==!0&&!WW($.parentSessionId)}function hS($){let W=$.match(/\d{13,}/g);if(!W||W.length===0)return 0;let Z=0;for(let Q of W){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function HQ($){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 kS($){let W=qj($);if(W===0)return[];let Z=PA(),J=(await wS(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:hS(X.name.trim())})).sort((X,Y)=>Y.recency-X.recency||Y.entry.name.localeCompare(X.entry.name));return(await Promise.all(J.map(async({entry:X})=>{let Y=X.name.trim();if(!Y)return;let V=CA(Z,Y,`${Y}.json`),B=await wA(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=g0.safeParse(H);if(!G.success)return;return HQ(G.data)}))).filter((X)=>Boolean(X)).sort((X,Y)=>Y.startedAt.localeCompare(X.startedAt)).slice(0,W)}async function IS($,W,Z){let Q=qj(W);if(Q===0)return await $.listSessions(0),[];let J=Z.includeSubagents?Q:bS(Q),j=await $.listSessions(J);return(Z.includeSubagents?j:j.filter(yS)).slice(0,Q)}function xS($){if(typeof $==="string")return $.trim();let W=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)W.push(J)}return W.join(`
506
- `).trim()}function EA($){return $.replace(/\s+/g," ").trim()}function gS($,W){if($.length<=W)return $;return`${$.slice(0,Math.max(0,W-3)).trimEnd()}...`}function mS($){for(let W of["user","assistant"])for(let Z of $){if(Z.role!==W)continue;let Q=EA(xS(Z.content));if(!Q)continue;let J=W==="user"?EA(CS(Q)):Q,j=PS(J.split(`
507
- `)[0]??J);return gS(j,50)}return}function vS($){let W=0;for(let Z of $)W+=BQ(Z.metrics?.cost)??0;return W}function cS($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=W1(J.modelInfo?.provider);if(!Z)Z=W1(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function uS($){return W1($?.provider)??W1($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function dS($){return W1($?.model)??W1($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function zj($,W){let Z=SS($.metadata),Q=WW(W?.title)??WW(Z?.title),J=BQ(W?.totalCost)??BQ(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:W1(W?.provider)??W1($.provider)??uS(Z)??"",model:W1(W?.model)??W1($.model)??dS(Z)??"",metadata:j}}function lS($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function pS($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!lS(Z)}async function rS($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return pS(Z,Q)?{...Z,status:"idle"}:Z}))}async function SA($,W){return await Promise.all(W.map(async(Z)=>{let Q=zj(Z),J=Boolean(WW(Q.metadata?.title)),j=Boolean(W1(Q.provider)),X=Boolean(W1(Q.model)),Y=BQ(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=cS(B),G=vS(B);return zj(Z,{title:J?void 0:mS(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function GQ($,W={}){let Z=qj(W.limit),Q=W.includeSubagents===!0,J=await IS($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await kS(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await rS($,Y);if(W.hydrate===!1)return V.map((B)=>zj(B));return await SA($,V)}async function iS($){let W=$.trim();if(!W)return;let Z=CA(PA(),W,`${W}.json`),Q=await wA(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=g0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function Mj($,W={}){let Z=new Map;return await GQ({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(V5)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await iS(J);return await l$(j)}},W)}var qU={};w(qU,{resolveSessionBackend:()=>pj,createRuntimeHost:()=>b6});import{captureSdkError as OU}from"@cline/shared";var pA={};w(pA,{HubRuntimeHost:()=>X$});import{resolveProviderRequestHeaders as sS}from"@cline/llms";import{captureSdkError as Rj,createSessionId as hA,HUB_CHECKPOINT_CAPABILITY as tS,HUB_COMPACTION_CAPABILITY as eS,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as $b,HUB_HOOK_CAPABILITY_PREFIX as Wb,HUB_MISTAKE_LIMIT_CAPABILITY as Zb,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Qb,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Jb,isHubToolExecutorName as jb}from"@cline/shared";var yA={};w(yA,{createCoreSessionSnapshot:()=>E1,coreSessionSnapshotToRecord:()=>KQ});function nS($){return $?JSON.parse(JSON.stringify($)):void 0}function aS($){return $?JSON.parse(JSON.stringify($)):void 0}function oS($){let W=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(W?.history)?W.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let Y=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!Y||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:Y,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),J=Q.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Q.length===0)return;return{...j?{enabled:j}:{},...J?{latest:J}:{},history:Q}}function E1($){let{session:W}=$,Z=nS(W.metadata);return{version:1,sessionId:W.sessionId,source:W.source,status:W.status,createdAt:W.startedAt,updatedAt:W.updatedAt,endedAt:W.endedAt??null,exitCode:W.exitCode??null,interactive:W.interactive,workspace:{cwd:W.cwd,root:W.workspaceRoot},model:{providerId:W.provider,modelId:W.model},capabilities:{enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams},lineage:{...W.parentSessionId?{parentSessionId:W.parentSessionId}:{},...W.parentAgentId?{parentAgentId:W.parentAgentId}:{},...W.agentId?{agentId:W.agentId}:{},...W.conversationId?{conversationId:W.conversationId}:{},isSubagent:W.isSubagent},...W.teamName?{team:{name:W.teamName}}:{},...W.prompt?{prompt:W.prompt}:{},...Z?{metadata:Z}:{},...W.messagesPath?{artifacts:{messagesPath:W.messagesPath}}:{},...$.messages?{messages:aS($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=oS(Z);return Q?{checkpoint:Q}:{}})()}}function KQ($){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 M6($){if(!$)return;return JSON.parse(JSON.stringify($))}var Xb=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function kA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function IA($){if(!$)return;let{userInstructionService:W,...Z}=$;return JSON.parse(JSON.stringify(Z))}function xA($,W){let Z={...$.config,sessionId:W},Q=sS({providerId:$.config.providerId,sessionId:W,source:$.source,defaultSource:F0.CORE,client:{name:$.localRuntime?.extensionContext?.client?.name,version:$.localRuntime?.extensionContext?.client?.version,versionHeaderFallback:$.config.headers?.["X-CLIENT-VERSION"],platform:$.localRuntime?.extensionContext?.client?.platform,platformVersion:$.localRuntime?.extensionContext?.client?.platformVersion,isMultiRoot:$.localRuntime?.extensionContext?.client?.isMultiRoot},coreVersion:q8,openAiCodex:{accessToken:$.config.apiKey,userAgentVersion:process.env.npm_package_version},headers:{config:$.config.headers}});if(Q)Z.headers=Q;return Z}function gA($){let W=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof W.agentId==="string"?W.agentId:"",conversationId:typeof W.conversationId==="string"?W.conversationId:"",iteration:typeof W.iteration==="number"?W.iteration:0,metadata:W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0}}function o2($,W,Z){$.manifest.push(W),$.handlers.set(W.capabilityName,Z)}function mA($,W){let Z={manifest:[],handlers:new Map};for(let J of Object.keys(W.toolExecutors??{}).filter(jb)){let j=W.toolExecutors?.[J];if(typeof j!=="function")continue;o2(Z,{kind:"toolExecutor",executor:J,capabilityName:`${Qb}${J}`},async({payload:X,abortSignal:Y})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...gA(X.context),signal:Y};return{result:await j(...V,B)}})}for(let J of $?.extraTools??[])o2(Z,{kind:"tool",name:J.name,description:J.description,inputSchema:M6(J.inputSchema)??{},...J.lifecycle?{lifecycle:M6(J.lifecycle)}:{},capabilityName:`${$b}${J.name}`},async({payload:j,abortSignal:X,progress:Y})=>{let V={...gA(j.context),signal:X};return{result:await J.execute(j.input,{...V,emitUpdate:(H)=>{Y({update:H})}})}});let Q=$?.hooks;if(Q)for(let J of Xb){let j=Q[J];if(typeof j!=="function")continue;o2(Z,{kind:"hook",name:J,capabilityName:`${Wb}${J}`},async({payload:X})=>({control:await j(X.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;o2(Z,{kind:"compaction",capabilityName:eS,config:kA($.compaction)},async({payload:j})=>({result:await J(j.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;o2(Z,{kind:"checkpoint",capabilityName:tS,config:kA($.checkpoint)},async({payload:j})=>({result:await J(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;o2(Z,{kind:"mistakeLimit",capabilityName:Zb},async({payload:j})=>({result:await J(j.context)}))}if($?.userInstructionService){let J=$.userInstructionService;o2(Z,{kind:"userInstructionService",capabilityName:Jb},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Z}function dA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let W=$.message;if(typeof W==="string"&&W.trim())return W.trim()}return}function Yb($){return dA($)??"Capability request was cancelled."}function Vb($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function Bb($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function Hb($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=typeof W.inputTokens==="number"?W.inputTokens:void 0,Q=typeof W.outputTokens==="number"?W.outputTokens:void 0;if(Z===void 0||Q===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:typeof W.cacheReadTokens==="number"?W.cacheReadTokens:0,cacheWriteTokens:typeof W.cacheWriteTokens==="number"?W.cacheWriteTokens:0,totalCost:typeof W.totalCost==="number"?W.totalCost:0}}function vA($){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 Nj($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function p$($,W){return Nj($?.[W])??0}function Gb($){let W=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:p$(W,"inputTokens"),outputTokens:p$(W,"outputTokens"),cacheReadTokens:p$(W,"cacheReadTokens"),cacheWriteTokens:p$(W,"cacheWriteTokens"),cost:Nj(W?.totalCost),totalInputTokens:p$(Z,"inputTokens"),totalOutputTokens:p$(Z,"outputTokens"),totalCacheReadTokens:p$(Z,"cacheReadTokens"),totalCacheWriteTokens:p$(Z,"cacheWriteTokens"),totalCost:Nj(Z?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:J}}function Kb($){let W=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??W?.finishReason,Q=Bb(Z)?Z:Z==="failed"?"error":"completed",J=Hb($?.usage??W?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof W?.text==="string"?W.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof W?.iterations==="number"?W.iterations:0,usage:J}}function s2($,W){return $.error?.message??`hub command failed: ${W}`}function ZW($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function lA($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof W?.parentSessionId==="string"?W.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof W?.agentId==="string"?W.agentId:void 0),parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,isSubagent:typeof W?.isSubagent==="boolean"?W.isSubagent:!1,source:typeof W?.source==="string"?W.source:F0.CORE,pid:typeof W?.pid==="number"?W.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:ZW($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:ZW($.status)==="completed"?0:ZW($.status)==="failed"?1:void 0,status:ZW($.status),interactive:W?.interactive===!0,provider:typeof W?.provider==="string"?W.provider:"hub",model:typeof W?.model==="string"?W.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof W?.teamName==="string"?W.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??W?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??W?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??W?.enableTeams===!0,prompt:typeof W?.prompt==="string"?W.prompt:void 0,metadata:W,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof W?.messagesPath==="string"?W.messagesPath:void 0,hookPath:typeof W?.hookPath==="string"?W.hookPath:void 0}}function r$($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$;return W.version===1&&typeof W.sessionId==="string"?JSON.parse(JSON.stringify(W)):void 0}function Fb($){let W=r$($?.snapshot);if(W)return KQ(W);let Z=$?.session;return Z?lA(Z):void 0}function cA($,W,Z){let Q=Z?.workspaceRoot?.trim()||W.config.workspaceRoot||W.config.cwd;return g0.parse({version:1,session_id:$,source:W.source??F0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:ZW(Z?.status),interactive:W.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:Z?.cwd?.trim()||W.config.cwd,workspace_root:Q,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,metadata:W.sessionMetadata&&Object.keys(W.sessionMetadata).length>0?W.sessionMetadata:void 0})}function uA($,W){return g0.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??W.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class X${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new $W;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,W){this.clientContext=W,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd},this.defaultCapabilities=C0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new B1({...this.clientOptions,url:$})}async replaceClient($){let W=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(W.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!L9($,"session.create"))return!1;let W=await T9({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!W)return!1;return await this.replaceClient(W),!0}registerPlannedSession($,W,Z){if(this.sessionCapabilities.set($,W),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let W=this.resolveCapabilities($),Z=mA($.localRuntime,W),Q=$.config.sessionId?.trim()||hA(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:M6(xA($,Q)),metadata:{...$.sessionMetadata??{},source:$.source??F0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:M6($.toolPolicies),initialMessages:$.initialMessages,...$.initialCompactionState?{initialCompactionState:$.initialCompactionState}:{}});this.registerPlannedSession(Q,W,Z.handlers);let j;try{j=await J()}catch(B){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(Q,W,Z.handlers);try{j=await J()}catch(H){throw this.cleanupPlannedSession(Q),H}}else throw B}let X=r$(j.payload?.snapshot),Y=j.payload?.session,V=(X?.sessionId??Y?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(V!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(V,W,Z.handlers);return{sessionId:V,manifest:X?uA(X,$):cA(V,$,Y),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,J=Q?this.resolveCapabilities(Q):void 0,j=Q?mA(Q.localRuntime,J??{}):{manifest:[],handlers:new Map},X,Y;if(Q)X=Q.config.sessionId?.trim()||hA(),Y=xA(Q,X);if(X&&J)this.sessionCapabilities.set(X,J);if(X&&j.handlers.size>0)this.sessionClientContributionHandlers.set(X,j.handlers),this.ensureSessionSubscription(X);let V;try{V=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:M6(Y),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:M6(Q.toolPolicies),...Q.initialCompactionState?{initialCompactionState:Q.initialCompactionState}:{}}:{}},W)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!V.ok){let A=typeof V.payload?.error==="string"?V.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let B=r$(V.payload?.snapshot),H=V.payload?.session,G=(B?.sessionId??H?.sessionId)?.trim();if(Z&&!G){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(G&&X&&G!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(G&&J)this.sessionCapabilities.set(G,J);if(G&&j.handlers.size>0)this.sessionClientContributionHandlers.set(G,j.handlers);if(G)this.ensureSessionSubscription(G);let K=Array.isArray(V.payload?.messages)?V.payload.messages:void 0,F=V.payload?.checkpoint;if(!F)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:G,startResult:G?{sessionId:G,manifest:B?uA(B,Q??{}):cA(G,Q??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:K,checkpoint:F}}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 W=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(W.payload?.prompts)?W.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,updated:W.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,removed:W.payload?.removed===!0}}async getAccumulatedUsage($){let W=await this.client.command("session.get",{includeSnapshot:!0},$),Z=r$(W.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,Y=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||Y?{usage:X,aggregateUsage:Y}:void 0}let Q=W.payload?.session,J=vA(Q?.usage),j=vA(Q?.aggregateUsage);return J||j?{usage:J,aggregateUsage:j}:void 0}async abort($,W){await this.client.command("run.abort",{sessionId:$,reason:dA(W)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,W]of this.sessionSubscriptions){W();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 W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(l1(Z))return;throw Z}return Fb(W.payload)}async listSessions($=100){let W=await this.client.command("session.list",{limit:$}),Z=Array.isArray(W.payload?.snapshots)?W.payload.snapshots.flatMap((J)=>{let j=r$(J);return j?[KQ(j)]:[]}):[];if(Z.length>0)return Z;return(W.payload?.sessions??[]).map(lA)}async listSettings($){let W=await this.client.command("settings.list",IA($));if(!W.ok)throw Error(s2(W,"settings.list"));return W.payload?.snapshot}async toggleSetting($){let W=await this.client.command("settings.toggle",IA($));if(!W.ok)throw Error(s2(W,"settings.toggle"));return{snapshot:W.payload?.snapshot,changedTypes:Array.isArray(W.payload?.changedTypes)?W.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,W){let Z={...W.metadata??{}};if(typeof W.prompt==="string")Z.prompt=W.prompt;if(typeof W.title==="string")Z.title=W.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async updateSessionConnection($,W){let Z=$.trim();if(!Z)return;let Q=await this.client.command("session.update_connection",{sessionId:Z,updates:W},Z);if(!Q.ok)throw Error(s2(Q,"session.update_connection"))}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=await this.client.command("session.compaction.update",{sessionId:Z,state:W},Z);if(!Q.ok)Rj(this.telemetry,{component:"core",operation:"hub.runtime_host.update_session_compaction_state",error:Error(s2(Q,"session.compaction.update")),severity:"warn",handled:!0,context:{command:"session.compaction.update",sessionId:Z,errorCode:Q.error?.code}});return{updated:Q.ok&&Q.payload?.updated===!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=await this.client.command("session.compaction.get",{sessionId:W},W);if(!Z.ok)throw Error(s2(Z,"session.compaction.get"));return G1(Z.payload?.state)}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Rj(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(s2(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:W,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(s2(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,W){return this.events.subscribe($,W)}ensureSessionSubscription($){let W=$.trim();if(!W||this.sessionSubscriptions.has(W))return;let Z=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:W});this.sessionSubscriptions.set(W,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let W=$.trim();if(!W)return;this.sessionSubscriptions.get(W)?.(),this.sessionSubscriptions.delete(W),this.agentDoneEmittedForCurrentRunBySession.delete(W)}resolveCapabilities($){return C0(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:Kb($.payload)}})}handleHubEvent($){let W=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!W)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(W);let Z=r$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,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"session.notice":{let Z=$.payload?.noticeType,Q=$.payload?.displayRole,J=$.payload?.reason,j=$.payload?.agent&&typeof $.payload.agent==="object"?$.payload.agent:void 0,X=j?.teamRole==="lead"||j?.teamRole==="teammate"?j.teamRole:void 0;this.events.emit({type:"agent_event",payload:{sessionId:W,...X?{teamRole:X}:{},...typeof j?.teamAgentId==="string"?{teamAgentId:j.teamAgentId}:{},event:{type:"notice",...typeof j?.agentId==="string"?{agentId:j.agentId}:{},...typeof j?.conversationId==="string"?{conversationId:j.conversationId}:{},...typeof j?.parentAgentId==="string"?{parentAgentId:j.parentAgentId}:{},noticeType:Z==="recovery"||Z==="stop"?Z:"status",message:typeof $.payload?.message==="string"?$.payload.message:"",...Q==="system"||Q==="status"?{displayRole:Q}:{},...typeof J==="string"?{reason:J}:{},...$.payload?.metadata&&typeof $.payload.metadata==="object"?{metadata:$.payload.metadata}:{}}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!Z&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:W,payload:$.payload});return}case"usage.updated":{let Z=Gb($.payload);this.events.emit({type:"agent_event",payload:{sessionId:W,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:W,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"tool",toolCallId:Z,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 Z=r$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:W,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:W,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=r$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:W,payload:{...$.payload,reason:Q}}),Z?.interactive===!0&&K0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:W,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,W,Z){try{Rj(this.telemetry,{component:"core",operation:$,error:W,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let W=$.sessionId?.trim();if(!W)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let j=this.sessionClientContributionHandlers.get(W)?.get(J);if(!j){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${W}.`},W).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Y=new AbortController;this.activeCapabilityAbortControllers.set(Q,Y);let V=(B)=>{this.client.command("capability.progress",{requestId:Q,payload:B},W).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await j({payload:X,abortSignal:Y.signal,progress:V});if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:B},W)}catch(B){if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:B instanceof Error?B.message:String(B)},W)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let W=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!W)return;let Z=this.activeCapabilityAbortControllers.get(W);if(!Z)return;Z.abort(Yb($.payload.error))}async handleApprovalRequested($){let W=$.sessionId?.trim();if(!W)return;let Z=this.sessionCapabilities.get(W)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!J||!j)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},Y=Vb($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:W,toolCallId:J,toolName:j,toolInput:Y});let V=await Promise.resolve(Z({sessionId:W,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:W,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:j,input:Y,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:V.approved,reason:V.reason},W).catch(()=>{})}}var rA={};w(rA,{RemoteRuntimeHost:()=>R6});class R6 extends X${constructor($){super({url:O$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var iA={};w(iA,{SqliteSessionStore:()=>C1});import{existsSync as Ab,mkdirSync as Ub}from"node:fs";import{join as fb}from"node:path";import{asBool as QW,asOptionalString as w1,asString as Y$,ensureSessionSchema as Db,loadSqliteDb as _b,nowIso as FQ,toBoolInt as JW}from"@cline/shared/db";import{resolveDbDataDir as Lb}from"@cline/shared/storage";class C1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Lb()}init(){this.getRawDb()}ensureSessionsDir(){if(!Ab(this.sessionsDirPath))Ub(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return fb(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=_b(this.sessionDbPath());return Db($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}create($){let W=FQ();this.run(`INSERT OR REPLACE INTO sessions (
504
+ `))j=j.slice(1);return{frontmatter:J,body:j}}function $1($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function BS($){if(!Array.isArray($))return;let W=$.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);return W.length>0?W:void 0}function zj($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function HS($){let W=zj($);if(!W)return;let Z=$1(W.providerId),Q=$1(W.modelId);if(Z===void 0&&Q===void 0)return;return{providerId:Z,modelId:Q}}function GS($){if(typeof $!=="string")return;let W=$.trim().toLowerCase();if(W==="act"||W==="plan"||W==="yolo")return W;return}function bA($,W={}){let Z=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Z)return;let Q=[...new Set(Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&W.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var KS=new Set(D$);function FS($){let W=bA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!KS.has(Q));if(Z.length>0)throw Error(`unknown tool(s): ${Z.join(", ")}`);return W}var AS=new Set(["rules","skills","plugins"]);function US($){let W=bA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!AS.has(Q));if(Z.length>0)throw Error(`unknown extension(s): ${Z.join(", ")}`);return W}function Tj($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function Oj($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function qj($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Z)=>qj(Z)).join(",")}]`;let W=Object.entries($).filter(([,Z])=>Z!==void 0);return W.sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0),`{${W.map(([Z,Q])=>`${JSON.stringify(Z)}:${qj(Q)}`).join(",")}}`}function yA($,W){let Z=jS("sha256");return Z.update(qj($)),Z.update(`
505
+ `),Z.update(W),Z.digest("hex")}function DS($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var _S=["schedule","timezone"],fS=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],LS=["cwd"];function SA($,W,Z,Q,J){return{externalId:$,relativePath:$,triggerKind:W,body:Z,contentHash:yA(Q,Z),error:J}}function E1($,W,Z,Q,J,j){return{externalId:$,relativePath:W,triggerKind:Z,body:Q,contentHash:J,error:j}}function hA($){let W=$.relativePath.replace(/\\/g,"/"),Z=YS(W),{frontmatter:Q,body:J}=VS($.raw),j={};if(Q!==void 0&&Q.trim().length>0)try{let _=XS.parse(Q);if(_&&typeof _==="object"&&!Array.isArray(_))j=_;else if(_!==null&&_!==void 0)return SA(W,Z,J,{},"frontmatter must be a YAML mapping")}catch(_){return SA(W,Z,J,{},_ instanceof Error?`failed to parse frontmatter: ${_.message}`:"failed to parse frontmatter")}let X=yA(j,J),Y=$1(j.id),V=Y??W;if(Z!=="schedule"){for(let _ of _S)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on *.cron.md specs`)}for(let _ of LS)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Z!=="event"){for(let _ of fS)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on .event.md specs`)}let B=$1(j.prompt),H=J.trim(),G=B??(H.length>0?H:void 0);if(!G)return E1(V,W,Z,J,X,"prompt is required (frontmatter `prompt` or markdown body)");let K=$1(j.workspaceRoot);if(!K)return E1(V,W,Z,J,X,"workspaceRoot is required");let F,A;try{F=FS(j.tools),A=US(j.extensions)}catch(_){return E1(V,W,Z,J,X,_ instanceof Error?_.message:String(_))}let D=GS(j.mode);if(j.mode!==void 0&&D===void 0)return E1(V,W,Z,J,X,"mode must be one of: act, plan, yolo");let U={id:Y,title:$1(j.title)??Y??DS(W),prompt:G,workspaceRoot:K,mode:D??"yolo",systemPrompt:$1(j.systemPrompt),modelSelection:HS(j.modelSelection),maxIterations:Tj(j.maxIterations),timeoutSeconds:Tj(j.timeoutSeconds),tools:F,notesDirectory:$1(j.notesDirectory),extensions:A,source:$1(j.source)??"user",tags:BS(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:zj(j.metadata)},f;if(Z==="schedule"){let _=$1(j.schedule);if(!_)return E1(V,W,Z,J,X,"schedule is required for *.cron.md specs");let R=$1(j.timezone);try{GV(_,R)}catch(T){return E1(V,W,Z,J,X,T instanceof Error?T.message:String(T))}f={...U,triggerKind:"schedule",schedule:_,timezone:R}}else if(Z==="event"){let _=$1(j.event);if(!_)return E1(V,W,Z,J,X,"event is required for .event.md specs");f={...U,triggerKind:"event",event:_,filters:zj(j.filters),debounceSeconds:Oj(j.debounceSeconds),dedupeWindowSeconds:Oj(j.dedupeWindowSeconds),cooldownSeconds:Oj(j.cooldownSeconds),maxParallel:Tj(j.maxParallel)}}else f={...U,triggerKind:"one_off"};return{externalId:V,relativePath:W,triggerKind:Z,body:J,contentHash:X,spec:f}}function ES($,W){return MS($,W).replace(/\\/g,"/")}function NS($){if(!TS($))return[];let W=[],Z=[$];while(Z.length>0){let Q=Z.pop();if(!Q)continue;let J;try{J=OS(Q,{withFileTypes:!0})}catch{continue}for(let j of J){let X=`${Q}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Z.push(X);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;W.push(X)}}return W}class Mj{store;cronDir;constructor($){this.store=$.store,this.cronDir=RS($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},W=NS(this.cronDir),Z=new Set;for(let J of W){let j=ES(this.cronDir,J);Z.add(j),$.scanned+=1;let X=await this.reconcileFile(j,J);if(X){if($.changes.push(X),$.upserted+=1,X.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of Q)if(!Z.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,W){let Z=this.store.getSpecBySourcePath($),Q,J;try{Q=zS(W,"utf8"),J=qS(W).mtimeMs}catch{return}let X=hA({relativePath:$,raw:Q}),Y=this.store.upsertSpec({externalId:X.externalId,sourcePath:$,triggerKind:X.triggerKind,sourceMtimeMs:J,sourceHash:X.contentHash,parseStatus:X.error?"invalid":"valid",parseError:X.error,spec:X.spec});if(!X.error&&X.triggerKind==="schedule"&&Y.record.enabled)this.applyScheduleNextRunAt(Y.record,{forceReset:!Z||Z.removed||!Z.enabled||Z.scheduleExpr!==Y.record.scheduleExpr||Z.timezone!==Y.record.timezone});return{relativePath:$,result:Y,parse:X}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of $)this.applyScheduleNextRunAt(W,{forceReset:!1})}applyScheduleNextRunAt($,W){if(!$.scheduleExpr)return;if(!W.forceReset&&$.nextRunAt)return;try{let Z=Date.now(),Q=$.lastRunAt?Math.max(Z,new Date($.lastRunAt).getTime()):Z,J=Q2($.scheduleExpr,Q,$.timezone),j=new Date(J).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as wS,mkdirSync as CS,watch as PS}from"node:fs";import{relative as SS,resolve as bS}from"node:path";var yS=250;class Rj{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??yS),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{CS($,{recursive:!0}),this.watcher=PS($,{recursive:!0},(W,Z)=>{if(!Z)return;let Q=String(Z).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(W){this.onError(W)}}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 W=this.pending.get($);if(W)clearTimeout(W);let Z=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Z)}async reconcileNow($){try{let W=bS(this.reconciler.getCronDir(),$);if(!wS(W)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Z=SS(this.reconciler.getCronDir(),W).replace(/\\/g,"/");await this.reconciler.reconcileFile(Z,W),await this.onReconciled()}catch(W){this.onError(W)}}}class W9{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath});let W=$.specs;this.reconciler=new Mj({store:this.store,specs:W}),this.materializer=new e6({store:this.store}),this.eventIngress=new Lj({store:this.store,logger:$.logger}),this.runner=new Z4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:W,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new Rj({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Z)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:Z});else Q.log("cron.watcher.failed",{error:Z})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var cA={};w(cA,{manifestToSessionRecord:()=>LQ,listSessionHistoryFromBackend:()=>Cj,listSessionHistory:()=>TQ,hydrateSessionHistory:()=>vA});import{readdir as IS,readFile as xA}from"node:fs/promises";import{join as gA}from"node:path";import{formatDisplayUserInput as xS,normalizeUserInput as gS}from"@cline/shared";import{resolveSessionDataDir as mA}from"@cline/shared/storage";import{existsSync as hS}from"node:fs";import{readFile as kS}from"node:fs/promises";class Z9{listeners=new Set;subscribe($,W){let Z={listener:$,sessionId:W?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let W=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==W)continue;Z.listener($)}}get size(){return this.listeners.size}}async function p$($){let W=$?.trim();if(!W||!hS(W))return[];try{let Z=(await kS(W,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function Ej($){return $?{...$}:void 0}async function kA($,W){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await W.queueSpawnRequest($);let Q=await W.upsertSubagentSessionFromHook($);if(!Q)return;await W.appendSubagentHookAudit(Q,$),await W.applySubagentStatus(Q,$)}function Q9($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function W1($){let W=Q9($);if(!W)return;return W.toLowerCase()==="unknown"?void 0:W}function fQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function mS($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function wj($){let W=$??200;return Number.isFinite(W)?Math.max(0,Math.floor(W)):200}function vS($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function cS($){return $.isSubagent!==!0&&!Q9($.parentSessionId)}function uS($){let W=$.match(/\d{13,}/g);if(!W||W.length===0)return 0;let Z=0;for(let Q of W){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function LQ($){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 dS($){let W=wj($);if(W===0)return[];let Z=mA(),J=(await IS(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:uS(X.name.trim())})).sort((X,Y)=>Y.recency-X.recency||Y.entry.name.localeCompare(X.entry.name));return(await Promise.all(J.map(async({entry:X})=>{let Y=X.name.trim();if(!Y)return;let V=gA(Z,Y,`${Y}.json`),B=await xA(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=m0.safeParse(H);if(!G.success)return;return LQ(G.data)}))).filter((X)=>Boolean(X)).sort((X,Y)=>Y.startedAt.localeCompare(X.startedAt)).slice(0,W)}async function lS($,W,Z){let Q=wj(W);if(Q===0)return await $.listSessions(0),[];let J=Z.includeSubagents?Q:vS(Q),j=await $.listSessions(J);return(Z.includeSubagents?j:j.filter(cS)).slice(0,Q)}function pS($){if(typeof $==="string")return $.trim();let W=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)W.push(J)}return W.join(`
506
+ `).trim()}function IA($){return $.replace(/\s+/g," ").trim()}function rS($,W){if($.length<=W)return $;return`${$.slice(0,Math.max(0,W-3)).trimEnd()}...`}function iS($){for(let W of["user","assistant"])for(let Z of $){if(Z.role!==W)continue;let Q=IA(pS(Z.content));if(!Q)continue;let J=W==="user"?IA(xS(Q)):Q,j=gS(J.split(`
507
+ `)[0]??J);return rS(j,50)}return}function nS($){let W=0;for(let Z of $)W+=fQ(Z.metrics?.cost)??0;return W}function aS($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=W1(J.modelInfo?.provider);if(!Z)Z=W1(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function oS($){return W1($?.provider)??W1($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function sS($){return W1($?.model)??W1($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function Nj($,W){let Z=mS($.metadata),Q=Q9(W?.title)??Q9(Z?.title),J=fQ(W?.totalCost)??fQ(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:W1(W?.provider)??W1($.provider)??oS(Z)??"",model:W1(W?.model)??W1($.model)??sS(Z)??"",metadata:j}}function tS($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function eS($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!tS(Z)}async function $b($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return eS(Z,Q)?{...Z,status:"idle"}:Z}))}async function vA($,W){return await Promise.all(W.map(async(Z)=>{let Q=Nj(Z),J=Boolean(Q9(Q.metadata?.title)),j=Boolean(W1(Q.provider)),X=Boolean(W1(Q.model)),Y=fQ(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=aS(B),G=nS(B);return Nj(Z,{title:J?void 0:iS(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function TQ($,W={}){let Z=wj(W.limit),Q=W.includeSubagents===!0,J=await lS($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await dS(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await $b($,Y);if(W.hydrate===!1)return V.map((B)=>Nj(B));return await vA($,V)}async function Wb($){let W=$.trim();if(!W)return;let Z=gA(mA(),W,`${W}.json`),Q=await xA(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=m0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function Cj($,W={}){let Z=new Map;return await TQ({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(H5)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await Wb(J);return await p$(j)}},W)}var bU={};w(bU,{resolveSessionBackend:()=>oj,createRuntimeHost:()=>h6});import{captureSdkError as PU}from"@cline/shared";var $U={};w($U,{HubRuntimeHost:()=>Y$});import{resolveProviderRequestHeaders as jb}from"@cline/llms";import{captureSdkError as Pj,createSessionId as dA,HUB_CHECKPOINT_CAPABILITY as Xb,HUB_COMPACTION_CAPABILITY as Yb,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Vb,HUB_HOOK_CAPABILITY_PREFIX as Bb,HUB_MISTAKE_LIMIT_CAPABILITY as Hb,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Gb,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Kb,isHubToolExecutorName as Fb}from"@cline/shared";var uA={};w(uA,{createCoreSessionSnapshot:()=>N1,coreSessionSnapshotToRecord:()=>OQ});function Zb($){return $?JSON.parse(JSON.stringify($)):void 0}function Qb($){return $?JSON.parse(JSON.stringify($)):void 0}function Jb($){let W=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(W?.history)?W.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let Y=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!Y||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:Y,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),J=Q.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Q.length===0)return;return{...j?{enabled:j}:{},...J?{latest:J}:{},history:Q}}function N1($){let{session:W}=$,Z=Zb(W.metadata);return{version:1,sessionId:W.sessionId,source:W.source,status:W.status,createdAt:W.startedAt,updatedAt:W.updatedAt,endedAt:W.endedAt??null,exitCode:W.exitCode??null,interactive:W.interactive,workspace:{cwd:W.cwd,root:W.workspaceRoot},model:{providerId:W.provider,modelId:W.model},capabilities:{enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams},lineage:{...W.parentSessionId?{parentSessionId:W.parentSessionId}:{},...W.parentAgentId?{parentAgentId:W.parentAgentId}:{},...W.agentId?{agentId:W.agentId}:{},...W.conversationId?{conversationId:W.conversationId}:{},isSubagent:W.isSubagent},...W.teamName?{team:{name:W.teamName}}:{},...W.prompt?{prompt:W.prompt}:{},...Z?{metadata:Z}:{},...W.messagesPath?{artifacts:{messagesPath:W.messagesPath}}:{},...$.messages?{messages:Qb($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=Jb(Z);return Q?{checkpoint:Q}:{}})()}}function OQ($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function E6($){if(!$)return;return JSON.parse(JSON.stringify($))}var Ab=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function lA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function pA($){if(!$)return;let{userInstructionService:W,...Z}=$;return JSON.parse(JSON.stringify(Z))}function rA($,W){let Z={...$.config,sessionId:W},Q=jb({providerId:$.config.providerId,sessionId:W,source:$.source,defaultSource:F0.CORE,client:{name:$.localRuntime?.extensionContext?.client?.name,version:$.localRuntime?.extensionContext?.client?.version,versionHeaderFallback:$.config.headers?.["X-CLIENT-VERSION"],platform:$.localRuntime?.extensionContext?.client?.platform,platformVersion:$.localRuntime?.extensionContext?.client?.platformVersion,isMultiRoot:$.localRuntime?.extensionContext?.client?.isMultiRoot},coreVersion:R8,openAiCodex:{accessToken:$.config.apiKey,userAgentVersion:process.env.npm_package_version},headers:{config:$.config.headers}});if(Q)Z.headers=Q;return Z}function iA($){let W=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof W.agentId==="string"?W.agentId:"",conversationId:typeof W.conversationId==="string"?W.conversationId:"",iteration:typeof W.iteration==="number"?W.iteration:0,metadata:W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0}}function s2($,W,Z){$.manifest.push(W),$.handlers.set(W.capabilityName,Z)}function nA($,W){let Z={manifest:[],handlers:new Map};for(let J of Object.keys(W.toolExecutors??{}).filter(Fb)){let j=W.toolExecutors?.[J];if(typeof j!=="function")continue;s2(Z,{kind:"toolExecutor",executor:J,capabilityName:`${Gb}${J}`},async({payload:X,abortSignal:Y})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...iA(X.context),signal:Y};return{result:await j(...V,B)}})}for(let J of $?.extraTools??[])s2(Z,{kind:"tool",name:J.name,description:J.description,inputSchema:E6(J.inputSchema)??{},...J.lifecycle?{lifecycle:E6(J.lifecycle)}:{},capabilityName:`${Vb}${J.name}`},async({payload:j,abortSignal:X,progress:Y})=>{let V={...iA(j.context),signal:X};return{result:await J.execute(j.input,{...V,emitUpdate:(H)=>{Y({update:H})}})}});let Q=$?.hooks;if(Q)for(let J of Ab){let j=Q[J];if(typeof j!=="function")continue;s2(Z,{kind:"hook",name:J,capabilityName:`${Bb}${J}`},async({payload:X})=>({control:await j(X.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;s2(Z,{kind:"compaction",capabilityName:Yb,config:lA($.compaction)},async({payload:j})=>({result:await J(j.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;s2(Z,{kind:"checkpoint",capabilityName:Xb,config:lA($.checkpoint)},async({payload:j})=>({result:await J(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;s2(Z,{kind:"mistakeLimit",capabilityName:Hb},async({payload:j})=>({result:await J(j.context)}))}if($?.userInstructionService){let J=$.userInstructionService;s2(Z,{kind:"userInstructionService",capabilityName:Kb},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Z}function tA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let W=$.message;if(typeof W==="string"&&W.trim())return W.trim()}return}function Ub($){return tA($)??"Capability request was cancelled."}function Db($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function _b($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function fb($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=typeof W.inputTokens==="number"?W.inputTokens:void 0,Q=typeof W.outputTokens==="number"?W.outputTokens:void 0;if(Z===void 0||Q===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:typeof W.cacheReadTokens==="number"?W.cacheReadTokens:0,cacheWriteTokens:typeof W.cacheWriteTokens==="number"?W.cacheWriteTokens:0,totalCost:typeof W.totalCost==="number"?W.totalCost:0}}function aA($){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 Sj($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function r$($,W){return Sj($?.[W])??0}function Lb($){let W=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:r$(W,"inputTokens"),outputTokens:r$(W,"outputTokens"),cacheReadTokens:r$(W,"cacheReadTokens"),cacheWriteTokens:r$(W,"cacheWriteTokens"),cost:Sj(W?.totalCost),totalInputTokens:r$(Z,"inputTokens"),totalOutputTokens:r$(Z,"outputTokens"),totalCacheReadTokens:r$(Z,"cacheReadTokens"),totalCacheWriteTokens:r$(Z,"cacheWriteTokens"),totalCost:Sj(Z?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:J}}function Tb($){let W=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??W?.finishReason,Q=_b(Z)?Z:Z==="failed"?"error":"completed",J=fb($?.usage??W?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof W?.text==="string"?W.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof W?.iterations==="number"?W.iterations:0,usage:J}}function t2($,W){return $.error?.message??`hub command failed: ${W}`}function J9($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function eA($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof W?.parentSessionId==="string"?W.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof W?.agentId==="string"?W.agentId:void 0),parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,isSubagent:typeof W?.isSubagent==="boolean"?W.isSubagent:!1,source:typeof W?.source==="string"?W.source:F0.CORE,pid:typeof W?.pid==="number"?W.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:J9($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:J9($.status)==="completed"?0:J9($.status)==="failed"?1:void 0,status:J9($.status),interactive:W?.interactive===!0,provider:typeof W?.provider==="string"?W.provider:"hub",model:typeof W?.model==="string"?W.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof W?.teamName==="string"?W.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??W?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??W?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??W?.enableTeams===!0,prompt:typeof W?.prompt==="string"?W.prompt:void 0,metadata:W,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof W?.messagesPath==="string"?W.messagesPath:void 0,hookPath:typeof W?.hookPath==="string"?W.hookPath:void 0}}function i$($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$;return W.version===1&&typeof W.sessionId==="string"?JSON.parse(JSON.stringify(W)):void 0}function Ob($){let W=i$($?.snapshot);if(W)return OQ(W);let Z=$?.session;return Z?eA(Z):void 0}function oA($,W,Z){let Q=Z?.workspaceRoot?.trim()||W.config.workspaceRoot||W.config.cwd;return m0.parse({version:1,session_id:$,source:W.source??F0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:J9(Z?.status),interactive:W.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:Z?.cwd?.trim()||W.config.cwd,workspace_root:Q,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,metadata:W.sessionMetadata&&Object.keys(W.sessionMetadata).length>0?W.sessionMetadata:void 0})}function sA($,W){return m0.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??W.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class Y${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new Z9;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,W){this.clientContext=W,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd},this.defaultCapabilities=P0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new B1({...this.clientOptions,url:$})}async replaceClient($){let W=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(W.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!NW($,"session.create"))return!1;let W=await wW({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!W)return!1;return await this.replaceClient(W),!0}registerPlannedSession($,W,Z){if(this.sessionCapabilities.set($,W),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let W=this.resolveCapabilities($),Z=nA($.localRuntime,W),Q=$.config.sessionId?.trim()||dA(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:E6(rA($,Q)),metadata:{...$.sessionMetadata??{},source:$.source??F0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:E6($.toolPolicies),initialMessages:$.initialMessages,...$.initialCompactionState?{initialCompactionState:$.initialCompactionState}:{}});this.registerPlannedSession(Q,W,Z.handlers);let j;try{j=await J()}catch(B){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(Q,W,Z.handlers);try{j=await J()}catch(H){throw this.cleanupPlannedSession(Q),H}}else throw B}let X=i$(j.payload?.snapshot),Y=j.payload?.session,V=(X?.sessionId??Y?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(V!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(V,W,Z.handlers);return{sessionId:V,manifest:X?sA(X,$):oA(V,$,Y),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,J=Q?this.resolveCapabilities(Q):void 0,j=Q?nA(Q.localRuntime,J??{}):{manifest:[],handlers:new Map},X,Y;if(Q)X=Q.config.sessionId?.trim()||dA(),Y=rA(Q,X);if(X&&J)this.sessionCapabilities.set(X,J);if(X&&j.handlers.size>0)this.sessionClientContributionHandlers.set(X,j.handlers),this.ensureSessionSubscription(X);let V;try{V=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:E6(Y),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:E6(Q.toolPolicies),...Q.initialCompactionState?{initialCompactionState:Q.initialCompactionState}:{}}:{}},W)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!V.ok){let A=typeof V.payload?.error==="string"?V.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let B=i$(V.payload?.snapshot),H=V.payload?.session,G=(B?.sessionId??H?.sessionId)?.trim();if(Z&&!G){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(G&&X&&G!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(G&&J)this.sessionCapabilities.set(G,J);if(G&&j.handlers.size>0)this.sessionClientContributionHandlers.set(G,j.handlers);if(G)this.ensureSessionSubscription(G);let K=Array.isArray(V.payload?.messages)?V.payload.messages:void 0,F=V.payload?.checkpoint;if(!F)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:G,startResult:G?{sessionId:G,manifest:B?sA(B,Q??{}):oA(G,Q??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:K,checkpoint:F}}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 W=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(W.payload?.prompts)?W.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,updated:W.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,removed:W.payload?.removed===!0}}async getAccumulatedUsage($){let W=await this.client.command("session.get",{includeSnapshot:!0},$),Z=i$(W.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,Y=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||Y?{usage:X,aggregateUsage:Y}:void 0}let Q=W.payload?.session,J=aA(Q?.usage),j=aA(Q?.aggregateUsage);return J||j?{usage:J,aggregateUsage:j}:void 0}async abort($,W){await this.client.command("run.abort",{sessionId:$,reason:tA(W)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,W]of this.sessionSubscriptions){W();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 W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(p1(Z))return;throw Z}return Ob(W.payload)}async listSessions($=100){let W=await this.client.command("session.list",{limit:$}),Z=Array.isArray(W.payload?.snapshots)?W.payload.snapshots.flatMap((J)=>{let j=i$(J);return j?[OQ(j)]:[]}):[];if(Z.length>0)return Z;return(W.payload?.sessions??[]).map(eA)}async listSettings($){let W=await this.client.command("settings.list",pA($));if(!W.ok)throw Error(t2(W,"settings.list"));return W.payload?.snapshot}async toggleSetting($){let W=await this.client.command("settings.toggle",pA($));if(!W.ok)throw Error(t2(W,"settings.toggle"));return{snapshot:W.payload?.snapshot,changedTypes:Array.isArray(W.payload?.changedTypes)?W.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,W){let Z={...W.metadata??{}};if(typeof W.prompt==="string")Z.prompt=W.prompt;if(typeof W.title==="string")Z.title=W.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async updateSessionConnection($,W){let Z=$.trim();if(!Z)return;let Q=await this.client.command("session.update_connection",{sessionId:Z,updates:W},Z);if(!Q.ok)throw Error(t2(Q,"session.update_connection"))}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=await this.client.command("session.compaction.update",{sessionId:Z,state:W},Z);if(!Q.ok)Pj(this.telemetry,{component:"core",operation:"hub.runtime_host.update_session_compaction_state",error:Error(t2(Q,"session.compaction.update")),severity:"warn",handled:!0,context:{command:"session.compaction.update",sessionId:Z,errorCode:Q.error?.code}});return{updated:Q.ok&&Q.payload?.updated===!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=await this.client.command("session.compaction.get",{sessionId:W},W);if(!Z.ok)throw Error(t2(Z,"session.compaction.get"));return G1(Z.payload?.state)}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Pj(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(t2(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:W,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(t2(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,W){return this.events.subscribe($,W)}ensureSessionSubscription($){let W=$.trim();if(!W||this.sessionSubscriptions.has(W))return;let Z=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:W});this.sessionSubscriptions.set(W,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let W=$.trim();if(!W)return;this.sessionSubscriptions.get(W)?.(),this.sessionSubscriptions.delete(W),this.agentDoneEmittedForCurrentRunBySession.delete(W)}resolveCapabilities($){return P0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:Tb($.payload)}})}handleHubEvent($){let W=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!W)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(W);let Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,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"session.notice":{let Z=$.payload?.noticeType,Q=$.payload?.displayRole,J=$.payload?.reason,j=$.payload?.agent&&typeof $.payload.agent==="object"?$.payload.agent:void 0,X=j?.teamRole==="lead"||j?.teamRole==="teammate"?j.teamRole:void 0;this.events.emit({type:"agent_event",payload:{sessionId:W,...X?{teamRole:X}:{},...typeof j?.teamAgentId==="string"?{teamAgentId:j.teamAgentId}:{},event:{type:"notice",...typeof j?.agentId==="string"?{agentId:j.agentId}:{},...typeof j?.conversationId==="string"?{conversationId:j.conversationId}:{},...typeof j?.parentAgentId==="string"?{parentAgentId:j.parentAgentId}:{},noticeType:Z==="recovery"||Z==="stop"?Z:"status",message:typeof $.payload?.message==="string"?$.payload.message:"",...Q==="system"||Q==="status"?{displayRole:Q}:{},...typeof J==="string"?{reason:J}:{},...$.payload?.metadata&&typeof $.payload.metadata==="object"?{metadata:$.payload.metadata}:{}}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!Z&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:W,payload:$.payload});return}case"usage.updated":{let Z=Lb($.payload);this.events.emit({type:"agent_event",payload:{sessionId:W,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:W,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"tool",toolCallId:Z,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 Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:W,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:W,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=i$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:W,payload:{...$.payload,reason:Q}}),Z?.interactive===!0&&K0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:W,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,W,Z){try{Pj(this.telemetry,{component:"core",operation:$,error:W,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let W=$.sessionId?.trim();if(!W)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let j=this.sessionClientContributionHandlers.get(W)?.get(J);if(!j){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${W}.`},W).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Y=new AbortController;this.activeCapabilityAbortControllers.set(Q,Y);let V=(B)=>{this.client.command("capability.progress",{requestId:Q,payload:B},W).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await j({payload:X,abortSignal:Y.signal,progress:V});if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:B},W)}catch(B){if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:B instanceof Error?B.message:String(B)},W)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let W=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!W)return;let Z=this.activeCapabilityAbortControllers.get(W);if(!Z)return;Z.abort(Ub($.payload.error))}async handleApprovalRequested($){let W=$.sessionId?.trim();if(!W)return;let Z=this.sessionCapabilities.get(W)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!J||!j)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},Y=Db($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:W,toolCallId:J,toolName:j,toolInput:Y});let V=await Promise.resolve(Z({sessionId:W,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:W,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:j,input:Y,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:V.approved,reason:V.reason},W).catch(()=>{})}}var WU={};w(WU,{RemoteRuntimeHost:()=>N6});class N6 extends Y${constructor($){super({url:z$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var ZU={};w(ZU,{SqliteSessionStore:()=>C1});import{existsSync as zb,mkdirSync as qb}from"node:fs";import{join as Mb}from"node:path";import{asBool as j9,asOptionalString as w1,asString as V$,ensureSessionSchema as Rb,loadSqliteDb as Eb,nowIso as zQ,toBoolInt as X9}from"@cline/shared/db";import{resolveDbDataDir as Nb}from"@cline/shared/storage";class C1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Nb()}init(){this.getRawDb()}ensureSessionsDir(){if(!zb(this.sessionsDirPath))qb(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return Mb(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=Eb(this.sessionDbPath());return Rb($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}create($){let W=zQ();this.run(`INSERT OR REPLACE INTO sessions (
508
508
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
509
509
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
510
510
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
511
511
  metadata_json, transcript_path, hook_path, messages_path, updated_at
512
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,JW($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,JW($.enableTools),JW($.enableSpawn),JW($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,JW($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,W])}update($){let W=[],Z=[];if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId);if(W.length===0)return;W.push("updated_at = ?"),Z.push(FQ()),Z.push($.sessionId),this.run(`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`,Z)}updateStatus($,W,Z){this.update({sessionId:$,status:W,endedAt:K0(W)?null:FQ(),exitCode:K0(W)?null:Z??(W==="failed"?1:0)})}get($){let W=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
512
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,X9($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,X9($.enableTools),X9($.enableSpawn),X9($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,X9($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,W])}update($){let W=[],Z=[];if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId);if(W.length===0)return;W.push("updated_at = ?"),Z.push(zQ()),Z.push($.sessionId),this.run(`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`,Z)}updateStatus($,W,Z){this.update({sessionId:$,status:W,endedAt:K0(W)?null:zQ(),exitCode:K0(W)?null:Z??(W==="failed"?1:0)})}get($){let W=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
513
513
  provider, model, cwd, workspace_root, team_name,
514
514
  enable_tools, enable_spawn, enable_teams,
515
515
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
516
516
  prompt, metadata_json, hook_path, messages_path, updated_at
517
- FROM sessions WHERE session_id = ?`,[$]);if(!W)return;return{sessionId:Y$(W.session_id),source:Y$(W.source),pid:Number(W.pid??0),startedAt:Y$(W.started_at),endedAt:W.ended_at??null,exitCode:W.exit_code??null,status:Y$(W.status),interactive:QW(W.interactive),provider:Y$(W.provider),model:Y$(W.model),cwd:Y$(W.cwd),workspaceRoot:Y$(W.workspace_root),teamName:w1(W.team_name),enableTools:QW(W.enable_tools),enableSpawn:QW(W.enable_spawn),enableTeams:QW(W.enable_teams),parentSessionId:w1(W.parent_session_id),parentAgentId:w1(W.parent_agent_id),agentId:w1(W.agent_id),conversationId:w1(W.conversation_id),isSubagent:QW(W.is_subagent),prompt:w1(W.prompt),metadata:(()=>{let Z=w1(W.metadata_json);if(!Z)return;try{let Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:w1(W.hook_path),messagesPath:w1(W.messages_path),updatedAt:w1(W.updated_at)??FQ()}}list($=200){let W=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Z=[];for(let Q of W){let J=this.get(Y$(Q.session_id));if(J)Z.push(J)}return Z}delete($,W=!1){let Z=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}}L8();import{existsSync as mj,mkdirSync as Xy,readFileSync as FU,renameSync as Yy,writeFileSync as Vy}from"node:fs";import{join as AU}from"node:path";import{resolveSessionDataDir as By}from"@cline/shared/storage";import{dirname as Jy}from"node:path";import{nanoid as jy}from"nanoid";import{appendFileSync as Rb,existsSync as Nb,mkdirSync as sA,readFileSync as Eb,writeFileSync as tA}from"node:fs";import{readFile as eA,rm as wb}from"node:fs/promises";import{dirname as $U,join as Cb}from"node:path";import{ensureHookLogDir as Pb}from"@cline/shared/storage";import{randomUUID as Tb}from"node:crypto";import{mkdir as Ob,open as aA,rename as zb,rm as qb}from"node:fs/promises";import{dirname as nA}from"node:path";async function Mb($){let W;try{W=await aA($,"r"),await W.sync()}catch{}finally{if(W!==void 0)try{await W.close()}catch{}}}async function oA($,W){await Ob(nA($),{recursive:!0});let Z=`${$}.${process.pid}.${Tb()}.tmp`,Q;try{Q=await aA(Z,"wx"),await Q.writeFile(W,"utf8"),await Q.sync(),await Q.close(),Q=void 0,await zb(Z,$),await Mb(nA($))}catch(J){if(Q!==void 0)try{await Q.close()}catch{}try{await qb(Z,{force:!0})}catch{}throw J}}function Sb($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}class Ej{adapter;messagesArtifactUploader;logger;artifacts;constructor($,W,Z){this.adapter=$;this.messagesArtifactUploader=W;this.logger=Z;this.artifacts=new iJ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,W,Z){JK(W,Z,KJ($))}writeSessionManifest($,W){sA($U($),{recursive:!0}),tA($,`${JSON.stringify(g0.parse(W),null,2)}
518
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}async readSessionManifestTitle($){let W=this.artifacts.sessionManifestPath($,!1),Z;try{Z=await eA(W,"utf8")}catch{return}try{let Q=JSON.parse(Z);if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J=Q.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let j=J.title;return typeof j==="string"?j:void 0}catch{return}}readManifestFile($){let W=this.artifacts.sessionManifestPath($,!1);if(!Nb(W))return{path:W};try{return{path:W,manifest:g0.parse(JSON.parse(Eb(W,"utf8")))}}catch{return{path:W}}}async resolveArtifactPath($,W,Z){let J=(await this.adapter.getSession($))?.[W];return typeof J==="string"&&J.trim().length>0?J:Z($)}async persistSessionMessages($,W,Z){let Q=await this.resolveArtifactPath($,"messagesPath",(X)=>this.artifacts.sessionMessagesPath(X)),J=FJ({updatedAt:X0(),context:KJ($),messages:W,systemPrompt:Z}),j=`${JSON.stringify(J,null,2)}
519
- `;if(sA($U(Q),{recursive:!0}),tA(Q,j,"utf8"),!this.messagesArtifactUploader)return;try{let X=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:j,row:X})}catch(X){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:X})}}resolveCompactionPath($){let{manifest:W}=this.readManifestFile($);return W?.compaction_path?.trim()||this.artifacts.sessionCompactionPath($)}updateCompactionPath($,W){let Z=this.readManifestFile($);if(!Z.manifest)return;if(Z.manifest.compaction_path===W)return;this.writeSessionManifest(Z.path,{...Z.manifest,compaction_path:W})}async readSessionCompactionState($){let W=this.resolveCompactionPath($);try{return G1(JSON.parse(await eA(W,"utf8")))}catch(Z){if(Sb(Z))return;this.logger?.debug("Ignoring invalid session compaction state",{sessionId:$,path:W,error:Z,recovery:"Canonical history is unchanged; deleting the sidecar is safe."});return}}async persistSessionCompactionState($,W){let Z=this.resolveCompactionPath($),Q=C4.parse(W);await oA(Z,`${JSON.stringify(Q,null,2)}
520
- `),this.updateCompactionPath($,Z)}async deleteSessionCompactionState($){await wb(this.resolveCompactionPath($),{force:!0}),this.updateCompactionPath($,void 0)}appendStaleSessionHookLog($,W,Z,Q,J){let X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Cb(Pb(),"hooks.jsonl");Rb(X,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:W,pid:Z,source:J})}
521
- `,"utf8")}}import{appendFileSync as bb}from"node:fs";import{join as yb}from"node:path";import{resolveRootSessionId as WU}from"@cline/shared";import{ensureHookLogDir as hb}from"@cline/shared/storage";import{z as wj}from"zod";var kb="subagent",Ib=wj.looseObject({task:wj.string().optional(),systemPrompt:wj.string().optional()});class AQ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,W,Z,Q){this.adapter=$;this.manifestStore=W;this.toPersistedMessages=Z;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,W){return`${$}::${W}`}activeTeamTaskSessionId($,W){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,W))?.at(-1)}buildSubsessionRow($,W){return{sessionId:W.sessionId,source:kb,pid:process.ppid,startedAt:W.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:W.parentSessionId,parentAgentId:W.parentAgentId,agentId:W.agentId,conversationId:W.conversationId??null,isSubagent:!0,prompt:W.prompt,metadata:B5({prompt:W.prompt}),hookPath:"",messagesPath:W.messagesPath,updatedAt:W.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let W=WU($.sessionContext);if(!W)return;let Z=Ib.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:W,parentAgentId:$.agent_id,task:Z.success?Z.data.task:void 0,systemPrompt:Z.success?Z.data.systemPrompt:void 0})}async upsertSubagentSession($){let W=$.rootSessionId;if(!W)return;let Z=await this.adapter.getSession(W);if(!Z)return;let Q=a8(W,$.agentId),J=await this.adapter.getSession(Q),j=X0(),X=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(W,$.parentAgentId)),Y=$.prompt??J?.prompt??void 0;if(!Y)Y=await this.adapter.claimSpawnRequest(W,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:Q,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Y,startedAt:j,...X})),this.manifestStore.initializeMessagesFile(Q,X.messagesPath,j),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??Y??null,metadata:B5({metadata:J.metadata??void 0,prompt:J.prompt??Y??null}),expectedStatusLock:J.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let W=WU($.sessionContext);if(!W)return;if($.hookName==="session_shutdown"){let Z=a8(W,$.agent_id);return await this.adapter.getSession(Z)?Z:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:W})}async applySubagentStatus($,W){await this.applySubagentStatusBySessionId($,X5(W))}async applySubagentStatusBySessionId($,W){let Z=await this.adapter.getSession($);if(!Z)return;let Q=K0(W)?null:X0(),J=K0(W)?null:W==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:W,endedAt:Q,exitCode:J,expectedStatusLock:Z.statusLock})}async applyStatusToRunningChildSessions($,W){if(!$)return;let Z=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of Z)await this.applySubagentStatusBySessionId(Q.sessionId,W)}async onTeamTaskStart($,W,Z){let Q=await this.adapter.getSession($);if(!Q)return;let J=J5($,W),j=X0(),{messagesPath:X}=this.manifestStore.artifacts.subagentArtifactPaths(J,W);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:W,prompt:Z||`Team task for ${W}`,startedAt:j,messagesPath:X})),this.manifestStore.initializeMessagesFile(J,X,j);let Y=this.teamTaskQueueKey($,W),V=this.teamTaskSessionsByAgent.get(Y)??[];V.push(J),this.teamTaskSessionsByAgent.set(Y,V)}async onTeamTaskEnd($,W,Z,Q,J,j){let X=this.teamTaskQueueKey($,W),Y=this.teamTaskSessionsByAgent.get(X);if(!Y||Y.length===0)return;let V=Y.shift();if(Y.length===0)this.teamTaskSessionsByAgent.delete(X);if(!V)return;let B=J?.messages??j,H=this.toPersistedMessages(B,J,j);if(H)await this.manifestStore.persistSessionMessages(V,H);await this.applySubagentStatusBySessionId(V,Z),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,W,Z,Q){let J=this.teamTaskQueueKey($,W),j=this.teamTaskSessionsByAgent.get(J)?.[0];if(!j)return;let X=Z.trim();if(!X)return;let Y=Q?.kind??"progress";if(Y==="heartbeat"){let B=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(B-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,B)}let V=Y==="heartbeat"?"[progress] heartbeat":Y==="text"?`[progress] text: ${X}`:`[progress] ${X}`;if(this.teamTaskLastProgressLineBySession.get(j)===V)return;this.teamTaskLastProgressLineBySession.set(j,V)}async handleSubAgentStart($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;await this.applySubagentStatusBySessionId(Z,"running")}async handleSubAgentEnd($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;if(W.error){await this.applySubagentStatusBySessionId(Z,"failed");return}let Q=this.toPersistedMessages(W.agentResult?.messages,W.agentResult);if(Q)await this.manifestStore.persistSessionMessages(Z,Q);let J=W.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Z,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??yb(hb(),"hooks.jsonl");bb(Z,`${JSON.stringify({ts:X0(),...$})}
522
- `,"utf8")}}import{formatUserInputBlock as Qy}from"@cline/shared";var KU={};w(KU,{toTeamProgressLifecycleEvent:()=>C6,sanitizeTeamName:()=>nG,reviveTeamStateDates:()=>ZZ,parseConfiguredAgentConfig:()=>jW,loadConfiguredAgentConfigs:()=>N6,createWorkerReviewerTeam:()=>GU,createSpawnAgentTool:()=>b$,createDelegatedAgentConfigProvider:()=>P$,createDelegatedAgent:()=>S$,createConfiguredAgentTools:()=>E6,createAgentTeamsTools:()=>P2,createAgentTeam:()=>Sj,buildTeamProgressSummary:()=>w6,buildDelegatedAgentConfig:()=>w2,buildConfiguredAgentToolName:()=>XW,buildConfiguredAgentToolDescriptors:()=>YW,bootstrapAgentTeams:()=>n8,AgentTeamsRuntime:()=>t2,AgentTeam:()=>S6});import{existsSync as xb,readdirSync as gb,readFileSync as mb}from"node:fs";import{basename as ZU,extname as vb,join as cb}from"node:path";import{resolveAgentConfigSearchPaths as ub}from"@cline/shared/storage";import JU from"yaml";import{z as y0}from"zod";var jU=y0.object({name:y0.string().trim().min(1),description:y0.string().trim().min(1),tools:y0.union([y0.string(),y0.array(y0.string())]).optional(),skills:y0.union([y0.string(),y0.array(y0.string())]).optional(),providerId:y0.string().trim().min(1).optional(),modelId:y0.string().trim().min(1).optional(),maxIterations:y0.number().int().positive().optional()});function db($){let W=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!W)throw Error("Missing YAML frontmatter block in agent config file.");let Z=W[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=Z;let J,j=Array.from($.matchAll(Q)).filter((X)=>X.index>=Z);for(let X of j){let Y=X.index,V=$.slice(Z,Y);try{let B=JU.parse(V);if(!B||typeof B!=="object"||Array.isArray(B))continue;jU.parse(B);let H=$.slice(Y+X[0].length);J={frontmatter:V,body:H}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function QU($){if($===void 0)return;let W=Array.isArray($)?$:$.split(",");return Array.from(new Set(W.map((Z)=>Z.trim()).filter((Z)=>Z.length>0)))}function lb($){return $.trim().toLowerCase()}function pb($){let W=vb($).toLowerCase();return W===".yml"||W===".yaml"}function jW($,W={}){let{frontmatter:Z,body:Q}=db($),J=JU.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let j=jU.parse(J),X=Q.trim();if(!X)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:QU(j.tools),skills:QU(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:X,path:W.path}}function N6($){let W=$.searchPaths??ub($.workspaceRoot),Z=new Map,Q=[];for(let j of W.filter(Boolean)){if(!xb(j))continue;let X;try{X=gb(j,{withFileTypes:!0})}catch(Y){Q.push({path:j,error:Y instanceof Error?Y:Error(String(Y))});continue}for(let Y of X){if(!Y.isFile()||!pb(Y.name))continue;let V=cb(j,Y.name);try{let B=mb(V,"utf8"),H=jW(B,{path:V}),G=lb(H.name);if(!Z.has(G))Z.set(G,H)}catch(B){Q.push({path:V,error:B instanceof Error?B:Error(String(B))})}}}return{configs:Array.from(Z.values()).sort((j,X)=>(j.path?ZU(j.path):j.name).localeCompare(X.path?ZU(X.path):X.name)),errors:Q}}import{createTool as rb,zodToJsonSchema as ib}from"@cline/shared";import{z as XU}from"zod";var Cj="subagent_",UQ=64,nb=XU.object({prompt:XU.string().trim().min(1).describe("Task for the subagent to perform")});function ab($){let W="",Z=!0;for(let Q of $.trim().toLowerCase()){let J=Q.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||Q==="_")||Q==="_"){if(!Z)W+="_",Z=!0;continue}W+=Q,Z=!1}return Z?W.slice(0,-1):W}function ob($){let W=2166136261;for(let Z=0;Z<$.length;Z++)W^=$.charCodeAt(Z),W=Math.imul(W,16777619);return(W>>>0).toString(36)}function XW($){let W=ab($)||"agent",Z=ob($).slice(0,6),Q=`${Cj}${W}`;if(Q.length<=UQ)return Q;let J=UQ-Cj.length-Z.length-1,j=W.slice(0,Math.max(1,J));return`${Cj}${j}_${Z}`.slice(0,UQ)}function YW($){let W=new Set,Z=[];for(let Q of[...$].sort((J,j)=>J.name.localeCompare(j.name))){let J=XW(Q.name),j=J,X=2;while(W.has(j)){let Y=`_${X++}`,V=Math.max(1,UQ-Y.length);j=`${J.slice(0,V)}${Y}`}W.add(j),Z.push({toolName:j,config:Q})}return Z}function sb($,W){return{...$,providerId:W.providerId??$.providerId,modelId:W.modelId??$.modelId,maxIterations:W.maxIterations??$.maxIterations}}function E6($){return YW($.agents).map(({toolName:W,config:Z})=>{return rb({name:W,description:`Use the "${Z.name}" subagent: ${Z.description}`,inputSchema:ib(nb),execute:async(J,j)=>{let X=$.configProvider.getRuntimeConfig(),Y=P$(sb(X,Z)),V=$.createSubAgentTools?await $.createSubAgentTools(Z,J,j):[],B=S$({kind:"subagent",prompt:Z.systemPrompt,configProvider:Y,tools:V,maxIterations:Z.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=B.getAgentId(),G=B.getConversationId(),K=j.agentId,F={systemPrompt:Z.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await B.run(J.prompt),f={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,result:f,agentResult:A})}catch{}return f}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function P1(){return new Date().toISOString()}function YU($,W){if(W<=0)return 0;return Math.round($/W*100)}function tb($,W){let Z=new Set;for(let J of W)if(J.status==="reviewed")Z.add(`${J.outcomeId}:${J.section}`);let Q=new Set;for(let J of $){if(J.status==="finalized")continue;for(let j of J.requiredSections)if(!Z.has(`${J.id}:${j}`))Q.add(`${J.id}:${j}`)}return[...Q].sort((J,j)=>J.localeCompare(j))}function w6($,W){let Z={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},X={draft:0,reviewed:0,rejected:0},Y=0,V=0;for(let U of W.members)if(Z[U.status]+=1,U.role==="lead")Y+=1;else V+=1;let B=[],H=[],G=W.tasks.filter((U)=>U.status==="completed").length,K=new Map(W.tasks.map((U)=>[U.id,U]));for(let U of W.tasks){if(Q[U.status]+=1,U.status==="blocked"){B.push(U.id);continue}if(U.status!=="pending")continue;if(U.dependsOn.every((D)=>{return K.get(D)?.status==="completed"}))H.push(U.id)}let F=[],A,f=0;for(let U of W.runs){if(J[U.status]+=1,U.status==="queued"||U.status==="running")F.push(U.id);let _=U.startedAt.getTime();if(_>=f)f=_,A=U.id}for(let U of W.outcomes)j[U.status]+=1;for(let U of W.outcomeFragments)X[U.status]+=1;return{teamName:$,updatedAt:P1(),members:{total:W.members.length,byStatus:Z,leadCount:Y,teammateCount:V},tasks:{total:W.tasks.length,byStatus:Q,blockedTaskIds:B,readyTaskIds:H,completionPct:YU(G,W.tasks.length)},runs:{total:W.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:W.outcomes.length,byStatus:j,finalizedPct:YU(j.finalized,W.outcomes.length),missingRequiredSections:tb(W.outcomes,W.outcomeFragments)},fragments:{total:W.outcomeFragments.length,byStatus:X}}}function C6($){let{event:W}=$;switch(W.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.task.id,agentId:W.task.assignee??W.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:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.fragment.outcomeId,fragmentId:W.fragment.id,agentId:W.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.message.taskId,agentId:W.message.fromAgentId,message:W.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.entry.taskId,agentId:W.entry.agentId,message:W.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),agentId:W.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1()}}import{sanitizeFileName as eb,TeamMessageType as m}from"@cline/shared";import{nanoid as $y}from"nanoid";import{TeamMessageType as ro}from"@cline/shared";function Pj($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function VU($,W){return $?.status==="stopped"&&Pj(W)}var Wy=600000,BU="recovered_queued";function Zy($){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.
523
-
524
- ${$.message}`}class S6{agents=new Map;configs=new Map;onTeamEvent;constructor($,W){if(this.onTeamEvent=W,$)for(let[Z,Q]of Object.entries($))this.addAgent(Z,Q)}addAgent($,W){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Z={...W,onEvent:(J)=>{W.onEvent?.(J),this.emitEvent({type:m.AgentEvent,agentId:$,event:J})}},Q=new C$(Z);if(Z.onEvent)Q.subscribeEvents(Z.onEvent);this.agents.set($,Q),this.configs.set($,W)}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($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.run(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async continueTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.continue(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async runParallel($){let W=$.map(async(Z)=>{let Q=this.agents.get(Z.agentId);if(!Q)return{agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata};this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),{agentId:Z.agentId,result:J,metadata:Z.metadata}}catch(J){let j=J instanceof Error?J:Error(String(J));return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),{agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata}}});return Promise.all(W)}async runSequential($){let W=[];for(let Z of $){let Q=this.agents.get(Z.agentId);if(!Q){W.push({agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata});continue}this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),W.push({agentId:Z.agentId,result:J,metadata:Z.metadata})}catch(J){let j=J instanceof Error?J:Error(String(J));this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),W.push({agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata})}}return W}async runPipeline($,W,Z){let Q=[],J=W;for(let j of $){let X=this.agents.get(j);if(!X){Q.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:m.TaskStart,agentId:j,message:J});try{let Y=await X.run(J);this.emitEvent({type:m.TaskEnd,agentId:j,result:Y}),Q.push({agentId:j,result:Y});let V=$.indexOf(j)+1;if(V<$.length){let B=$[V];J=Z?Z(Y,B):`Previous agent output:
517
+ FROM sessions WHERE session_id = ?`,[$]);if(!W)return;return{sessionId:V$(W.session_id),source:V$(W.source),pid:Number(W.pid??0),startedAt:V$(W.started_at),endedAt:W.ended_at??null,exitCode:W.exit_code??null,status:V$(W.status),interactive:j9(W.interactive),provider:V$(W.provider),model:V$(W.model),cwd:V$(W.cwd),workspaceRoot:V$(W.workspace_root),teamName:w1(W.team_name),enableTools:j9(W.enable_tools),enableSpawn:j9(W.enable_spawn),enableTeams:j9(W.enable_teams),parentSessionId:w1(W.parent_session_id),parentAgentId:w1(W.parent_agent_id),agentId:w1(W.agent_id),conversationId:w1(W.conversation_id),isSubagent:j9(W.is_subagent),prompt:w1(W.prompt),metadata:(()=>{let Z=w1(W.metadata_json);if(!Z)return;try{let Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:w1(W.hook_path),messagesPath:w1(W.messages_path),updatedAt:w1(W.updated_at)??zQ()}}list($=200){let W=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Z=[];for(let Q of W){let J=this.get(V$(Q.session_id));if(J)Z.push(J)}return Z}delete($,W=!1){let Z=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}}O8();import{existsSync as lj,mkdirSync as Ay,readFileSync as zU,renameSync as Uy,writeFileSync as Dy}from"node:fs";import{join as qU}from"node:path";import{resolveSessionDataDir as _y}from"@cline/shared/storage";import{dirname as Ky}from"node:path";import{nanoid as Fy}from"nanoid";import{appendFileSync as yb,existsSync as hb,mkdirSync as XU,readFileSync as kb,writeFileSync as YU}from"node:fs";import{readFile as VU,rm as Ib}from"node:fs/promises";import{dirname as BU,join as xb}from"node:path";import{ensureHookLogDir as gb}from"@cline/shared/storage";import{randomUUID as wb}from"node:crypto";import{mkdir as Cb,open as JU,rename as Pb,rm as Sb}from"node:fs/promises";import{dirname as QU}from"node:path";async function bb($){let W;try{W=await JU($,"r"),await W.sync()}catch{}finally{if(W!==void 0)try{await W.close()}catch{}}}async function jU($,W){await Cb(QU($),{recursive:!0});let Z=`${$}.${process.pid}.${wb()}.tmp`,Q;try{Q=await JU(Z,"wx"),await Q.writeFile(W,"utf8"),await Q.sync(),await Q.close(),Q=void 0,await Pb(Z,$),await bb(QU($))}catch(J){if(Q!==void 0)try{await Q.close()}catch{}try{await Sb(Z,{force:!0})}catch{}throw J}}function mb($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}class bj{adapter;messagesArtifactUploader;logger;artifacts;constructor($,W,Z){this.adapter=$;this.messagesArtifactUploader=W;this.logger=Z;this.artifacts=new tJ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,W,Z){FK(W,Z,_J($))}writeSessionManifest($,W){XU(BU($),{recursive:!0}),YU($,`${JSON.stringify(m0.parse(W),null,2)}
518
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}async readSessionManifestTitle($){let W=this.artifacts.sessionManifestPath($,!1),Z;try{Z=await VU(W,"utf8")}catch{return}try{let Q=JSON.parse(Z);if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J=Q.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let j=J.title;return typeof j==="string"?j:void 0}catch{return}}readManifestFile($){let W=this.artifacts.sessionManifestPath($,!1);if(!hb(W))return{path:W};try{return{path:W,manifest:m0.parse(JSON.parse(kb(W,"utf8")))}}catch{return{path:W}}}async resolveArtifactPath($,W,Z){let J=(await this.adapter.getSession($))?.[W];return typeof J==="string"&&J.trim().length>0?J:Z($)}async persistSessionMessages($,W,Z){let Q=await this.resolveArtifactPath($,"messagesPath",(X)=>this.artifacts.sessionMessagesPath(X)),J=fJ({updatedAt:X0(),context:_J($),messages:W,systemPrompt:Z}),j=`${JSON.stringify(J,null,2)}
519
+ `;if(XU(BU(Q),{recursive:!0}),YU(Q,j,"utf8"),!this.messagesArtifactUploader)return;try{let X=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:j,row:X})}catch(X){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:X})}}resolveCompactionPath($){let{manifest:W}=this.readManifestFile($);return W?.compaction_path?.trim()||this.artifacts.sessionCompactionPath($)}updateCompactionPath($,W){let Z=this.readManifestFile($);if(!Z.manifest)return;if(Z.manifest.compaction_path===W)return;this.writeSessionManifest(Z.path,{...Z.manifest,compaction_path:W})}async readSessionCompactionState($){let W=this.resolveCompactionPath($);try{return G1(JSON.parse(await VU(W,"utf8")))}catch(Z){if(mb(Z))return;this.logger?.debug("Ignoring invalid session compaction state",{sessionId:$,path:W,error:Z,recovery:"Canonical history is unchanged; deleting the sidecar is safe."});return}}async persistSessionCompactionState($,W){let Z=this.resolveCompactionPath($),Q=S4.parse(W);await jU(Z,`${JSON.stringify(Q,null,2)}
520
+ `),this.updateCompactionPath($,Z)}async deleteSessionCompactionState($){await Ib(this.resolveCompactionPath($),{force:!0}),this.updateCompactionPath($,void 0)}appendStaleSessionHookLog($,W,Z,Q,J){let X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??xb(gb(),"hooks.jsonl");yb(X,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:W,pid:Z,source:J})}
521
+ `,"utf8")}}import{appendFileSync as vb}from"node:fs";import{join as cb}from"node:path";import{resolveRootSessionId as HU}from"@cline/shared";import{ensureHookLogDir as ub}from"@cline/shared/storage";import{z as yj}from"zod";var db="subagent",lb=yj.looseObject({task:yj.string().optional(),systemPrompt:yj.string().optional()});class qQ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,W,Z,Q){this.adapter=$;this.manifestStore=W;this.toPersistedMessages=Z;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,W){return`${$}::${W}`}activeTeamTaskSessionId($,W){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,W))?.at(-1)}buildSubsessionRow($,W){return{sessionId:W.sessionId,source:db,pid:process.ppid,startedAt:W.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:W.parentSessionId,parentAgentId:W.parentAgentId,agentId:W.agentId,conversationId:W.conversationId??null,isSubagent:!0,prompt:W.prompt,metadata:G5({prompt:W.prompt}),hookPath:"",messagesPath:W.messagesPath,updatedAt:W.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let W=HU($.sessionContext);if(!W)return;let Z=lb.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:W,parentAgentId:$.agent_id,task:Z.success?Z.data.task:void 0,systemPrompt:Z.success?Z.data.systemPrompt:void 0})}async upsertSubagentSession($){let W=$.rootSessionId;if(!W)return;let Z=await this.adapter.getSession(W);if(!Z)return;let Q=s8(W,$.agentId),J=await this.adapter.getSession(Q),j=X0(),X=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(W,$.parentAgentId)),Y=$.prompt??J?.prompt??void 0;if(!Y)Y=await this.adapter.claimSpawnRequest(W,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:Q,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Y,startedAt:j,...X})),this.manifestStore.initializeMessagesFile(Q,X.messagesPath,j),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??Y??null,metadata:G5({metadata:J.metadata??void 0,prompt:J.prompt??Y??null}),expectedStatusLock:J.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let W=HU($.sessionContext);if(!W)return;if($.hookName==="session_shutdown"){let Z=s8(W,$.agent_id);return await this.adapter.getSession(Z)?Z:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:W})}async applySubagentStatus($,W){await this.applySubagentStatusBySessionId($,V5(W))}async applySubagentStatusBySessionId($,W){let Z=await this.adapter.getSession($);if(!Z)return;let Q=K0(W)?null:X0(),J=K0(W)?null:W==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:W,endedAt:Q,exitCode:J,expectedStatusLock:Z.statusLock})}async applyStatusToRunningChildSessions($,W){if(!$)return;let Z=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of Z)await this.applySubagentStatusBySessionId(Q.sessionId,W)}async onTeamTaskStart($,W,Z){let Q=await this.adapter.getSession($);if(!Q)return;let J=X5($,W),j=X0(),{messagesPath:X}=this.manifestStore.artifacts.subagentArtifactPaths(J,W);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:W,prompt:Z||`Team task for ${W}`,startedAt:j,messagesPath:X})),this.manifestStore.initializeMessagesFile(J,X,j);let Y=this.teamTaskQueueKey($,W),V=this.teamTaskSessionsByAgent.get(Y)??[];V.push(J),this.teamTaskSessionsByAgent.set(Y,V)}async onTeamTaskEnd($,W,Z,Q,J,j){let X=this.teamTaskQueueKey($,W),Y=this.teamTaskSessionsByAgent.get(X);if(!Y||Y.length===0)return;let V=Y.shift();if(Y.length===0)this.teamTaskSessionsByAgent.delete(X);if(!V)return;let B=J?.messages??j,H=this.toPersistedMessages(B,J,j);if(H)await this.manifestStore.persistSessionMessages(V,H);await this.applySubagentStatusBySessionId(V,Z),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,W,Z,Q){let J=this.teamTaskQueueKey($,W),j=this.teamTaskSessionsByAgent.get(J)?.[0];if(!j)return;let X=Z.trim();if(!X)return;let Y=Q?.kind??"progress";if(Y==="heartbeat"){let B=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(B-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,B)}let V=Y==="heartbeat"?"[progress] heartbeat":Y==="text"?`[progress] text: ${X}`:`[progress] ${X}`;if(this.teamTaskLastProgressLineBySession.get(j)===V)return;this.teamTaskLastProgressLineBySession.set(j,V)}async handleSubAgentStart($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;await this.applySubagentStatusBySessionId(Z,"running")}async handleSubAgentEnd($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;if(W.error){await this.applySubagentStatusBySessionId(Z,"failed");return}let Q=this.toPersistedMessages(W.agentResult?.messages,W.agentResult);if(Q)await this.manifestStore.persistSessionMessages(Z,Q);let J=W.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Z,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??cb(ub(),"hooks.jsonl");vb(Z,`${JSON.stringify({ts:X0(),...$})}
522
+ `,"utf8")}}import{formatUserInputBlock as Gy}from"@cline/shared";var OU={};w(OU,{toTeamProgressLifecycleEvent:()=>S6,sanitizeTeamName:()=>QK,reviveTeamStateDates:()=>GZ,parseConfiguredAgentConfig:()=>Y9,loadConfiguredAgentConfigs:()=>w6,createWorkerReviewerTeam:()=>TU,createSpawnAgentTool:()=>y$,createDelegatedAgentConfigProvider:()=>S$,createDelegatedAgent:()=>b$,createConfiguredAgentTools:()=>C6,createAgentTeamsTools:()=>S2,createAgentTeam:()=>Ij,buildTeamProgressSummary:()=>P6,buildDelegatedAgentConfig:()=>C2,buildConfiguredAgentToolName:()=>V9,buildConfiguredAgentToolDescriptors:()=>B9,bootstrapAgentTeams:()=>o8,AgentTeamsRuntime:()=>e2,AgentTeam:()=>y6});import{existsSync as pb,readdirSync as rb,readFileSync as ib}from"node:fs";import{basename as GU,extname as nb,join as ab}from"node:path";import{resolveAgentConfigSearchPaths as ob}from"@cline/shared/storage";import FU from"yaml";import{z as h0}from"zod";var AU=h0.object({name:h0.string().trim().min(1),description:h0.string().trim().min(1),tools:h0.union([h0.string(),h0.array(h0.string())]).optional(),skills:h0.union([h0.string(),h0.array(h0.string())]).optional(),providerId:h0.string().trim().min(1).optional(),modelId:h0.string().trim().min(1).optional(),maxIterations:h0.number().int().positive().optional()});function sb($){let W=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!W)throw Error("Missing YAML frontmatter block in agent config file.");let Z=W[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=Z;let J,j=Array.from($.matchAll(Q)).filter((X)=>X.index>=Z);for(let X of j){let Y=X.index,V=$.slice(Z,Y);try{let B=FU.parse(V);if(!B||typeof B!=="object"||Array.isArray(B))continue;AU.parse(B);let H=$.slice(Y+X[0].length);J={frontmatter:V,body:H}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function KU($){if($===void 0)return;let W=Array.isArray($)?$:$.split(",");return Array.from(new Set(W.map((Z)=>Z.trim()).filter((Z)=>Z.length>0)))}function tb($){return $.trim().toLowerCase()}function eb($){let W=nb($).toLowerCase();return W===".yml"||W===".yaml"}function Y9($,W={}){let{frontmatter:Z,body:Q}=sb($),J=FU.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let j=AU.parse(J),X=Q.trim();if(!X)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:KU(j.tools),skills:KU(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:X,path:W.path}}function w6($){let W=$.searchPaths??ob($.workspaceRoot),Z=new Map,Q=[];for(let j of W.filter(Boolean)){if(!pb(j))continue;let X;try{X=rb(j,{withFileTypes:!0})}catch(Y){Q.push({path:j,error:Y instanceof Error?Y:Error(String(Y))});continue}for(let Y of X){if(!Y.isFile()||!eb(Y.name))continue;let V=ab(j,Y.name);try{let B=ib(V,"utf8"),H=Y9(B,{path:V}),G=tb(H.name);if(!Z.has(G))Z.set(G,H)}catch(B){Q.push({path:V,error:B instanceof Error?B:Error(String(B))})}}}return{configs:Array.from(Z.values()).sort((j,X)=>(j.path?GU(j.path):j.name).localeCompare(X.path?GU(X.path):X.name)),errors:Q}}import{createTool as $y,zodToJsonSchema as Wy}from"@cline/shared";import{z as UU}from"zod";var hj="subagent_",MQ=64,Zy=UU.object({prompt:UU.string().trim().min(1).describe("Task for the subagent to perform")});function Qy($){let W="",Z=!0;for(let Q of $.trim().toLowerCase()){let J=Q.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||Q==="_")||Q==="_"){if(!Z)W+="_",Z=!0;continue}W+=Q,Z=!1}return Z?W.slice(0,-1):W}function Jy($){let W=2166136261;for(let Z=0;Z<$.length;Z++)W^=$.charCodeAt(Z),W=Math.imul(W,16777619);return(W>>>0).toString(36)}function V9($){let W=Qy($)||"agent",Z=Jy($).slice(0,6),Q=`${hj}${W}`;if(Q.length<=MQ)return Q;let J=MQ-hj.length-Z.length-1,j=W.slice(0,Math.max(1,J));return`${hj}${j}_${Z}`.slice(0,MQ)}function B9($){let W=new Set,Z=[];for(let Q of[...$].sort((J,j)=>J.name.localeCompare(j.name))){let J=V9(Q.name),j=J,X=2;while(W.has(j)){let Y=`_${X++}`,V=Math.max(1,MQ-Y.length);j=`${J.slice(0,V)}${Y}`}W.add(j),Z.push({toolName:j,config:Q})}return Z}function jy($,W){return{...$,providerId:W.providerId??$.providerId,modelId:W.modelId??$.modelId,maxIterations:W.maxIterations??$.maxIterations}}function C6($){return B9($.agents).map(({toolName:W,config:Z})=>{return $y({name:W,description:`Use the "${Z.name}" subagent: ${Z.description}`,inputSchema:Wy(Zy),execute:async(J,j)=>{let X=$.configProvider.getRuntimeConfig(),Y=S$(jy(X,Z)),V=$.createSubAgentTools?await $.createSubAgentTools(Z,J,j):[],B=b$({kind:"subagent",prompt:Z.systemPrompt,configProvider:Y,tools:V,maxIterations:Z.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=B.getAgentId(),G=B.getConversationId(),K=j.agentId,F={systemPrompt:Z.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await B.run(J.prompt),D={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,result:D,agentResult:A})}catch{}return D}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function P1(){return new Date().toISOString()}function DU($,W){if(W<=0)return 0;return Math.round($/W*100)}function Xy($,W){let Z=new Set;for(let J of W)if(J.status==="reviewed")Z.add(`${J.outcomeId}:${J.section}`);let Q=new Set;for(let J of $){if(J.status==="finalized")continue;for(let j of J.requiredSections)if(!Z.has(`${J.id}:${j}`))Q.add(`${J.id}:${j}`)}return[...Q].sort((J,j)=>J.localeCompare(j))}function P6($,W){let Z={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},X={draft:0,reviewed:0,rejected:0},Y=0,V=0;for(let U of W.members)if(Z[U.status]+=1,U.role==="lead")Y+=1;else V+=1;let B=[],H=[],G=W.tasks.filter((U)=>U.status==="completed").length,K=new Map(W.tasks.map((U)=>[U.id,U]));for(let U of W.tasks){if(Q[U.status]+=1,U.status==="blocked"){B.push(U.id);continue}if(U.status!=="pending")continue;if(U.dependsOn.every((_)=>{return K.get(_)?.status==="completed"}))H.push(U.id)}let F=[],A,D=0;for(let U of W.runs){if(J[U.status]+=1,U.status==="queued"||U.status==="running")F.push(U.id);let f=U.startedAt.getTime();if(f>=D)D=f,A=U.id}for(let U of W.outcomes)j[U.status]+=1;for(let U of W.outcomeFragments)X[U.status]+=1;return{teamName:$,updatedAt:P1(),members:{total:W.members.length,byStatus:Z,leadCount:Y,teammateCount:V},tasks:{total:W.tasks.length,byStatus:Q,blockedTaskIds:B,readyTaskIds:H,completionPct:DU(G,W.tasks.length)},runs:{total:W.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:W.outcomes.length,byStatus:j,finalizedPct:DU(j.finalized,W.outcomes.length),missingRequiredSections:Xy(W.outcomes,W.outcomeFragments)},fragments:{total:W.outcomeFragments.length,byStatus:X}}}function S6($){let{event:W}=$;switch(W.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.task.id,agentId:W.task.assignee??W.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:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.fragment.outcomeId,fragmentId:W.fragment.id,agentId:W.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.message.taskId,agentId:W.message.fromAgentId,message:W.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.entry.taskId,agentId:W.entry.agentId,message:W.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),agentId:W.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1()}}import{sanitizeFileName as Yy,TeamMessageType as m}from"@cline/shared";import{nanoid as Vy}from"nanoid";import{TeamMessageType as Zs}from"@cline/shared";function kj($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function _U($,W){return $?.status==="stopped"&&kj(W)}var By=600000,fU="recovered_queued";function Hy($){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.
523
+
524
+ ${$.message}`}class y6{agents=new Map;configs=new Map;onTeamEvent;constructor($,W){if(this.onTeamEvent=W,$)for(let[Z,Q]of Object.entries($))this.addAgent(Z,Q)}addAgent($,W){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Z={...W,onEvent:(J)=>{W.onEvent?.(J),this.emitEvent({type:m.AgentEvent,agentId:$,event:J})}},Q=new P$(Z);if(Z.onEvent)Q.subscribeEvents(Z.onEvent);this.agents.set($,Q),this.configs.set($,W)}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($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.run(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async continueTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.continue(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async runParallel($){let W=$.map(async(Z)=>{let Q=this.agents.get(Z.agentId);if(!Q)return{agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata};this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),{agentId:Z.agentId,result:J,metadata:Z.metadata}}catch(J){let j=J instanceof Error?J:Error(String(J));return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),{agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata}}});return Promise.all(W)}async runSequential($){let W=[];for(let Z of $){let Q=this.agents.get(Z.agentId);if(!Q){W.push({agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata});continue}this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),W.push({agentId:Z.agentId,result:J,metadata:Z.metadata})}catch(J){let j=J instanceof Error?J:Error(String(J));this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),W.push({agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata})}}return W}async runPipeline($,W,Z){let Q=[],J=W;for(let j of $){let X=this.agents.get(j);if(!X){Q.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:m.TaskStart,agentId:j,message:J});try{let Y=await X.run(J);this.emitEvent({type:m.TaskEnd,agentId:j,result:Y}),Q.push({agentId:j,result:Y});let V=$.indexOf(j)+1;if(V<$.length){let B=$[V];J=Z?Z(Y,B):`Previous agent output:
525
525
  ${Y.text}
526
526
 
527
- Please continue from here.`}}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.emitEvent({type:m.TaskEnd,agentId:j,error:V,messages:X.getMessages()}),Q.push({agentId:j,result:void 0,error:V});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function Sj($,W){return new S6($,W)}function GU($){let W=Sj({worker:$.worker,reviewer:$.reviewer}),Z=W;return Z.doAndReview=async(Q)=>{let J=await W.routeTo("worker",Q),j=await W.routeTo("reviewer",`Please review this work:
527
+ Please continue from here.`}}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.emitEvent({type:m.TaskEnd,agentId:j,error:V,messages:X.getMessages()}),Q.push({agentId:j,result:void 0,error:V});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function Ij($,W){return new y6($,W)}function TU($){let W=Ij({worker:$.worker,reviewer:$.reviewer}),Z=W;return Z.doAndReview=async(Q)=>{let J=await W.routeTo("worker",Q),j=await W.routeTo("reviewer",`Please review this work:
528
528
 
529
- ${J.text}`);return{workerResult:J,reviewResult:j}},Z}class t2{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${eb($y(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 W=$.leadAgentId??"lead";this.members.set(W,{agentId:W,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((W)=>{let Z=this.getUnresolvedDependencies(W);return{...W,blockedBy:Z,isReady:W.status==="pending"&&!W.assignee&&Z.length===0}}).filter((W)=>{if($?.status&&W.status!==$.status)return!1;if($?.assignee&&W.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,W){let Z=W?.unreadOnly??!0,Q=W?.markRead??!0,J=W?.limit,j=this.mailbox.filter((Y)=>Y.toAgentId===$&&(!Z||!Y.readAt)),X=typeof J==="number"&&J>0?j.slice(Math.max(0,j.length-J)):j;if(Q){let Y=new Date;for(let V of X)if(!V.readAt)V.readAt=Y}return X.map((Y)=>({...Y}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Z of this.tasks.values())$[Z.status]++;let W={draft:0,in_review:0,finalized:0};for(let Z of this.outcomes.values())W[Z.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Z)=>({agentId:Z.agentId,role:Z.role,description:Z.description,status:Z.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Z)=>!Z.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").length,outcomeCounts:W}}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 Z of $.tasks)this.tasks.set(Z.id,{...Z});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Z)=>({...Z}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Z)=>({...Z}))),this.runs.clear();for(let Z of $.runs??[])this.runs.set(Z.id,{...Z});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").map((Z)=>Z.id)),this.outcomes.clear();for(let Z of $.outcomes??[])this.outcomes.set(Z.id,{...Z});this.outcomeFragments.clear();for(let Z of $.outcomeFragments??[])this.outcomeFragments.set(Z.id,{...Z});let W=Array.from(this.members.values()).filter((Z)=>Z.role==="lead");this.members.clear();for(let Z of W)this.members.set(Z.agentId,{...Z,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Z of $.members){if(Z.role!=="teammate")continue;this.members.set(Z.agentId,{agentId:Z.agentId,role:"teammate",description:Z.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,P6($.tasks.map((Z)=>Z.id),"task_")),this.messageCounter=Math.max(this.messageCounter,P6($.mailbox.map((Z)=>Z.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,P6($.missionLog.map((Z)=>Z.id),"log_")),this.runCounter=Math.max(this.runCounter,P6(($.runs??[]).map((Z)=>Z.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,P6(($.outcomes??[]).map((Z)=>Z.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,P6(($.outcomeFragments??[]).map((Z)=>Z.id),"frag_"))}isTeammateActive($){let W=this.members.get($);return!!W&&W.role==="teammate"&&!!W.agent}spawnTeammate({agentId:$,config:W}){let Z=this.members.get($);if(Z&&Z.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Z&&Z.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...W,apiTimeoutMs:Wy,consumePendingUserMessage:()=>{let X=this.members.get($);if(!X||!X.pendingSteerMessage)return;let Y=X.pendingSteerMessage;return X.pendingSteerMessage=void 0,Y},onEvent:(X)=>{W.onEvent?.(X),this.emitEvent({type:m.AgentEvent,agentId:$,event:X}),this.trackMeaningfulEvent($,X)}},J=new C$(Q);if(Q.onEvent)J.subscribeEvents(Q.onEvent);let j={agentId:$,role:"teammate",description:W.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:m.TeammateSpawned,agentId:$,role:W.role,teammate:{rolePrompt:W.systemPrompt,modelId:W.modelId,maxIterations:W.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,W){let Z=this.members.get($);if(!Z||Z.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Z.agent?.abort()}catch(Q){if(!Pj(Q))throw Q}Z.status="stopped",this.emitEvent({type:m.TeammateShutdown,agentId:$,reason:W})}updateTeammateConnections($){for(let W of this.members.values()){if(W.role!=="teammate"||!W.agent)continue;W.agent.updateConnection($)}}createTask($){let W=`task_${String(++this.taskCounter).padStart(4,"0")}`,Z=new Date,Q={id:W,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Z,updatedAt:Z,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(W,Q),this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,W){let Z=this.requireTask($);return this.assertDependenciesResolved(Z),Z.status="in_progress",Z.assignee=W,Z.updatedAt=new Date,this.emitEvent({type:m.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:W,taskId:$,kind:"progress",summary:`Claimed task "${Z.title}"`}),{...Z}}blockTask($,W,Z){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=Z,this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"blocked",summary:Z}),{...Q}}completeTask($,W,Z){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=Z,!Q.assignee)Q.assignee=W;return this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"done",summary:Z}),{...Q}}async routeToTeammate($,W,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=J.length>0?`${this.buildMailboxNotification(J)}
529
+ ${J.text}`);return{workerResult:J,reviewResult:j}},Z}class e2{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_${Yy(Vy(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 W=$.leadAgentId??"lead";this.members.set(W,{agentId:W,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((W)=>{let Z=this.getUnresolvedDependencies(W);return{...W,blockedBy:Z,isReady:W.status==="pending"&&!W.assignee&&Z.length===0}}).filter((W)=>{if($?.status&&W.status!==$.status)return!1;if($?.assignee&&W.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,W){let Z=W?.unreadOnly??!0,Q=W?.markRead??!0,J=W?.limit,j=this.mailbox.filter((Y)=>Y.toAgentId===$&&(!Z||!Y.readAt)),X=typeof J==="number"&&J>0?j.slice(Math.max(0,j.length-J)):j;if(Q){let Y=new Date;for(let V of X)if(!V.readAt)V.readAt=Y}return X.map((Y)=>({...Y}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Z of this.tasks.values())$[Z.status]++;let W={draft:0,in_review:0,finalized:0};for(let Z of this.outcomes.values())W[Z.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Z)=>({agentId:Z.agentId,role:Z.role,description:Z.description,status:Z.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Z)=>!Z.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").length,outcomeCounts:W}}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 Z of $.tasks)this.tasks.set(Z.id,{...Z});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Z)=>({...Z}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Z)=>({...Z}))),this.runs.clear();for(let Z of $.runs??[])this.runs.set(Z.id,{...Z});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").map((Z)=>Z.id)),this.outcomes.clear();for(let Z of $.outcomes??[])this.outcomes.set(Z.id,{...Z});this.outcomeFragments.clear();for(let Z of $.outcomeFragments??[])this.outcomeFragments.set(Z.id,{...Z});let W=Array.from(this.members.values()).filter((Z)=>Z.role==="lead");this.members.clear();for(let Z of W)this.members.set(Z.agentId,{...Z,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Z of $.members){if(Z.role!=="teammate")continue;this.members.set(Z.agentId,{agentId:Z.agentId,role:"teammate",description:Z.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,b6($.tasks.map((Z)=>Z.id),"task_")),this.messageCounter=Math.max(this.messageCounter,b6($.mailbox.map((Z)=>Z.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,b6($.missionLog.map((Z)=>Z.id),"log_")),this.runCounter=Math.max(this.runCounter,b6(($.runs??[]).map((Z)=>Z.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,b6(($.outcomes??[]).map((Z)=>Z.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,b6(($.outcomeFragments??[]).map((Z)=>Z.id),"frag_"))}isTeammateActive($){let W=this.members.get($);return!!W&&W.role==="teammate"&&!!W.agent}spawnTeammate({agentId:$,config:W}){let Z=this.members.get($);if(Z&&Z.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Z&&Z.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...W,apiTimeoutMs:By,consumePendingUserMessage:()=>{let X=this.members.get($);if(!X||!X.pendingSteerMessage)return;let Y=X.pendingSteerMessage;return X.pendingSteerMessage=void 0,Y},onEvent:(X)=>{W.onEvent?.(X),this.emitEvent({type:m.AgentEvent,agentId:$,event:X}),this.trackMeaningfulEvent($,X)}},J=new P$(Q);if(Q.onEvent)J.subscribeEvents(Q.onEvent);let j={agentId:$,role:"teammate",description:W.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:m.TeammateSpawned,agentId:$,role:W.role,teammate:{rolePrompt:W.systemPrompt,modelId:W.modelId,maxIterations:W.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,W){let Z=this.members.get($);if(!Z||Z.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Z.agent?.abort()}catch(Q){if(!kj(Q))throw Q}Z.status="stopped",this.emitEvent({type:m.TeammateShutdown,agentId:$,reason:W})}updateTeammateConnections($){for(let W of this.members.values()){if(W.role!=="teammate"||!W.agent)continue;W.agent.updateConnection($)}}createTask($){let W=`task_${String(++this.taskCounter).padStart(4,"0")}`,Z=new Date,Q={id:W,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Z,updatedAt:Z,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(W,Q),this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,W){let Z=this.requireTask($);return this.assertDependenciesResolved(Z),Z.status="in_progress",Z.assignee=W,Z.updatedAt=new Date,this.emitEvent({type:m.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:W,taskId:$,kind:"progress",summary:`Claimed task "${Z.title}"`}),{...Z}}blockTask($,W,Z){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=Z,this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"blocked",summary:Z}),{...Q}}completeTask($,W,Z){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=Z,!Q.assignee)Q.assignee=W;return this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"done",summary:Z}),{...Q}}async routeToTeammate($,W,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=J.length>0?`${this.buildMailboxNotification(J)}
530
530
 
531
- ${W}`:W,X=Z?.continueConversation?await Q.agent.continue(j):await Q.agent.run(j);return this.emitEvent({type:m.TaskEnd,agentId:$,result:X}),this.recordProgressStep($,`Completed a delegated run (${X.iterations} iterations)`,Z?.taskId,!0),X}catch(J){let j=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:m.TaskEnd,agentId:$,error:j,messages:Q.agent.getMessages()}),!VU(Q,j))this.appendMissionLog({agentId:$,taskId:Z?.taskId,kind:"error",summary:j.message});throw j}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,W,Z){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:Q,agentId:$,taskId:Z?.taskId,status:"queued",message:W,priority:Z?.priority??0,retryCount:0,maxRetries:Math.max(0,Z?.maxRetries??0),continueConversation:Z?.continueConversation,startedAt:new Date(0),leaseOwner:Z?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,J),this.runQueue.push(Q),this.emitEvent({type:m.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let W=this.selectNextDispatchableQueuedRun();$=W.nextDelayedAttemptAt;let Z=W.index;if(Z<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(Z,1),J=Q?this.runs.get(Q):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,W=Number.NEGATIVE_INFINITY,Z,Q=Date.now();for(let J=0;J<this.runQueue.length;J++){let j=this.runs.get(this.runQueue[J]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Q){if(!Z||j.nextAttemptAt<Z)Z=j.nextAttemptAt;continue}if(j.priority>W)W=j.priority,$=J}return{index:$,nextDelayedAttemptAt:Z}}scheduleQueuedRunDispatch($){if(!$)return;let W=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},W)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let W of this.runs.values())if(W.status==="running")$++;return $}async executeQueuedRun($){let W=$.currentActivity===BU;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:m.RunStarted,run:{...$}});let Z=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=W?Zy($):$.message,J=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:m.RunCompleted,run:{...$}})}catch(Q){let J=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=J,$.endedAt=new Date;let j=this.members.get($.agentId);if(VU(j,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:m.RunCancelled,run:{...$},reason:J});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:m.RunFailed,run:{...$}})}finally{clearInterval(Z),this.dispatchQueuedRuns()}}listRuns($){let W=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Z)=>{if(!W&&!["running","queued"].includes(Z.status))return!1;if($?.status&&Z.status!==$.status)return!1;if($?.agentId&&Z.agentId!==$.agentId)return!1;return!0}).map((Z)=>({...Z}))}getRun($){let W=this.runs.get($);return W?{...W}:void 0}async awaitRun($,W=250){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);while(Z.status==="queued"||Z.status==="running")await HU(W);return{...Z}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((W)=>["queued","running"].includes(W.status)))await HU($);return this.listRuns()}cancelRun($,W){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);if(Z.status==="completed"||Z.status==="failed")return{...Z};Z.status="cancelled",Z.error=W,Z.endedAt=new Date,Z.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:m.RunCancelled,run:{...Z},reason:W}),{...Z}}recoverActiveRuns($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;let Q=this.members.get(Z.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){Z.status="interrupted",Z.error="teammate_unavailable_after_recovery",Z.endedAt=new Date,Z.currentActivity="interrupted",this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:Z.error});continue}let J=new Date;if(Z.status="queued",Z.error=void 0,Z.endedAt=void 0,Z.heartbeatAt=J,Z.lastProgressAt=J,Z.lastProgressMessage=$,Z.currentActivity=BU,!this.runQueue.includes(Z.id))this.runQueue.push(Z.id);W.push({...Z}),this.emitEvent({type:m.RunQueued,run:{...Z}})}return this.dispatchQueuedRuns(),W}markStaleRunsInterrupted($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;Z.status="interrupted",Z.error=$,Z.endedAt=new Date,Z.currentActivity="interrupted",W.push({...Z}),this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),W}sendMessage($,W,Z,Q,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(W);if(!j)throw Error(`Unknown recipient "${W}"`);let X={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:W,subject:Z,body:Q,taskId:J,sentAt:new Date};if(this.mailbox.push(X),this.emitEvent({type:m.TeamMessage,message:{...X}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Z}". Use the team_read_mailbox tool to read it at your convenience.`;return{...X}}broadcast($,W,Z,Q){let J=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;J.push(this.sendMessage($,j.agentId,W,Z,Q?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let W={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(W);let Z=this.members.get($.agentId);if(Z)Z.lastMissionAt=Date.now(),Z.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:m.TeamMissionLog,entry:{...W}}),{...W}}createOutcome($){let W={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(W.id,W),this.emitEvent({type:m.OutcomeCreated,outcome:{...W}}),{...W}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let W=this.outcomes.get($.outcomeId);if(!W)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!W.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Z={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(Z.id,Z),W.status==="draft")W.status="in_review";return this.emitEvent({type:m.OutcomeFragmentAttached,fragment:{...Z}}),{...Z}}reviewOutcomeFragment($){let W=this.outcomeFragments.get($.fragmentId);if(!W)throw Error(`Fragment "${$.fragmentId}" was not found`);return W.status=$.approved?"reviewed":"rejected",W.reviewedBy=$.reviewedBy,W.reviewedAt=new Date,this.emitEvent({type:m.OutcomeFragmentReviewed,fragment:{...W}}),{...W}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((W)=>W.outcomeId===$).map((W)=>({...W}))}finalizeOutcome($){let W=this.outcomes.get($);if(!W)throw Error(`Outcome "${$}" was not found`);let Z=this.listOutcomeFragments($);for(let Q of W.requiredSections)if(!Z.some((j)=>j.section===Q&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return W.status="finalized",W.finalizedAt=new Date,this.emitEvent({type:m.OutcomeFinalized,outcome:{...W}}),{...W}}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(W){if(!Pj(W))throw W}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[$,W]of this.members.entries())if(W.role==="teammate")this.members.delete($)}requireTask($){let W=this.tasks.get($);if(!W)throw Error(`Task "${$}" was not found`);return W}assertDependenciesResolved($){let W=this.getUnresolvedDependencies($);if(W.length>0)throw Error(`Task "${$.id}" is blocked by "${W[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((W)=>{let Z=this.tasks.get(W);return!Z||Z.status!=="completed"})}trackMeaningfulEvent($,W){if(this.recordRunActivityFromAgentEvent($,W),W.type==="iteration_end"&&W.hadToolCalls){this.recordProgressStep($,`Completed iteration ${W.iteration} with ${W.toolCallCount} tool call(s)`);return}if(W.type==="content_end"&&W.contentType==="tool"&&!W.error){this.recordProgressStep($,`Finished tool "${W.toolName??"unknown"}"`);return}if(W.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${W.iterations} iterations)`});return}if(W.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:W.error.message})}recordRunActivityFromAgentEvent($,W){let Z;switch(W.type){case"iteration_start":Z=`iteration_${W.iteration}_started`;break;case"content_start":if(W.contentType==="tool")Z=`running_tool_${W.toolName??"unknown"}`;break;case"content_end":if(W.contentType==="tool")Z=W.error?this.formatProgressErrorActivity(`tool_${W.toolName??"unknown"}_error`,W.error):`finished_tool_${W.toolName??"unknown"}`;break;case"done":Z="finalizing_response";break;case"error":Z=this.formatProgressErrorActivity("run_error",W.error.message);break;default:break}if(!Z)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,Z)}}recordRunProgress($,W){let Z=new Date;$.heartbeatAt=Z,$.lastProgressAt=Z,$.lastProgressMessage=W,$.currentActivity=W,this.emitEvent({type:m.RunProgress,run:{...$},message:W})}formatProgressErrorActivity($,W){let Z=W.replace(/\s+/g," ").trim();if(Z.length===0)return $;let Q=Z.length>240?`${Z.slice(0,237).trimEnd()}...`:Z;return`${$}: ${Q}`}recordProgressStep($,W,Z,Q=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let j=this.missionStepCounter-J.lastMissionStep,X=Date.now()-J.lastMissionAt;if(!Q&&j<this.missionLogIntervalSteps&&X<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Z,kind:"progress",summary:W})}buildMailboxNotification($){if($.length===0)return"";let W=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Z of $)W.push(`--- Message from ${Z.fromAgentId} | subject: ${Z.subject} ---`),W.push(Z.body);return W.push("---"),W.join(`
532
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function HU($){return new Promise((W)=>setTimeout(W,$))}function P6($,W){let Z=0;for(let Q of $){if(!Q.startsWith(W))continue;let J=Number.parseInt(Q.slice(W.length),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return Z}function bj($,W){switch(W.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(W.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Z;if(W.type==="run_failed")Z=W.run.error;else if(W.type==="run_cancelled"||W.type==="run_interrupted")Z=W.run.error??W.reason;$.activeTeamRunIds.delete(W.run.id),$.pendingTeamRunUpdates.push({runId:W.run.id,agentId:W.run.agentId,taskId:W.run.taskId,status:W.type.replace("run_",""),error:Z,iterations:W.run.result?.iterations}),fQ($);break}default:break}}async function yj($,W,Z){switch(W.type){case"run_progress":await Z("onTeamTaskProgress",$,W.run.agentId,W.message,{kind:W.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(W.event.type==="content_start"&&W.event.contentType==="text"&&typeof W.event.text==="string"){let Q=W.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await Z("onTeamTaskProgress",$,W.agentId,Q,{kind:"text"})}break;case"task_start":await Z("onTeamTaskStart",$,W.agentId,W.message);break;case"task_end":{if(W.error)await Z("onTeamTaskEnd",$,W.agentId,"failed",`[error] ${W.error.message}`,void 0,W.messages);else if(W.result?.finishReason==="aborted")await Z("onTeamTaskEnd",$,W.agentId,"cancelled","[done] aborted",W.result,W.result.messages);else await Z("onTeamTaskEnd",$,W.agentId,"completed",`[done] ${W.result?.finishReason??"completed"}`,W.result,W.result?.messages);break}default:break}}function hj($,W,Z,Q){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:W,teamName:J,lifecycle:C6({teamName:J,sessionId:W,event:Z}),summary:w6(J,$.runtime.teamRuntime.exportState())}})}function VW($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function kj($,W){if($.aborting)return!1;if(!(W==="completed"||W==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&VW($)}function fQ($){let W=$.teamRunWaiters.splice(0);for(let Z of W)Z()}async function Ij($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let W=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,W}if($.activeTeamRunIds.size===0)return[];await new Promise((W)=>{$.teamRunWaiters.push(W)})}}function xj($,W){let Z=W.map((j)=>{let X=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)X.push(` task=${j.taskId}`);if(typeof j.iterations==="number")X.push(` iterations=${j.iterations}`);if(j.error)X.push(` error=${j.error}`);return X.join("")}),Q=$.activeTeamRunIds.size,J=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return BW(`System-delivered teammate async run updates:
531
+ ${W}`:W,X=Z?.continueConversation?await Q.agent.continue(j):await Q.agent.run(j);return this.emitEvent({type:m.TaskEnd,agentId:$,result:X}),this.recordProgressStep($,`Completed a delegated run (${X.iterations} iterations)`,Z?.taskId,!0),X}catch(J){let j=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:m.TaskEnd,agentId:$,error:j,messages:Q.agent.getMessages()}),!_U(Q,j))this.appendMissionLog({agentId:$,taskId:Z?.taskId,kind:"error",summary:j.message});throw j}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,W,Z){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:Q,agentId:$,taskId:Z?.taskId,status:"queued",message:W,priority:Z?.priority??0,retryCount:0,maxRetries:Math.max(0,Z?.maxRetries??0),continueConversation:Z?.continueConversation,startedAt:new Date(0),leaseOwner:Z?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,J),this.runQueue.push(Q),this.emitEvent({type:m.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let W=this.selectNextDispatchableQueuedRun();$=W.nextDelayedAttemptAt;let Z=W.index;if(Z<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(Z,1),J=Q?this.runs.get(Q):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,W=Number.NEGATIVE_INFINITY,Z,Q=Date.now();for(let J=0;J<this.runQueue.length;J++){let j=this.runs.get(this.runQueue[J]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Q){if(!Z||j.nextAttemptAt<Z)Z=j.nextAttemptAt;continue}if(j.priority>W)W=j.priority,$=J}return{index:$,nextDelayedAttemptAt:Z}}scheduleQueuedRunDispatch($){if(!$)return;let W=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},W)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let W of this.runs.values())if(W.status==="running")$++;return $}async executeQueuedRun($){let W=$.currentActivity===fU;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:m.RunStarted,run:{...$}});let Z=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=W?Hy($):$.message,J=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:m.RunCompleted,run:{...$}})}catch(Q){let J=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=J,$.endedAt=new Date;let j=this.members.get($.agentId);if(_U(j,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:m.RunCancelled,run:{...$},reason:J});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:m.RunFailed,run:{...$}})}finally{clearInterval(Z),this.dispatchQueuedRuns()}}listRuns($){let W=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Z)=>{if(!W&&!["running","queued"].includes(Z.status))return!1;if($?.status&&Z.status!==$.status)return!1;if($?.agentId&&Z.agentId!==$.agentId)return!1;return!0}).map((Z)=>({...Z}))}getRun($){let W=this.runs.get($);return W?{...W}:void 0}async awaitRun($,W=250){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);while(Z.status==="queued"||Z.status==="running")await LU(W);return{...Z}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((W)=>["queued","running"].includes(W.status)))await LU($);return this.listRuns()}cancelRun($,W){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);if(Z.status==="completed"||Z.status==="failed")return{...Z};Z.status="cancelled",Z.error=W,Z.endedAt=new Date,Z.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:m.RunCancelled,run:{...Z},reason:W}),{...Z}}recoverActiveRuns($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;let Q=this.members.get(Z.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){Z.status="interrupted",Z.error="teammate_unavailable_after_recovery",Z.endedAt=new Date,Z.currentActivity="interrupted",this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:Z.error});continue}let J=new Date;if(Z.status="queued",Z.error=void 0,Z.endedAt=void 0,Z.heartbeatAt=J,Z.lastProgressAt=J,Z.lastProgressMessage=$,Z.currentActivity=fU,!this.runQueue.includes(Z.id))this.runQueue.push(Z.id);W.push({...Z}),this.emitEvent({type:m.RunQueued,run:{...Z}})}return this.dispatchQueuedRuns(),W}markStaleRunsInterrupted($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;Z.status="interrupted",Z.error=$,Z.endedAt=new Date,Z.currentActivity="interrupted",W.push({...Z}),this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),W}sendMessage($,W,Z,Q,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(W);if(!j)throw Error(`Unknown recipient "${W}"`);let X={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:W,subject:Z,body:Q,taskId:J,sentAt:new Date};if(this.mailbox.push(X),this.emitEvent({type:m.TeamMessage,message:{...X}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Z}". Use the team_read_mailbox tool to read it at your convenience.`;return{...X}}broadcast($,W,Z,Q){let J=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;J.push(this.sendMessage($,j.agentId,W,Z,Q?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let W={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(W);let Z=this.members.get($.agentId);if(Z)Z.lastMissionAt=Date.now(),Z.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:m.TeamMissionLog,entry:{...W}}),{...W}}createOutcome($){let W={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(W.id,W),this.emitEvent({type:m.OutcomeCreated,outcome:{...W}}),{...W}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let W=this.outcomes.get($.outcomeId);if(!W)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!W.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Z={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(Z.id,Z),W.status==="draft")W.status="in_review";return this.emitEvent({type:m.OutcomeFragmentAttached,fragment:{...Z}}),{...Z}}reviewOutcomeFragment($){let W=this.outcomeFragments.get($.fragmentId);if(!W)throw Error(`Fragment "${$.fragmentId}" was not found`);return W.status=$.approved?"reviewed":"rejected",W.reviewedBy=$.reviewedBy,W.reviewedAt=new Date,this.emitEvent({type:m.OutcomeFragmentReviewed,fragment:{...W}}),{...W}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((W)=>W.outcomeId===$).map((W)=>({...W}))}finalizeOutcome($){let W=this.outcomes.get($);if(!W)throw Error(`Outcome "${$}" was not found`);let Z=this.listOutcomeFragments($);for(let Q of W.requiredSections)if(!Z.some((j)=>j.section===Q&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return W.status="finalized",W.finalizedAt=new Date,this.emitEvent({type:m.OutcomeFinalized,outcome:{...W}}),{...W}}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(W){if(!kj(W))throw W}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[$,W]of this.members.entries())if(W.role==="teammate")this.members.delete($)}requireTask($){let W=this.tasks.get($);if(!W)throw Error(`Task "${$}" was not found`);return W}assertDependenciesResolved($){let W=this.getUnresolvedDependencies($);if(W.length>0)throw Error(`Task "${$.id}" is blocked by "${W[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((W)=>{let Z=this.tasks.get(W);return!Z||Z.status!=="completed"})}trackMeaningfulEvent($,W){if(this.recordRunActivityFromAgentEvent($,W),W.type==="iteration_end"&&W.hadToolCalls){this.recordProgressStep($,`Completed iteration ${W.iteration} with ${W.toolCallCount} tool call(s)`);return}if(W.type==="content_end"&&W.contentType==="tool"&&!W.error){this.recordProgressStep($,`Finished tool "${W.toolName??"unknown"}"`);return}if(W.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${W.iterations} iterations)`});return}if(W.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:W.error.message})}recordRunActivityFromAgentEvent($,W){let Z;switch(W.type){case"iteration_start":Z=`iteration_${W.iteration}_started`;break;case"content_start":if(W.contentType==="tool")Z=`running_tool_${W.toolName??"unknown"}`;break;case"content_end":if(W.contentType==="tool")Z=W.error?this.formatProgressErrorActivity(`tool_${W.toolName??"unknown"}_error`,W.error):`finished_tool_${W.toolName??"unknown"}`;break;case"done":Z="finalizing_response";break;case"error":Z=this.formatProgressErrorActivity("run_error",W.error.message);break;default:break}if(!Z)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,Z)}}recordRunProgress($,W){let Z=new Date;$.heartbeatAt=Z,$.lastProgressAt=Z,$.lastProgressMessage=W,$.currentActivity=W,this.emitEvent({type:m.RunProgress,run:{...$},message:W})}formatProgressErrorActivity($,W){let Z=W.replace(/\s+/g," ").trim();if(Z.length===0)return $;let Q=Z.length>240?`${Z.slice(0,237).trimEnd()}...`:Z;return`${$}: ${Q}`}recordProgressStep($,W,Z,Q=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let j=this.missionStepCounter-J.lastMissionStep,X=Date.now()-J.lastMissionAt;if(!Q&&j<this.missionLogIntervalSteps&&X<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Z,kind:"progress",summary:W})}buildMailboxNotification($){if($.length===0)return"";let W=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Z of $)W.push(`--- Message from ${Z.fromAgentId} | subject: ${Z.subject} ---`),W.push(Z.body);return W.push("---"),W.join(`
532
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function LU($){return new Promise((W)=>setTimeout(W,$))}function b6($,W){let Z=0;for(let Q of $){if(!Q.startsWith(W))continue;let J=Number.parseInt(Q.slice(W.length),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return Z}function xj($,W){switch(W.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(W.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Z;if(W.type==="run_failed")Z=W.run.error;else if(W.type==="run_cancelled"||W.type==="run_interrupted")Z=W.run.error??W.reason;$.activeTeamRunIds.delete(W.run.id),$.pendingTeamRunUpdates.push({runId:W.run.id,agentId:W.run.agentId,taskId:W.run.taskId,status:W.type.replace("run_",""),error:Z,iterations:W.run.result?.iterations}),RQ($);break}default:break}}async function gj($,W,Z){switch(W.type){case"run_progress":await Z("onTeamTaskProgress",$,W.run.agentId,W.message,{kind:W.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(W.event.type==="content_start"&&W.event.contentType==="text"&&typeof W.event.text==="string"){let Q=W.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await Z("onTeamTaskProgress",$,W.agentId,Q,{kind:"text"})}break;case"task_start":await Z("onTeamTaskStart",$,W.agentId,W.message);break;case"task_end":{if(W.error)await Z("onTeamTaskEnd",$,W.agentId,"failed",`[error] ${W.error.message}`,void 0,W.messages);else if(W.result?.finishReason==="aborted")await Z("onTeamTaskEnd",$,W.agentId,"cancelled","[done] aborted",W.result,W.result.messages);else await Z("onTeamTaskEnd",$,W.agentId,"completed",`[done] ${W.result?.finishReason??"completed"}`,W.result,W.result?.messages);break}default:break}}function mj($,W,Z,Q){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:W,teamName:J,lifecycle:S6({teamName:J,sessionId:W,event:Z}),summary:P6(J,$.runtime.teamRuntime.exportState())}})}function H9($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function vj($,W){if($.aborting)return!1;if(!(W==="completed"||W==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&H9($)}function RQ($){let W=$.teamRunWaiters.splice(0);for(let Z of W)Z()}async function cj($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let W=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,W}if($.activeTeamRunIds.size===0)return[];await new Promise((W)=>{$.teamRunWaiters.push(W)})}}function uj($,W){let Z=W.map((j)=>{let X=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)X.push(` task=${j.taskId}`);if(typeof j.iterations==="number")X.push(` iterations=${j.iterations}`);if(j.error)X.push(` error=${j.error}`);return X.join("")}),Q=$.activeTeamRunIds.size,J=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return G9(`System-delivered teammate async run updates:
533
533
  ${Z.join(`
534
534
  `)}
535
535
 
536
- ${J}`,$.config.mode)}function BW($,W){return Qy($,W==="plan"?"plan":W==="yolo"?"yolo":"act")}var gj=4;class V${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,W={}){this.adapter=$;this.manifestStore=new Ej($,W.messagesArtifactUploader,W.logger),this.teamChildren=new AQ($,this.manifestStore,(Z,Q,J)=>this.toPersistedMessages(Z,Q,J),V$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,W,Z){if(!$)return;return W?YZ(W.messages,W,Z):XZ($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,W){this.manifestStore.writeSessionManifest($,W)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let W=$.startedAt??X0(),Z=$.sessionId.trim(),Q=Z.length>0?Z:`${Date.now()}_${jy(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(Q),j=this.manifestStore.artifacts.sessionCompactionPath(Q),X=this.manifestStore.artifacts.sessionManifestPath(Q),Y=B5({metadata:$.metadata,prompt:$.prompt}),V={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:W,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:Y,messages_path:J};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:W,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:V.prompt??null,metadata:y$(V.metadata),hookPath:"",messagesPath:J,updatedAt:X0()}),this.manifestStore.initializeMessagesFile(Q,J,W),this.manifestStore.writeSessionManifest(X,V),{manifestPath:X,messagesPath:J,compactionPath:j,manifest:V}}async updateSessionStatus($,W,Z){let Q;if((await XK(()=>this.adapter.getSession($),async(j)=>{return Q=K0(W)?void 0:X0(),this.adapter.updateSession({sessionId:$,status:W,endedAt:Q??null,exitCode:K0(W)?null:typeof Z==="number"?Z:null,expectedStatusLock:j.statusLock})},gj)).updated){if(W==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let W=0;W<gj;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return{updated:!1};let Q=Z.metadata??void 0,J=$.metadata!==void 0?y$($.metadata)??{}:y$(Q)??{},j=h2(typeof Q?.title==="string"?Q.title:void 0),X=$.title!==void 0?h2($.title):j??GJ($.prompt);if(X)J.title=X;else delete J.title;let Y=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:Y?Object.keys(J).length>0?J:null:void 0,title:X,expectedStatusLock:Z.statusLock})).updated)continue;let{path:B,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let G=$.metadata!==void 0?y$($.metadata)??{}:y$(H.metadata)??{};if(X)G.title=X;H.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(B,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,W){return this.teamChildren.appendSubagentHookAudit(W),Promise.resolve()}persistSessionMessages($,W,Z){let Q=XZ(W);return this.manifestStore.persistSessionMessages($,Q,Z)}async readSessionCompactionState($){return await this.manifestStore.readSessionCompactionState($)}async persistSessionCompactionState($,W){await this.manifestStore.persistSessionCompactionState($,W)}async deleteSessionCompactionState($){await this.manifestStore.deleteSessionCompactionState($)}applySubagentStatus($,W){return this.teamChildren.applySubagentStatus($,W)}applySubagentStatusBySessionId($,W){return this.teamChildren.applySubagentStatusBySessionId($,W)}applyStatusToRunningChildSessions($,W){return this.teamChildren.applyStatusToRunningChildSessions($,W)}onTeamTaskStart($,W,Z){return this.teamChildren.onTeamTaskStart($,W,Z)}onTeamTaskEnd($,W,Z,Q,J,j){return this.teamChildren.onTeamTaskEnd($,W,Z,Q,J,j)}onTeamTaskProgress($,W,Z,Q){return this.teamChildren.onTeamTaskProgress($,W,Z,Q)}handleSubAgentStart($,W){return this.teamChildren.handleSubAgentStart($,W)}handleSubAgentEnd($,W){return this.teamChildren.handleSubAgentEnd($,W)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(W){return typeof W==="object"&&W!==null&&"code"in W&&W.code==="EPERM"}}async reconcileDeadRunningSession($){if(K0($.status)===!1||this.isPidAlive($.pid))return $;let W=X0(),Z=V$.STALE_REASON;for(let Q=0;Q<gj;Q++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(K0(J.status)===!1)return J;let j={...J.metadata??{},terminal_marker:Z,terminal_marker_at:W,terminal_marker_pid:J.pid,terminal_marker_source:V$.STALE_SOURCE},X=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:W,exitCode:1,metadata:j,expectedStatusLock:J.statusLock});if(!X.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let Y=jK(J,{status:"failed",endedAt:W,exitCode:1,metadata:j}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,Y),this.manifestStore.appendStaleSessionHookLog(W,J.sessionId,J.pid,Z,V$.STALE_SOURCE),{...J,status:"failed",endedAt:W,exitCode:1,metadata:j,statusLock:X.statusLock,updatedAt:W}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let W=Math.max(1,Math.floor($)),Z=Math.min(W*5,2000);await this.reconcileDeadSessions(Z);let Q=(await this.adapter.listSessions({limit:Z})).slice(0,W),J=await Promise.all(Q.map((j)=>this.manifestStore.readSessionManifestTitle(j.sessionId)));return Q.map((j,X)=>{let Y=y$(j.metadata??void 0),V=h2(J[X]),B=V?{...Y??{},title:V}:Y;return{...j,metadata:B}})}async reconcileDeadSessions($=2000){let W=Math.max(1,Math.floor($)),Z=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:W,status:J})))).flat(),Q=0;for(let J of Z){let j=await this.reconcileDeadRunningSession(J);if(j&&j.status!==J.status)Q++}return Q}async deleteSession($){let W=$.trim();if(!W)throw Error("session id is required");let Z=await this.adapter.getSession(W);if(!Z)return{deleted:!1};if(await this.adapter.deleteSession(W,!1),!Z.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:W});await this.adapter.deleteSession(W,!0),await Promise.allSettled(Q.map(async(J)=>{await bJ(J.cwd,J.sessionId),E5(J.messagesPath),await this.deleteSessionCompactionStateIfExists(J.sessionId),E5(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await bJ(Z.cwd,W),E5(Z.messagesPath),await this.deleteSessionCompactionStateIfExists(W),E5(this.manifestStore.artifacts.sessionManifestPath(W,!1)),Z.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(W);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(W)]);for(let J of[Z.messagesPath])if(typeof J==="string"&&J.trim().length>0)Q.add(Jy(J));for(let J of Q)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}async deleteSessionCompactionStateIfExists($){try{await this.manifestStore.deleteSessionCompactionState($)}catch{}}}function vj(){return new Date().toISOString()}function UU($,W){let Z=`${$}.tmp`;Vy(Z,`${JSON.stringify(W,null,2)}
537
- `,"utf8"),Yy(Z,$)}class fU{sessionsDirPath;constructor($=By()){this.sessionsDirPath=$}ensureSessionsDir(){if(!mj(this.sessionsDirPath))Xy(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return AU(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return AU(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!mj($))return{version:1,sessions:{}};try{let W=JSON.parse(FU($,"utf8"));if(W?.version===1&&W.sessions)return W}catch{}return{version:1,sessions:{}}}writeIndex($){UU(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!mj($))return{version:1,nextId:1,requests:[]};try{let W=JSON.parse(FU($,"utf8"));if(W?.version===1&&typeof W.nextId==="number"&&Array.isArray(W.requests))return W}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){UU(this.spawnQueuePath(),$)}async upsertSession($){let W=this.readIndex();W.sessions[$.sessionId]=$,this.writeIndex(W)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((W)=>$.parentSessionId!==void 0?W.parentSessionId===$.parentSessionId:!0).filter((W)=>$.status!==void 0?W.status===$.status:!0).sort((W,Z)=>Z.startedAt.localeCompare(W.startedAt)).slice(0,$.limit)}async updateSession($){let W=this.readIndex(),Z=W.sessions[$.sessionId];if(!Z)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Z.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Z.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Z.statusLock,J={...Z,status:$.status??Z.status,endedAt:$.endedAt!==void 0?$.endedAt:Z.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Z.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Z.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Z.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Z.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Z.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Z.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Z.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Z.isSubagent,updatedAt:vj()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return W.sessions[$.sessionId]=J,this.writeIndex(W),{updated:!0,statusLock:J.statusLock}}async deleteSession($,W){let Z=this.readIndex();if(!Z.sessions[$])return!1;if(delete Z.sessions[$],W){for(let J of Object.values(Z.sessions))if(J.parentSessionId===$)delete Z.sessions[J.sessionId]}return this.writeIndex(Z),!0}async enqueueSpawnRequest($){let W=this.readQueue();W.requests.push({id:W.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:vj()}),W.nextId+=1,this.writeQueue(W)}async claimSpawnRequest($,W){let Z=this.readQueue(),Q=Z.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===W&&!J.consumedAt);if(!Q)return;return Q.consumedAt=vj(),this.writeQueue(Z),Q.task}}class cj extends V${constructor($,W={}){super(new fU($),W)}ensureSessionsDir(){return super.ensureSessionsDir()}}var LU={};w(LU,{CoreSessionService:()=>S1});import{existsSync as Hy,mkdirSync as Gy}from"node:fs";import{resolveSessionDataDir as Ky}from"@cline/shared/storage";var uj=`
536
+ ${J}`,$.config.mode)}function G9($,W){return Gy($,W==="plan"?"plan":W==="yolo"?"yolo":"act")}var dj=4;class B${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,W={}){this.adapter=$;this.manifestStore=new bj($,W.messagesArtifactUploader,W.logger),this.teamChildren=new qQ($,this.manifestStore,(Z,Q,J)=>this.toPersistedMessages(Z,Q,J),B$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,W,Z){if(!$)return;return W?DZ(W.messages,W,Z):UZ($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,W){this.manifestStore.writeSessionManifest($,W)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let W=$.startedAt??X0(),Z=$.sessionId.trim(),Q=Z.length>0?Z:`${Date.now()}_${Fy(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(Q),j=this.manifestStore.artifacts.sessionCompactionPath(Q),X=this.manifestStore.artifacts.sessionManifestPath(Q),Y=G5({metadata:$.metadata,prompt:$.prompt}),V={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:W,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:Y,messages_path:J};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:W,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:V.prompt??null,metadata:h$(V.metadata),hookPath:"",messagesPath:J,updatedAt:X0()}),this.manifestStore.initializeMessagesFile(Q,J,W),this.manifestStore.writeSessionManifest(X,V),{manifestPath:X,messagesPath:J,compactionPath:j,manifest:V}}async updateSessionStatus($,W,Z){let Q;if((await UK(()=>this.adapter.getSession($),async(j)=>{return Q=K0(W)?void 0:X0(),this.adapter.updateSession({sessionId:$,status:W,endedAt:Q??null,exitCode:K0(W)?null:typeof Z==="number"?Z:null,expectedStatusLock:j.statusLock})},dj)).updated){if(W==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let W=0;W<dj;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return{updated:!1};let Q=Z.metadata??void 0,J=$.metadata!==void 0?h$($.metadata)??{}:h$(Q)??{},j=k2(typeof Q?.title==="string"?Q.title:void 0),X=$.title!==void 0?k2($.title):j??DJ($.prompt);if(X)J.title=X;else delete J.title;let Y=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:Y?Object.keys(J).length>0?J:null:void 0,title:X,expectedStatusLock:Z.statusLock})).updated)continue;let{path:B,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let G=$.metadata!==void 0?h$($.metadata)??{}:h$(H.metadata)??{};if(X)G.title=X;H.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(B,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,W){return this.teamChildren.appendSubagentHookAudit(W),Promise.resolve()}persistSessionMessages($,W,Z){let Q=UZ(W);return this.manifestStore.persistSessionMessages($,Q,Z)}async readSessionCompactionState($){return await this.manifestStore.readSessionCompactionState($)}async persistSessionCompactionState($,W){await this.manifestStore.persistSessionCompactionState($,W)}async deleteSessionCompactionState($){await this.manifestStore.deleteSessionCompactionState($)}applySubagentStatus($,W){return this.teamChildren.applySubagentStatus($,W)}applySubagentStatusBySessionId($,W){return this.teamChildren.applySubagentStatusBySessionId($,W)}applyStatusToRunningChildSessions($,W){return this.teamChildren.applyStatusToRunningChildSessions($,W)}onTeamTaskStart($,W,Z){return this.teamChildren.onTeamTaskStart($,W,Z)}onTeamTaskEnd($,W,Z,Q,J,j){return this.teamChildren.onTeamTaskEnd($,W,Z,Q,J,j)}onTeamTaskProgress($,W,Z,Q){return this.teamChildren.onTeamTaskProgress($,W,Z,Q)}handleSubAgentStart($,W){return this.teamChildren.handleSubAgentStart($,W)}handleSubAgentEnd($,W){return this.teamChildren.handleSubAgentEnd($,W)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(W){return typeof W==="object"&&W!==null&&"code"in W&&W.code==="EPERM"}}async reconcileDeadRunningSession($){if(K0($.status)===!1||this.isPidAlive($.pid))return $;let W=X0(),Z=B$.STALE_REASON;for(let Q=0;Q<dj;Q++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(K0(J.status)===!1)return J;let j={...J.metadata??{},terminal_marker:Z,terminal_marker_at:W,terminal_marker_pid:J.pid,terminal_marker_source:B$.STALE_SOURCE},X=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:W,exitCode:1,metadata:j,expectedStatusLock:J.statusLock});if(!X.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let Y=AK(J,{status:"failed",endedAt:W,exitCode:1,metadata:j}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,Y),this.manifestStore.appendStaleSessionHookLog(W,J.sessionId,J.pid,Z,B$.STALE_SOURCE),{...J,status:"failed",endedAt:W,exitCode:1,metadata:j,statusLock:X.statusLock,updatedAt:W}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let W=Math.max(1,Math.floor($)),Z=Math.min(W*5,2000);await this.reconcileDeadSessions(Z);let Q=(await this.adapter.listSessions({limit:Z})).slice(0,W),J=await Promise.all(Q.map((j)=>this.manifestStore.readSessionManifestTitle(j.sessionId)));return Q.map((j,X)=>{let Y=h$(j.metadata??void 0),V=k2(J[X]),B=V?{...Y??{},title:V}:Y;return{...j,metadata:B}})}async reconcileDeadSessions($=2000){let W=Math.max(1,Math.floor($)),Z=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:W,status:J})))).flat(),Q=0;for(let J of Z){let j=await this.reconcileDeadRunningSession(J);if(j&&j.status!==J.status)Q++}return Q}async deleteSession($){let W=$.trim();if(!W)throw Error("session id is required");let Z=await this.adapter.getSession(W);if(!Z)return{deleted:!1};if(await this.adapter.deleteSession(W,!1),!Z.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:W});await this.adapter.deleteSession(W,!0),await Promise.allSettled(Q.map(async(J)=>{await xJ(J.cwd,J.sessionId),C5(J.messagesPath),await this.deleteSessionCompactionStateIfExists(J.sessionId),C5(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await xJ(Z.cwd,W),C5(Z.messagesPath),await this.deleteSessionCompactionStateIfExists(W),C5(this.manifestStore.artifacts.sessionManifestPath(W,!1)),Z.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(W);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(W)]);for(let J of[Z.messagesPath])if(typeof J==="string"&&J.trim().length>0)Q.add(Ky(J));for(let J of Q)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}async deleteSessionCompactionStateIfExists($){try{await this.manifestStore.deleteSessionCompactionState($)}catch{}}}function pj(){return new Date().toISOString()}function MU($,W){let Z=`${$}.tmp`;Dy(Z,`${JSON.stringify(W,null,2)}
537
+ `,"utf8"),Uy(Z,$)}class RU{sessionsDirPath;constructor($=_y()){this.sessionsDirPath=$}ensureSessionsDir(){if(!lj(this.sessionsDirPath))Ay(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return qU(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return qU(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!lj($))return{version:1,sessions:{}};try{let W=JSON.parse(zU($,"utf8"));if(W?.version===1&&W.sessions)return W}catch{}return{version:1,sessions:{}}}writeIndex($){MU(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!lj($))return{version:1,nextId:1,requests:[]};try{let W=JSON.parse(zU($,"utf8"));if(W?.version===1&&typeof W.nextId==="number"&&Array.isArray(W.requests))return W}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){MU(this.spawnQueuePath(),$)}async upsertSession($){let W=this.readIndex();W.sessions[$.sessionId]=$,this.writeIndex(W)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((W)=>$.parentSessionId!==void 0?W.parentSessionId===$.parentSessionId:!0).filter((W)=>$.status!==void 0?W.status===$.status:!0).sort((W,Z)=>Z.startedAt.localeCompare(W.startedAt)).slice(0,$.limit)}async updateSession($){let W=this.readIndex(),Z=W.sessions[$.sessionId];if(!Z)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Z.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Z.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Z.statusLock,J={...Z,status:$.status??Z.status,endedAt:$.endedAt!==void 0?$.endedAt:Z.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Z.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Z.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Z.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Z.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Z.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Z.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Z.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Z.isSubagent,updatedAt:pj()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return W.sessions[$.sessionId]=J,this.writeIndex(W),{updated:!0,statusLock:J.statusLock}}async deleteSession($,W){let Z=this.readIndex();if(!Z.sessions[$])return!1;if(delete Z.sessions[$],W){for(let J of Object.values(Z.sessions))if(J.parentSessionId===$)delete Z.sessions[J.sessionId]}return this.writeIndex(Z),!0}async enqueueSpawnRequest($){let W=this.readQueue();W.requests.push({id:W.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:pj()}),W.nextId+=1,this.writeQueue(W)}async claimSpawnRequest($,W){let Z=this.readQueue(),Q=Z.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===W&&!J.consumedAt);if(!Q)return;return Q.consumedAt=pj(),this.writeQueue(Z),Q.task}}class rj extends B${constructor($,W={}){super(new RU($),W)}ensureSessionsDir(){return super.ensureSessionsDir()}}var wU={};w(wU,{CoreSessionService:()=>S1});import{existsSync as fy,mkdirSync as Ly}from"node:fs";import{resolveSessionDataDir as Ty}from"@cline/shared/storage";var ij=`
538
538
  session_id AS sessionId,
539
539
  source,
540
540
  pid,
@@ -561,33 +561,33 @@ ${J}`,$.config.mode)}function BW($,W){return Qy($,W==="plan"?"plan":W==="yolo"?"
561
561
  metadata_json AS metadata,
562
562
  hook_path AS hookPath,
563
563
  messages_path AS messagesPath,
564
- updated_at AS updatedAt`;function dj($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let W=$.metadata;if(typeof W==="string"&&W.trim())try{let Z=JSON.parse(W);$.metadata=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:null}catch{$.metadata=null}else $.metadata=null;return $}function lj($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function DU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class _U{store;sessionsDirPath;constructor($,W=Ky()){this.store=$;this.sessionsDirPath=W}ensureSessionsDir(){if(!Hy(this.sessionsDirPath))Gy(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
564
+ updated_at AS updatedAt`;function nj($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let W=$.metadata;if(typeof W==="string"&&W.trim())try{let Z=JSON.parse(W);$.metadata=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:null}catch{$.metadata=null}else $.metadata=null;return $}function aj($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function EU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class NU{store;sessionsDirPath;constructor($,W=Ty()){this.store=$;this.sessionsDirPath=W}ensureSessionsDir(){if(!fy(this.sessionsDirPath))Ly(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
565
565
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
566
566
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
567
567
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
568
568
  metadata_json, transcript_path, hook_path, messages_path, updated_at
569
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,lj($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let W=this.store.queryOne(`SELECT ${uj} FROM sessions WHERE session_id = ?`,[$]);return W?dj(W):void 0}async listSessions($){let W=[],Z=[];if($.parentSessionId)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.status)W.push("status = ?"),Z.push($.status);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${uj}
569
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,aj($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let W=this.store.queryOne(`SELECT ${ij} FROM sessions WHERE session_id = ?`,[$]);return W?nj(W):void 0}async listSessions($){let W=[],Z=[];if($.parentSessionId)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.status)W.push("status = ?"),Z.push($.status);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${ij}
570
570
  FROM sessions
571
571
  ${Q}
572
572
  ORDER BY started_at DESC
573
- LIMIT ?`,[...Z,$.limit]).map(dj)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
573
+ LIMIT ?`,[...Z,$.limit]).map(nj)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
574
574
  SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
575
575
  parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
576
576
  prompt = COALESCE(prompt, ?)
577
- WHERE session_id = ? AND status_lock = ?`,[X0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let W=[],Z=[];if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt??null);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push(lj($.metadata));if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId??null);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId??null);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId??null);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId??null);if(W.length===0){let X=await this.getSession($.sessionId);return{updated:!!X,statusLock:X?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,W.push("status_lock = ?"),Z.push(Q);W.push("updated_at = ?"),Z.push(X0());let J=`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`;if(Z.push($.sessionId),$.expectedStatusLock!==void 0)J+=" AND status_lock = ?",Z.push($.expectedStatusLock);if((this.store.run(J,Z).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,W){let Z=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
577
+ WHERE session_id = ? AND status_lock = ?`,[X0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let W=[],Z=[];if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt??null);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push(aj($.metadata));if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId??null);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId??null);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId??null);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId??null);if(W.length===0){let X=await this.getSession($.sessionId);return{updated:!!X,statusLock:X?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,W.push("status_lock = ?"),Z.push(Q);W.push("updated_at = ?"),Z.push(X0());let J=`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`;if(Z.push($.sessionId),$.expectedStatusLock!==void 0)J+=" AND status_lock = ?",Z.push($.expectedStatusLock);if((this.store.run(J,Z).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,W){let Z=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
578
578
  VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,X0()])}async claimSpawnRequest($,W){let Z=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
579
579
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
580
- ORDER BY id ASC LIMIT 1`,[$,W]);if(!Z||typeof Z.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[X0(),Z.id]),Z.task??void 0}}class S1 extends V${store;constructor($,W={}){super(new _U($,W.sessionArtifactsDir),W);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
580
+ ORDER BY id ASC LIMIT 1`,[$,W]);if(!Z||typeof Z.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[X0(),Z.id]),Z.task??void 0}}class S1 extends B${store;constructor($,W={}){super(new NU($,W.sessionArtifactsDir),W);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
581
581
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
582
582
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
583
583
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
584
584
  metadata_json, transcript_path, hook_path, messages_path, updated_at
585
- ) 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,X0()])}}function Fy($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let W=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(W==="local"||W==="hub"||W==="remote")return W;return"auto"}var HW,GW;function Ay($,W){if($!=="auto"&&$!=="hub")return;if(W.hub?.endpoint?.trim())return;D9(W.hub?.workspaceRoot?.trim()||W.hub?.cwd?.trim()||process.cwd())}async function Uy($){await $.reconcileDeadSessions?.().catch(()=>{})}function zU($){try{let W=new C1;return W.init(),new S1(W,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(W){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),OU($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:W,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new cj(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function TU($,W,Z){return new b1({sessionService:Z??$.sessionService??zU($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:W,fetch:$.fetch})}async function pj($){if(HW)return HW;if(GW)return await GW;return GW=(async()=>{return HW=zU($),await Uy(HW),HW})().finally(()=>{GW=void 0}),await GW}async function b6($){let W=I0($.distinctId);$.telemetry?.setDistinctId(W);let Z=Fy($);if(Ay(Z,$),Z==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new R6({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Z==="hub"){let Q=$.hub?.endpoint?.trim(),J=Q||await B2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!J)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:J,explicitEndpoint:Q||void 0}),new X$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Z==="auto"){let Q=await _4({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let J=new X$({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await J.connect(),J}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),OU($.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"}),TU($,W)}return TU($,W)}var NU={};w(NU,{NoOpFeatureFlagsProvider:()=>$8,FeatureFlagsService:()=>e2});import{existsSync as fy,mkdirSync as Dy,readFileSync as _y,writeFileSync as Ly}from"node:fs";import{dirname as Ty}from"node:path";import{FEATURE_FLAGS as MU,FeatureFlagDefaultValue as rj}from"@cline/shared";var Oy=3600000,zy=604800000,RU=1;class e2{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??Oy,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??zy,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 W=$??this.context.userId??null,Z=Date.now();if(Z-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===W)return}let Q=this.cacheInfo;this.cacheInfo={updateTime:Z,userId:W||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:MU.length>0?MU:void 0,context:{...this.context,userId:W}});if(this.cacheInfo.userId!==W)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==W)return;throw this.cacheInfo=Q.updateTime?Q:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:J}),J}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((W)=>this.isFeatureFlagPayload(W));if(typeof $==="object")return Object.values($).every((W)=>this.isFeatureFlagPayload(W));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=Object.entries($).filter(([,Q])=>this.isFeatureFlagPayload(Q));if(W.length===0)return;let Z={};for(let[Q,J]of W)Z[Q]=J;return Z}readPersistentCache(){try{if(!this.cacheFilePath||!fy(this.cacheFilePath))return;let $=JSON.parse(_y(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let W=$;if(W.version!==RU||typeof W.updatedAt!=="number"||!Number.isFinite(W.updatedAt)||Date.now()-W.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:W.updatedAt,userId:W.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(W.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(W.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;Dy(Ty(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),W={version:RU,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};Ly(this.cacheFilePath,`${JSON.stringify(W,null,2)}
586
- `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let W=new Map;for(let Z of this.getReturnedFlagKeys($)){let Q=this.getFeatureFlag(Z);W.set(Z,Q??!1)}this.cache=W}getFeatureFlag($){try{let W=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Z=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=W??Z??rj[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:v.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Z}});return Q}catch(W){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:W}),rj[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??rj[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,W){if(process.env.IS_TEST==="true")this.cache.set($,W)}async dispose(){await this.provider.dispose()}}class $8{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}L8();var yU={};w(yU,{createCheckpointComparePlan:()=>_Q,compareCheckpointToWorkspace:()=>KW,buildCheckpointWorkspaceDiff:()=>LQ});import{execFile as Ry}from"node:child_process";import*as SU from"node:fs/promises";import*as k6 from"node:path";import{promisify as Ny}from"node:util";var CU={};w(CU,{trimMessagesToCheckpoint:()=>wU,trimMessagesBeforeCheckpoint:()=>nj,readSessionCheckpointHistory:()=>W8,findCheckpointForRun:()=>h6,createRestoredCheckpointMetadata:()=>ij,createCheckpointRestorePlan:()=>aj,applyCheckpointToWorktree:()=>oj});import{execFile as qy}from"node:child_process";import{promisify as My}from"node:util";var y6=My(qy);function W8($){let W=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(W?.history)?W.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let J=String(Q.ref??"").trim(),j=Number(Q.createdAt??0),X=Number(Q.runCount??0);if(J.length===0||!Number.isFinite(j)||!Number.isInteger(X)||X<1)return[];let Y=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:J,createdAt:j,runCount:X,...Y?{kind:Y}:{}}]})}function ij($,W){let Z=W8($).filter((J)=>J.runCount<=W),Q=Z.at(-1);return Q?{latest:Q,history:Z}:void 0}function h6($,W){return $.reduce((Z,Q)=>{if(Q.runCount>W)return Z;if(!Z||Q.runCount>Z.runCount)return Q;return Z},void 0)}function EU($,W){let Z=0;for(let Q=0;Q<$.length;Q+=1){let J=$[Q];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Z+=1,Z===W)return Q}throw Error(`Could not find user message for checkpoint run ${W}`)}function wU($,W){let Z=EU($,W);return $.slice(0,Z+1)}function nj($,W){let Z=EU($,W);return $.slice(0,Z)}function aj($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=h6(W8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Z,cwd:Q,...$.restoreMessages!==!1?{messages:wU($.messages??[],W)}:{}}}async function oj($,W){if((await y6("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await y6("git",["-C",$,"cat-file","-e",`${W.ref}^{commit}`],{windowsHide:!0}),await y6("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await y6("git",["-C",$,"clean","-fd"],{windowsHide:!0}),W.kind==="commit"){await y6("git",["-C",$,"reset","--hard",W.ref],{windowsHide:!0});return}await y6("git",["-C",$,"stash","apply",W.ref],{windowsHide:!0})}var Ey=Ny(Ry),wy=52428800;async function DQ($,W){let{stdout:Z}=await Ey("git",["-C",$,...W],{windowsHide:!0,maxBuffer:wy,encoding:"utf8"});return Z}function PU($){return $.split("\x00").filter(Boolean)}function bU($,W){let Z=k6.resolve($,W),Q=k6.relative($,Z);if(Q.startsWith("..")||k6.isAbsolute(Q))throw Error(`Checkpoint diff path escapes workspace: ${W}`);return Z}async function Cy($,W,Z){try{return await DQ($,["show",`${W}:${Z}`])}catch{return""}}async function Py($,W){try{return await SU.readFile(bU($,W),"utf8")}catch{return""}}async function Sy($,W){await DQ($,["cat-file","-e",`${W.ref}^{tree}`]);let[Z,Q]=await Promise.all([DQ($,["diff","--name-only","-z",W.ref,"--"]),DQ($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...PU(Z),...PU(Q)])].sort((j,X)=>j.localeCompare(X))}function _Q($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=h6(W8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Z,cwd:Q}}async function LQ($,W){let Z=await Sy($,W);return(await Promise.all(Z.map(async(J)=>{let[j,X]=await Promise.all([Cy($,W.ref,J),Py($,J)]);return{filePath:bU($,J),leftContent:j,rightContent:X}}))).filter((J)=>J.leftContent!==J.rightContent)}async function KW($){let W=_Q($),Z=await LQ(W.cwd,W.checkpoint);return{...W,diffs:Z}}class FW{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,W,Z,Q,J,j,X,Y,V,B){this.clientName=W,this.runtimeAddress=Z,this.host=$,this.prepare=Q,this.capabilities=J,this.logger=j,this.telemetry=X,this.distinctId=Y,this.featureFlags=V,this.settings=fA($),this.pendingPrompts=DA($),this.automation=new nJ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=B?new e5({workspaceRoot:B.workspaceRoot??process.cwd(),specs:{cronSpecsDir:B.cronSpecsDir??B.cronDir,scope:KF(B.cronScope),workspaceRoot:B.workspaceRoot},runtimeHandlers:FF({host:$,getExtensionContext:()=>lZ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:B.dbPath,logger:B.logger,pollIntervalMs:B.pollIntervalMs,claimLeaseSeconds:B.claimLeaseSeconds,globalMaxConcurrency:B.globalMaxConcurrency,watcherDebounceMs:B.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let W=I0($.distinctId),Z=C0($.capabilities),Q={...$,capabilities:Z,distinctId:W},J=await b6(Q),j=GF($.automation),X=$.featureFlags||new e2({provider:new $8,telemetry:$.telemetry,logger:$.logger,context:{distinctId:W,clientName:$.clientName}}),Y=new FW(J,$.clientName,J.runtimeAddress,$.prepare,Z,$.logger,$.telemetry,W,X,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await Y.automation.start();return Y}async disposeSessionBootstrap($){let W=this.activeSessionBootstraps.get($);if(!W)return;this.activeSessionBootstraps.delete($),await Promise.resolve(W.dispose?.())}async start($){let W=_A($),Z=await this.prepare?.(W);try{let Q=Z?await Z.applyToStartSessionInput(W):W,J=await this.host.startSession(Gj(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>lZ({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Z)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Z);else await Promise.resolve(Z.dispose?.());return LA({input:Q,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(Q){throw await Promise.resolve(Z?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let W=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(W.map((Z)=>this.disposeSessionBootstrap(Z)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await GQ(this.host,$);list=async($=200,W={})=>await this.listHistory({...W,limit:$});delete=async($)=>{let W=await this.host.deleteSession($);if(W)await this.disposeSessionBootstrap($);return W};update=(...$)=>this.host.updateSession(...$);updateSessionCompactionState=(...$)=>this.host.updateSessionCompactionState(...$);readSessionCompactionState=(...$)=>this.host.readSessionCompactionState(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let W=$.start?Gj($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Z)=>lZ({automationService:this.automationService,automation:this.automation,context:Z,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:W})}async compareCheckpoint($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=await this.host.getSession(W);if(!Z)throw Error(`Session ${W} not found`);return KW({session:Z,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,W){return this.host.subscribe($,W)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()};updateSessionConnection=(...$)=>{return this.host.updateSessionConnection?.(...$)??Promise.resolve()}}var kU={};w(kU,{resolvePluginSkillDirectoriesFromPaths:()=>Q$,resolvePluginConfigSearchPaths:()=>U5,resolveAndLoadAgentPlugins:()=>J6,resolveAgentPluginPaths:()=>Z$,loadAgentPluginsFromPathsWithDiagnostics:()=>I2,loadAgentPluginsFromPaths:()=>BZ,loadAgentPluginFromPath:()=>F5,discoverPluginModulePaths:()=>f5});var gU={};w(gU,{toHookConfigFileName:()=>L5,runSubprocessEvent:()=>I6,runHook:()=>g6,resolveHooksConfigSearchPaths:()=>D5,parseHookEventPayload:()=>x6,mergeAgentHooks:()=>v2,listHookConfigFiles:()=>k$,createSubprocessHooks:()=>zQ,createHookConfigFileHooks:()=>T5,createHookConfigFileExtension:()=>V6,createHookAuditHooks:()=>Y6,createAgentHooksExtension:()=>j6,HookEventPayloadSchema:()=>OQ,HookEventNameSchema:()=>TQ,HookConfigFileName:()=>X6,HOOK_CONFIG_FILE_EVENT_MAP:()=>_5,HOOKS_CONFIG_DIRECTORY_NAME:()=>UZ});import{HookEventNameSchema as TQ,HookEventPayloadSchema as OQ,parseHookEventPayload as x6,resolveHookSessionContext as gy}from"@cline/shared";import{z as Z8}from"zod";import{spawn as by}from"node:child_process";import{augmentNodeCommandForDebug as yy,withResolvedClineBuildEnv as hy}from"@cline/shared";function ky($){let W=$.trim();if(!W)return{};let Q=W.split(`
587
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function Iy($,W){let Z=$ instanceof Error?$:Error(String($)),Q=Z,J=W.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${J}" (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 "${J}": ${Z.message}`)}async function xy($,W){let Z=$.stdin;if(!Z)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,J)=>{let j=(X)=>{Z.off("error",j);let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X)};Z.once("error",j),Z.end(W,(X)=>{if(Z.off("error",j),X){let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X);return}Q()})})}async function I6($,W){let Z=yy(W.command,{env:W.env,debugRole:"hook"});if(!Array.isArray(Z)||Z.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!W.detached,J=by(Z[0],Z.slice(1),{cwd:W.cwd,env:hy(W.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),j=new Promise((K)=>{J.once("spawn",()=>{try{W.onSpawn?.({command:Z,pid:J.pid??void 0,detached:Q})}catch{}K()})}),X=new Promise((K,F)=>{J.once("error",(A)=>{F(Iy(A,Z))})});if(await xy(J,JSON.stringify($)),Q){await Promise.race([j,X]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let Y="",V="",B=!1,H;J.stdout.on("data",(K)=>{Y+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,J.kill("SIGKILL")},W.timeoutMs);J.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:f}=ky(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:f,timedOut:B})})});return await Promise.race([G,X])}var my=Z8.object({contextModification:Z8.string().optional(),cancel:Z8.boolean().optional(),review:Z8.boolean().optional(),errorMessage:Z8.string().optional(),context:Z8.string().optional(),overrideInput:Z8.unknown().optional()}).passthrough();var vy=["agent","hook"];async function g6($,W={}){let Z=W.command??vy;return await I6($,{command:Z,cwd:W.cwd,env:W.env,detached:W.detached,timeoutMs:W.timeoutMs,onSpawn:W.onSpawn})}function xU($){return $ instanceof Error?$:Error(String($))}function cy($){if(!$||typeof $!=="object")return;let W=my.safeParse($);if(!W.success)return;let Z=W.data;if(!(("cancel"in Z)||("review"in Z)||("context"in Z)||("contextModification"in Z)||("overrideInput"in Z)||("errorMessage"in Z)))return;let J=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"&&Z.errorMessage.length>0?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:J,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function IU($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q;else W[Z]=JSON.stringify(Q);return W}function B$($,W,Z){let Q=Z.env??process.env,J=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",j=Z.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:W.conversationId,sessionContext:gy(Z.sessionContext,{hookName:$,conversationId:W.conversationId,agentId:W.agentId,parentAgentId:W.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Z.workspaceInfo,userId:J,agent_id:W.agentId,parent_agent_id:W.parentAgentId}}function uy($){return{name:$.name,message:$.message,stack:$.stack}}function dy($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function ly($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function py($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function ry($){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 iy($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}async function Q8($,W){try{let Z=await g6($,{command:W.command,cwd:W.cwd,env:W.env,detached:!0,onSpawn:W.onSpawn});W.onDispatch?.({payload:$,result:Z,detached:!0})}catch(Z){W.onDispatchError?.(xU(Z),$)}}function zQ($={}){return{hooks:{beforeRun:async(Y)=>{let V=ly(Y);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...B$("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await Q8(H,$)}else{let H={...B$("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await Q8(H,$)}return},beforeTool:async(Y)=>{let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...B$("tool_call",V,$),hookName:"tool_call",iteration:Y.snapshot.iteration,tool_call:{id:Y.toolCall.toolCallId,name:Y.toolCall.toolName,input:Y.input},preToolUse:{toolName:Y.toolCall.toolName,parameters:IU(Y.input)}};try{let H=await g6(B,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:B,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 iy(cy(H?.parsedJson))}catch(H){$.onDispatchError?.(xU(H),B);return}},afterTool:async(Y)=>{let V=ry(Y),B={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},H={...B$("tool_result",B,$),hookName:"tool_result",iteration:Y.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:IU(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await Q8(H,$);return},afterRun:async({snapshot:Y,result:V})=>{let B={agentId:Y.agentId,conversationId:Y.conversationId??Y.runId??Y.agentId,parentAgentId:Y.parentAgentId??null};if(V.status==="completed"){let K={...B$("agent_end",B,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await Q8(K,$);return}let H=V.status==="aborted"||dy(V.error?.message)?"agent_abort":"agent_error",G=H==="agent_error"?{...B$(H,B,$),hookName:H,iteration:V.iterations,error:uy(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...B$(H,B,$),hookName:H,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await Q8(G,$)},onEvent:async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...B$("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:py(Y.message.content),attachments:[]}};await Q8(B,$)}},shutdown:async({agentId:Y,conversationId:V,parentAgentId:B,reason:H})=>{let G={...B$("session_shutdown",{agentId:Y,conversationId:V,parentAgentId:B},$),hookName:"session_shutdown",reason:H};await Q8(G,$)}}}qQ();var vU={};w(vU,{registerRemoteConfigSessionBlobUpload:()=>NQ,readRemoteConfigSessionBlobUploadMetadata:()=>sj,prepareRemoteConfigCoreIntegration:()=>ej,createRemoteConfigSessionMessagesArtifactUploader:()=>tj,buildRemoteConfigSessionBlobUploadMetadata:()=>MQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>RQ});import{buildRemoteConfigSessionBlobUploadMetadata as MQ,clearRemoteConfigSessionBlobUpload as ny,createClineTelemetryServiceConfig as ay,createSessionId as oy,createRemoteConfigSessionMessagesArtifactUploader as sy,prepareRemoteConfigRuntime as ty,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as RQ,readRemoteConfigSessionBlobUploadMetadata as sj,registerRemoteConfigSessionBlobUpload as NQ}from"@cline/shared";function ey($,W){let Z=$.telemetry||W.telemetryService?{...W.telemetryService??{},...$.telemetry??{}}:void 0;if(!Z)return;return u1(ay(Z)).telemetry}function tj(){let $=sy();return{async uploadMessagesFile(W){await $.uploadMessagesFile(W)}}}async function ej($){let W=await ty($),Z=ey(W,$),Q=[W.pluginDefinition],J=W.claims?.subject,j=MQ(W.bundle?.remoteConfig,J),X;return{prepared:W,extensions:Q,telemetry:Z,applyToStartSessionInput(Y){let V=Y.config.extensions??[],B=Y.config.telemetry,H=j?Y.config.sessionId?.trim()||oy():Y.config.sessionId;if(H&&j)X=H;let G=H&&j?NQ(H,W.bundle?.remoteConfig,J):void 0,K=G?{...Y.sessionMetadata??{},[RQ]:G}:Y.sessionMetadata;return{...Y,...K?{sessionMetadata:K}:{},config:{...Y.config,...H?{sessionId:H}:{},extensions:[...V,...Q],telemetry:Z??B}}},async dispose(){if(X)ny(X)}}}var iU={};w(iU,{createTeamName:()=>CQ,DefaultRuntimeBuilder:()=>c6});import{hasRuntimeConfigExtension as Fh}from"@cline/shared";import{nanoid as Ah}from"nanoid";X1();var rU={};w(rU,{createLocalTeamStore:()=>QX,SqliteTeamStore:()=>J8,FileTeamStore:()=>AW});import{appendFileSync as $h,existsSync as m6,mkdirSync as cU,readdirSync as Wh,readFileSync as uU,renameSync as Zh,writeFileSync as Qh}from"node:fs";import{join as $X}from"node:path";import{resolveTeamDataDir as Jh}from"@cline/shared/storage";function dU(){return new Date().toISOString()}function WX($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function lU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class AW{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??Jh()}init(){this.ensureTeamDir()}listTeamNames(){if(!m6(this.teamDirPath))return[];return Wh(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>m6(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let W=this.readEnvelope($);return W?.teamState?lU(W.teamState):void 0}readHistory($,W=200){let Z=this.historyPath($);if(!m6(Z))return[];return uU(Z,"utf8").split(`
588
- `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,W)}loadRuntime($){let W=this.readEnvelope($);return{state:W?.teamState?lU(W.teamState):void 0,teammates:W?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,W){this.ensureTeamSubdir($),$h(this.historyPath($),`${JSON.stringify({ts:dU(),eventType:W.type,payload:W})}
589
- `,"utf8")}persistRuntime($,W,Z){this.ensureTeamSubdir($);let Q={version:1,updatedAt:dU(),teamState:W,teammates:Z},J=this.statePath($),j=`${J}.tmp`;Qh(j,`${JSON.stringify(Q,null,2)}
590
- `,"utf8"),Zh(j,J)}markInProgressRunsInterrupted($,W){let Z=this.readEnvelope($);if(!Z?.teamState?.runs?.length)return[];let Q=Z.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Q.length===0)return[];let J=new Date;return Z.teamState={...Z.teamState,runs:Z.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:W,endedAt:J}:j)},this.persistRuntime($,Z.teamState,Z.teammates),Q}ensureTeamDir(){if(!m6(this.teamDirPath))cU(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let W=$X(this.ensureTeamDir(),WX($));if(!m6(W))cU(W,{recursive:!0});return W}statePath($){return $X(this.ensureTeamDir(),WX($),"state.json")}historyPath($){return $X(this.ensureTeamDir(),WX($),"task-history.jsonl")}readEnvelope($){let W=this.statePath($);if(!m6(W))return;try{let Z=JSON.parse(uU(W,"utf8"));if(Z?.version===1&&Z.teamState)return Z}catch{}return}}import{existsSync as jh,mkdirSync as Xh}from"node:fs";import{join as Yh}from"node:path";import{safeJsonParse as pU}from"@cline/shared";import{loadSqliteDb as Vh,nowIso as ZX}from"@cline/shared/db";import{resolveDbDataDir as Bh}from"@cline/shared/storage";function Hh(){return Bh()}function v6($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Gh($){let W=pU($);if(!Array.isArray(W))return[];let Z=[];for(let Q of W){if(!Q||typeof Q!=="object")continue;let J=Q,j=J.agentId,X=J.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof X!=="string"||!X.trim())continue;let Y={agentId:j.trim(),rolePrompt:X};if(typeof J.modelId==="string"&&J.modelId.trim())Y.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))Y.maxIterations=Math.max(1,Math.floor(J.maxIterations));Z.push(Y)}return Z}function Kh($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class J8{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??Hh()}init(){this.getRawDb()}ensureTeamDir(){if(!jh(this.teamDirPath))Xh(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Yh(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=Vh(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
585
+ ) 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,X0()])}}function Oy($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let W=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(W==="local"||W==="hub"||W==="remote")return W;return"auto"}var K9,F9;function zy($,W){if($!=="auto"&&$!=="hub")return;if(W.hub?.endpoint?.trim())return;RW(W.hub?.workspaceRoot?.trim()||W.hub?.cwd?.trim()||process.cwd())}async function qy($){await $.reconcileDeadSessions?.().catch(()=>{})}function SU($){try{let W=new C1;return W.init(),new S1(W,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(W){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),PU($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:W,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new rj(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function CU($,W,Z){return new b1({sessionService:Z??$.sessionService??SU($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:W,fetch:$.fetch})}async function oj($){if(K9)return K9;if(F9)return await F9;return F9=(async()=>{return K9=SU($),await qy(K9),K9})().finally(()=>{F9=void 0}),await F9}async function h6($){let W=x0($.distinctId);$.telemetry?.setDistinctId(W);let Z=Oy($);if(zy(Z,$),Z==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new N6({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Z==="hub"){let Q=$.hub?.endpoint?.trim(),J=Q||await H2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!J)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:J,explicitEndpoint:Q||void 0}),new Y$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Z==="auto"){let Q=await T4({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let J=new Y$({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await J.connect(),J}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),PU($.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"}),CU($,W)}return CU($,W)}var kU={};w(kU,{NoOpFeatureFlagsProvider:()=>W8,FeatureFlagsService:()=>$8});import{existsSync as My,mkdirSync as Ry,readFileSync as Ey,writeFileSync as Ny}from"node:fs";import{dirname as wy}from"node:path";import{FEATURE_FLAGS as yU,FeatureFlagDefaultValue as sj}from"@cline/shared";var Cy=3600000,Py=604800000,hU=1;class $8{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??Cy,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Py,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 W=$??this.context.userId??null,Z=Date.now();if(Z-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===W)return}let Q=this.cacheInfo;this.cacheInfo={updateTime:Z,userId:W||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:yU.length>0?yU:void 0,context:{...this.context,userId:W}});if(this.cacheInfo.userId!==W)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==W)return;throw this.cacheInfo=Q.updateTime?Q:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:J}),J}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((W)=>this.isFeatureFlagPayload(W));if(typeof $==="object")return Object.values($).every((W)=>this.isFeatureFlagPayload(W));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=Object.entries($).filter(([,Q])=>this.isFeatureFlagPayload(Q));if(W.length===0)return;let Z={};for(let[Q,J]of W)Z[Q]=J;return Z}readPersistentCache(){try{if(!this.cacheFilePath||!My(this.cacheFilePath))return;let $=JSON.parse(Ey(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let W=$;if(W.version!==hU||typeof W.updatedAt!=="number"||!Number.isFinite(W.updatedAt)||Date.now()-W.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:W.updatedAt,userId:W.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(W.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(W.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;Ry(wy(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),W={version:hU,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};Ny(this.cacheFilePath,`${JSON.stringify(W,null,2)}
586
+ `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let W=new Map;for(let Z of this.getReturnedFlagKeys($)){let Q=this.getFeatureFlag(Z);W.set(Z,Q??!1)}this.cache=W}getFeatureFlag($){try{let W=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Z=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=W??Z??sj[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:v.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Z}});return Q}catch(W){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:W}),sj[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??sj[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,W){if(process.env.IS_TEST==="true")this.cache.set($,W)}async dispose(){await this.provider.dispose()}}class W8{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}O8();var uU={};w(uU,{createCheckpointComparePlan:()=>NQ,compareCheckpointToWorkspace:()=>A9,buildCheckpointWorkspaceDiff:()=>wQ});import{execFile as yy}from"node:child_process";import*as vU from"node:fs/promises";import*as x6 from"node:path";import{promisify as hy}from"node:util";var gU={};w(gU,{trimMessagesToCheckpoint:()=>xU,trimMessagesBeforeCheckpoint:()=>ej,readSessionCheckpointHistory:()=>Z8,findCheckpointForRun:()=>I6,createRestoredCheckpointMetadata:()=>tj,createCheckpointRestorePlan:()=>$X,applyCheckpointToWorktree:()=>WX});import{execFile as Sy}from"node:child_process";import{promisify as by}from"node:util";var k6=by(Sy);function Z8($){let W=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(W?.history)?W.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let J=String(Q.ref??"").trim(),j=Number(Q.createdAt??0),X=Number(Q.runCount??0);if(J.length===0||!Number.isFinite(j)||!Number.isInteger(X)||X<1)return[];let Y=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:J,createdAt:j,runCount:X,...Y?{kind:Y}:{}}]})}function tj($,W){let Z=Z8($).filter((J)=>J.runCount<=W),Q=Z.at(-1);return Q?{latest:Q,history:Z}:void 0}function I6($,W){return $.reduce((Z,Q)=>{if(Q.runCount>W)return Z;if(!Z||Q.runCount>Z.runCount)return Q;return Z},void 0)}function IU($,W){let Z=0;for(let Q=0;Q<$.length;Q+=1){let J=$[Q];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Z+=1,Z===W)return Q}throw Error(`Could not find user message for checkpoint run ${W}`)}function xU($,W){let Z=IU($,W);return $.slice(0,Z+1)}function ej($,W){let Z=IU($,W);return $.slice(0,Z)}function $X($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=I6(Z8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Z,cwd:Q,...$.restoreMessages!==!1?{messages:xU($.messages??[],W)}:{}}}async function WX($,W){if((await k6("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await k6("git",["-C",$,"cat-file","-e",`${W.ref}^{commit}`],{windowsHide:!0}),await k6("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await k6("git",["-C",$,"clean","-fd"],{windowsHide:!0}),W.kind==="commit"){await k6("git",["-C",$,"reset","--hard",W.ref],{windowsHide:!0});return}await k6("git",["-C",$,"stash","apply",W.ref],{windowsHide:!0})}var ky=hy(yy),Iy=52428800;async function EQ($,W){let{stdout:Z}=await ky("git",["-C",$,...W],{windowsHide:!0,maxBuffer:Iy,encoding:"utf8"});return Z}function mU($){return $.split("\x00").filter(Boolean)}function cU($,W){let Z=x6.resolve($,W),Q=x6.relative($,Z);if(Q.startsWith("..")||x6.isAbsolute(Q))throw Error(`Checkpoint diff path escapes workspace: ${W}`);return Z}async function xy($,W,Z){try{return await EQ($,["show",`${W}:${Z}`])}catch{return""}}async function gy($,W){try{return await vU.readFile(cU($,W),"utf8")}catch{return""}}async function my($,W){await EQ($,["cat-file","-e",`${W.ref}^{tree}`]);let[Z,Q]=await Promise.all([EQ($,["diff","--name-only","-z",W.ref,"--"]),EQ($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...mU(Z),...mU(Q)])].sort((j,X)=>j.localeCompare(X))}function NQ($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=I6(Z8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Z,cwd:Q}}async function wQ($,W){let Z=await my($,W);return(await Promise.all(Z.map(async(J)=>{let[j,X]=await Promise.all([xy($,W.ref,J),gy($,J)]);return{filePath:cU($,J),leftContent:j,rightContent:X}}))).filter((J)=>J.leftContent!==J.rightContent)}async function A9($){let W=NQ($),Z=await wQ(W.cwd,W.checkpoint);return{...W,diffs:Z}}class U9{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,W,Z,Q,J,j,X,Y,V,B){this.clientName=W,this.runtimeAddress=Z,this.host=$,this.prepare=Q,this.capabilities=J,this.logger=j,this.telemetry=X,this.distinctId=Y,this.featureFlags=V,this.settings=RA($),this.pendingPrompts=EA($),this.automation=new eJ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=B?new W9({workspaceRoot:B.workspaceRoot??process.cwd(),specs:{cronSpecsDir:B.cronSpecsDir??B.cronDir,scope:OF(B.cronScope),workspaceRoot:B.workspaceRoot},runtimeHandlers:zF({host:$,getExtensionContext:()=>eZ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:B.dbPath,logger:B.logger,pollIntervalMs:B.pollIntervalMs,claimLeaseSeconds:B.claimLeaseSeconds,globalMaxConcurrency:B.globalMaxConcurrency,watcherDebounceMs:B.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let W=x0($.distinctId),Z=P0($.capabilities),Q={...$,capabilities:Z,distinctId:W},J=await h6(Q),j=TF($.automation),X=$.featureFlags||new $8({provider:new W8,telemetry:$.telemetry,logger:$.logger,context:{distinctId:W,clientName:$.clientName}}),Y=new U9(J,$.clientName,J.runtimeAddress,$.prepare,Z,$.logger,$.telemetry,W,X,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await Y.automation.start();return Y}async disposeSessionBootstrap($){let W=this.activeSessionBootstraps.get($);if(!W)return;this.activeSessionBootstraps.delete($),await Promise.resolve(W.dispose?.())}async start($){let W=NA($),Z=await this.prepare?.(W);try{let Q=Z?await Z.applyToStartSessionInput(W):W,J=await this.host.startSession(Dj(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>eZ({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Z)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Z);else await Promise.resolve(Z.dispose?.());return wA({input:Q,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(Q){throw await Promise.resolve(Z?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let W=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(W.map((Z)=>this.disposeSessionBootstrap(Z)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await TQ(this.host,$);list=async($=200,W={})=>await this.listHistory({...W,limit:$});delete=async($)=>{let W=await this.host.deleteSession($);if(W)await this.disposeSessionBootstrap($);return W};update=(...$)=>this.host.updateSession(...$);updateSessionCompactionState=(...$)=>this.host.updateSessionCompactionState(...$);readSessionCompactionState=(...$)=>this.host.readSessionCompactionState(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let W=$.start?Dj($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Z)=>eZ({automationService:this.automationService,automation:this.automation,context:Z,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:W})}async compareCheckpoint($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=await this.host.getSession(W);if(!Z)throw Error(`Session ${W} not found`);return A9({session:Z,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,W){return this.host.subscribe($,W)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()};updateSessionConnection=(...$)=>{return this.host.updateSessionConnection?.(...$)??Promise.resolve()}}var lU={};w(lU,{resolvePluginSkillDirectoriesFromPaths:()=>J$,resolvePluginConfigSearchPaths:()=>_5,resolveAndLoadAgentPlugins:()=>X6,resolveAgentPluginPaths:()=>Q$,loadAgentPluginsFromPathsWithDiagnostics:()=>x2,loadAgentPluginsFromPaths:()=>fZ,loadAgentPluginFromPath:()=>U5,discoverPluginModulePaths:()=>f5});var iU={};w(iU,{toHookConfigFileName:()=>O5,runSubprocessEvent:()=>g6,runHook:()=>v6,resolveHooksConfigSearchPaths:()=>L5,parseHookEventPayload:()=>m6,mergeAgentHooks:()=>c2,listHookConfigFiles:()=>I$,createSubprocessHooks:()=>SQ,createHookConfigFileHooks:()=>z5,createHookConfigFileExtension:()=>H6,createHookAuditHooks:()=>B6,createAgentHooksExtension:()=>Y6,HookEventPayloadSchema:()=>PQ,HookEventNameSchema:()=>CQ,HookConfigFileName:()=>V6,HOOK_CONFIG_FILE_EVENT_MAP:()=>T5,HOOKS_CONFIG_DIRECTORY_NAME:()=>MZ});import{HookEventNameSchema as CQ,HookEventPayloadSchema as PQ,parseHookEventPayload as m6,resolveHookSessionContext as ry}from"@cline/shared";import{z as Q8}from"zod";import{spawn as vy}from"node:child_process";import{augmentNodeCommandForDebug as cy,withResolvedClineBuildEnv as uy}from"@cline/shared";function dy($){let W=$.trim();if(!W)return{};let Q=W.split(`
587
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function ly($,W){let Z=$ instanceof Error?$:Error(String($)),Q=Z,J=W.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${J}" (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 "${J}": ${Z.message}`)}async function py($,W){let Z=$.stdin;if(!Z)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,J)=>{let j=(X)=>{Z.off("error",j);let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X)};Z.once("error",j),Z.end(W,(X)=>{if(Z.off("error",j),X){let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X);return}Q()})})}async function g6($,W){let Z=cy(W.command,{env:W.env,debugRole:"hook"});if(!Array.isArray(Z)||Z.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!W.detached,J=vy(Z[0],Z.slice(1),{cwd:W.cwd,env:uy(W.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),j=new Promise((K)=>{J.once("spawn",()=>{try{W.onSpawn?.({command:Z,pid:J.pid??void 0,detached:Q})}catch{}K()})}),X=new Promise((K,F)=>{J.once("error",(A)=>{F(ly(A,Z))})});if(await py(J,JSON.stringify($)),Q){await Promise.race([j,X]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let Y="",V="",B=!1,H;J.stdout.on("data",(K)=>{Y+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,J.kill("SIGKILL")},W.timeoutMs);J.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=dy(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,X])}var iy=Q8.object({contextModification:Q8.string().optional(),cancel:Q8.boolean().optional(),review:Q8.boolean().optional(),errorMessage:Q8.string().optional(),context:Q8.string().optional(),overrideInput:Q8.unknown().optional()}).passthrough();var ny=["agent","hook"];async function v6($,W={}){let Z=W.command??ny;return await g6($,{command:Z,cwd:W.cwd,env:W.env,detached:W.detached,timeoutMs:W.timeoutMs,onSpawn:W.onSpawn})}function rU($){return $ instanceof Error?$:Error(String($))}function ay($){if(!$||typeof $!=="object")return;let W=iy.safeParse($);if(!W.success)return;let Z=W.data;if(!(("cancel"in Z)||("review"in Z)||("context"in Z)||("contextModification"in Z)||("overrideInput"in Z)||("errorMessage"in Z)))return;let J=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"&&Z.errorMessage.length>0?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:J,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function pU($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q;else W[Z]=JSON.stringify(Q);return W}function H$($,W,Z){let Q=Z.env??process.env,J=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",j=Z.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:W.conversationId,sessionContext:ry(Z.sessionContext,{hookName:$,conversationId:W.conversationId,agentId:W.agentId,parentAgentId:W.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Z.workspaceInfo,userId:J,agent_id:W.agentId,parent_agent_id:W.parentAgentId}}function oy($){return{name:$.name,message:$.message,stack:$.stack}}function sy($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function ty($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function ey($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function $h($){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 Wh($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}async function J8($,W){try{let Z=await v6($,{command:W.command,cwd:W.cwd,env:W.env,detached:!0,onSpawn:W.onSpawn});W.onDispatch?.({payload:$,result:Z,detached:!0})}catch(Z){W.onDispatchError?.(rU(Z),$)}}function SQ($={}){return{hooks:{beforeRun:async(Y)=>{let V=ty(Y);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...H$("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await J8(H,$)}else{let H={...H$("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await J8(H,$)}return},beforeTool:async(Y)=>{let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("tool_call",V,$),hookName:"tool_call",iteration:Y.snapshot.iteration,tool_call:{id:Y.toolCall.toolCallId,name:Y.toolCall.toolName,input:Y.input},preToolUse:{toolName:Y.toolCall.toolName,parameters:pU(Y.input)}};try{let H=await v6(B,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:B,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 Wh(ay(H?.parsedJson))}catch(H){$.onDispatchError?.(rU(H),B);return}},afterTool:async(Y)=>{let V=$h(Y),B={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},H={...H$("tool_result",B,$),hookName:"tool_result",iteration:Y.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:pU(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await J8(H,$);return},afterRun:async({snapshot:Y,result:V})=>{let B={agentId:Y.agentId,conversationId:Y.conversationId??Y.runId??Y.agentId,parentAgentId:Y.parentAgentId??null};if(V.status==="completed"){let K={...H$("agent_end",B,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await J8(K,$);return}let H=V.status==="aborted"||sy(V.error?.message)?"agent_abort":"agent_error",G=H==="agent_error"?{...H$(H,B,$),hookName:H,iteration:V.iterations,error:oy(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...H$(H,B,$),hookName:H,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await J8(G,$)},onEvent:async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:ey(Y.message.content),attachments:[]}};await J8(B,$)}},shutdown:async({agentId:Y,conversationId:V,parentAgentId:B,reason:H})=>{let G={...H$("session_shutdown",{agentId:Y,conversationId:V,parentAgentId:B},$),hookName:"session_shutdown",reason:H};await J8(G,$)}}}bQ();var aU={};w(aU,{registerRemoteConfigSessionBlobUpload:()=>kQ,readRemoteConfigSessionBlobUploadMetadata:()=>ZX,prepareRemoteConfigCoreIntegration:()=>JX,createRemoteConfigSessionMessagesArtifactUploader:()=>QX,buildRemoteConfigSessionBlobUploadMetadata:()=>yQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>hQ});import{buildRemoteConfigSessionBlobUploadMetadata as yQ,clearRemoteConfigSessionBlobUpload as Zh,createClineTelemetryServiceConfig as Qh,createSessionId as Jh,createRemoteConfigSessionMessagesArtifactUploader as jh,prepareRemoteConfigRuntime as Xh,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as hQ,readRemoteConfigSessionBlobUploadMetadata as ZX,registerRemoteConfigSessionBlobUpload as kQ}from"@cline/shared";function Yh($,W){let Z=$.telemetry||W.telemetryService?{...W.telemetryService??{},...$.telemetry??{}}:void 0;if(!Z)return;return d1(Qh(Z)).telemetry}function QX(){let $=jh();return{async uploadMessagesFile(W){await $.uploadMessagesFile(W)}}}async function JX($){let W=await Xh($),Z=Yh(W,$),Q=[W.pluginDefinition],J=W.claims?.subject,j=yQ(W.bundle?.remoteConfig,J),X;return{prepared:W,extensions:Q,telemetry:Z,applyToStartSessionInput(Y){let V=Y.config.extensions??[],B=Y.config.telemetry,H=j?Y.config.sessionId?.trim()||Jh():Y.config.sessionId;if(H&&j)X=H;let G=H&&j?kQ(H,W.bundle?.remoteConfig,J):void 0,K=G?{...Y.sessionMetadata??{},[hQ]:G}:Y.sessionMetadata;return{...Y,...K?{sessionMetadata:K}:{},config:{...Y.config,...H?{sessionId:H}:{},extensions:[...V,...Q],telemetry:Z??B}}},async dispose(){if(X)Zh(X)}}}var ZD={};w(ZD,{createTeamName:()=>gQ,DefaultRuntimeBuilder:()=>d6});import{hasRuntimeConfigExtension as Oh}from"@cline/shared";import{nanoid as zh}from"nanoid";X1();var WD={};w(WD,{createLocalTeamStore:()=>VX,SqliteTeamStore:()=>j8,FileTeamStore:()=>D9});import{appendFileSync as Vh,existsSync as c6,mkdirSync as oU,readdirSync as Bh,readFileSync as sU,renameSync as Hh,writeFileSync as Gh}from"node:fs";import{join as jX}from"node:path";import{resolveTeamDataDir as Kh}from"@cline/shared/storage";function tU(){return new Date().toISOString()}function XX($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function eU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class D9{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??Kh()}init(){this.ensureTeamDir()}listTeamNames(){if(!c6(this.teamDirPath))return[];return Bh(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>c6(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let W=this.readEnvelope($);return W?.teamState?eU(W.teamState):void 0}readHistory($,W=200){let Z=this.historyPath($);if(!c6(Z))return[];return sU(Z,"utf8").split(`
588
+ `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,W)}loadRuntime($){let W=this.readEnvelope($);return{state:W?.teamState?eU(W.teamState):void 0,teammates:W?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,W){this.ensureTeamSubdir($),Vh(this.historyPath($),`${JSON.stringify({ts:tU(),eventType:W.type,payload:W})}
589
+ `,"utf8")}persistRuntime($,W,Z){this.ensureTeamSubdir($);let Q={version:1,updatedAt:tU(),teamState:W,teammates:Z},J=this.statePath($),j=`${J}.tmp`;Gh(j,`${JSON.stringify(Q,null,2)}
590
+ `,"utf8"),Hh(j,J)}markInProgressRunsInterrupted($,W){let Z=this.readEnvelope($);if(!Z?.teamState?.runs?.length)return[];let Q=Z.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Q.length===0)return[];let J=new Date;return Z.teamState={...Z.teamState,runs:Z.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:W,endedAt:J}:j)},this.persistRuntime($,Z.teamState,Z.teammates),Q}ensureTeamDir(){if(!c6(this.teamDirPath))oU(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let W=jX(this.ensureTeamDir(),XX($));if(!c6(W))oU(W,{recursive:!0});return W}statePath($){return jX(this.ensureTeamDir(),XX($),"state.json")}historyPath($){return jX(this.ensureTeamDir(),XX($),"task-history.jsonl")}readEnvelope($){let W=this.statePath($);if(!c6(W))return;try{let Z=JSON.parse(sU(W,"utf8"));if(Z?.version===1&&Z.teamState)return Z}catch{}return}}import{existsSync as Fh,mkdirSync as Ah}from"node:fs";import{join as Uh}from"node:path";import{safeJsonParse as $D}from"@cline/shared";import{loadSqliteDb as Dh,nowIso as YX}from"@cline/shared/db";import{resolveDbDataDir as _h}from"@cline/shared/storage";function fh(){return _h()}function u6($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Lh($){let W=$D($);if(!Array.isArray(W))return[];let Z=[];for(let Q of W){if(!Q||typeof Q!=="object")continue;let J=Q,j=J.agentId,X=J.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof X!=="string"||!X.trim())continue;let Y={agentId:j.trim(),rolePrompt:X};if(typeof J.modelId==="string"&&J.modelId.trim())Y.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))Y.maxIterations=Math.max(1,Math.floor(J.maxIterations));Z.push(Y)}return Z}function Th($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class j8{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??fh()}init(){this.getRawDb()}ensureTeamDir(){if(!Fh(this.teamDirPath))Ah(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Uh(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=Dh(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
591
591
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
592
592
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
593
593
  version INTEGER NOT NULL
@@ -671,8 +671,8 @@ ${J}`,$.config.mode)}function BW($,W){return Qy($,W==="plan"?"plan":W==="yolo"?"
671
671
  version INTEGER NOT NULL DEFAULT 1,
672
672
  PRIMARY KEY(team_name, fragment_id)
673
673
  );
674
- `)}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}withTransaction($){let W=this.getRawDb();W.exec("BEGIN IMMEDIATE;");try{$(),W.exec("COMMIT;")}catch(Z){try{W.exec("ROLLBACK;")}catch{}throw Z}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[v6($)]);if(!W)return;let Z=pU(W.state_json);if(!Z)return;try{return Kh(Z)}catch{return}}readHistory($,W=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[v6($),W]).flatMap((Z)=>{try{return[{eventType:Z.event_type,payload:JSON.parse(Z.payload_json),ts:Z.ts}]}catch{return[]}})}loadRuntime($){let W=v6($),Z=this.readState(W),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[W]),J=Q?Gh(Q.teammates_json):[];return{state:Z,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,W,Z,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
675
- VALUES (?, ?, ?, ?, NULL, ?)`,[v6($),ZX(),W,JSON.stringify(Z),Q??null])}persistRuntime($,W,Z){let Q=v6($),J=ZX();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
674
+ `)}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}withTransaction($){let W=this.getRawDb();W.exec("BEGIN IMMEDIATE;");try{$(),W.exec("COMMIT;")}catch(Z){try{W.exec("ROLLBACK;")}catch{}throw Z}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[u6($)]);if(!W)return;let Z=$D(W.state_json);if(!Z)return;try{return Th(Z)}catch{return}}readHistory($,W=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[u6($),W]).flatMap((Z)=>{try{return[{eventType:Z.event_type,payload:JSON.parse(Z.payload_json),ts:Z.ts}]}catch{return[]}})}loadRuntime($){let W=u6($),Z=this.readState(W),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[W]),J=Q?Lh(Q.teammates_json):[];return{state:Z,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,W,Z,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
675
+ VALUES (?, ?, ?, ?, NULL, ?)`,[u6($),YX(),W,JSON.stringify(Z),Q??null])}persistRuntime($,W,Z){let Q=u6($),J=YX();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
676
676
  VALUES (?, ?, ?, ?)
677
677
  ON CONFLICT(team_name) DO UPDATE SET
678
678
  state_json = excluded.state_json,
@@ -717,44 +717,44 @@ ${J}`,$.config.mode)}function BW($,W){return Qy($,W==="plan"?"plan":W==="yolo"?"
717
717
  status = excluded.status,
718
718
  reviewed_by = excluded.reviewed_by,
719
719
  reviewed_at = excluded.reviewed_at,
720
- version = team_outcome_fragments.version + 1`,[Q,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($,W){let Z=v6($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Z]);if(Q.length===0)return[];let J=ZX();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
721
- WHERE team_name = ? AND status IN ('queued', 'running')`,[W,J,Z]),Q.map((j)=>j.run_id)}handleTeamEvent($,W){this.appendTeamEvent($,W.type,W)}}function QX($={}){try{let W=new J8($);return W.init(),W}catch{let W=new AW({teamDir:$.teamDir});return W.init(),W}}function EQ($,W){return Fh($,W)}function Uh($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function fh($,W){return $.filter((Z)=>Uh(Z.name,W))}function JX($,W){return c1(fh($,W))}var Dh={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 _h($){let W=$.trim().toLowerCase();return Dh[W]??W}function Lh($,W){if(W.tools===void 0)return $;let Z=new Set(W.tools.map(_h));if(W.skills!==void 0)Z.add("skills");return $.filter((Q)=>Z.has(Q.name))}function CQ(){return`team-${Ah(5)}`}function wQ($,W,Z,Q,J,j,X,Y){let V=a0[t1({mode:Z})],B=l8(W,Q,Z,J??d8);return JX(b2({cwd:$,...V,enableSkills:!!X,...B,executors:{...X?{skills:X}:{},...Y??{}}}),j)}function Th($){return wQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,Oh,$.toolExecutors).some((W)=>W.name==="skills")}var Oh=async()=>"";async function zh($){let W=J0();if(!j$({filePath:W}))return{tools:[]};let Z=new n2({clientFactory:T6({settingsPath:W})}),Q;try{Q=await i2(Z,{filePath:W})}catch(Y){await Z.dispose().catch(()=>{});let V=Y instanceof Error?Y.message:String(Y);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=Q.filter((Y)=>Y.disabled!==!0),j=await Promise.allSettled(J.map((Y)=>z6({serverName:Y.name,provider:Z}))),X=[];for(let[Y,V]of j.entries())if(V.status==="fulfilled")X.push(...V.value);else{let B=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[Y].name}", skipping: ${B}`)}return{tools:X,shutdown:async()=>{await Z.dispose()}}}function qh($,W){if(!$)return;for(let Z of $.getTeammateIds())try{$.shutdownTeammate(Z,W)}catch{}}function Mh($){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 Rh($){let W=a0[t1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??W.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??W.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 c6{teamRuntimeEntries=new Map;async build($){let{config:W,hooks:Z,extensions:Q,logger:J,telemetry:j,createSpawnTool:X,onTeamRestored:Y,userInstructionService:V,configExtensions:B,toolExecutors:H}=$,G=$.onTeamEvent??(()=>{}),K=Rh(W),F=W.workspaceRoot??W.cwd,A=$.toolPolicies??W.toolPolicies,f=L1(),U=[],_=W.teamName?.trim()||CQ(),D=W.sessionId?.trim()||_,M=K.enableSpawnAgent?N6({workspaceRoot:F}):{configs:[],errors:[]},O=M.configs.some((l)=>l.skills!==void 0),T=EQ(B,"rules"),L=EQ(B,"skills"),C=L||O,N=EQ(B,"workflows"),p=EQ(B,"plugins"),x=T||L||N,P=!1,r=Boolean(V),d=V,k1;for(let l of M.errors)(J??W.logger)?.log?.(`[agents] Failed to load agent config at ${l.path}: ${l.error.message}`);if(!d&&(x||O))d=v$({skills:C?{workspacePath:F,includePluginSkills:p,pluginSkillDirectories:p?$.pluginSkillDirectories:void 0,pluginPaths:W.pluginPaths,cwd:W.cwd}:{workspacePath:F},rules:{workspacePath:W.cwd},workflows:{workspacePath:W.cwd}});if(d)await d.start().catch(()=>{});let e$=K.enableTools&&L&&Boolean(d)&&d?.hasConfiguredSkills(W.skills)===!0&&Th({cwd:W.cwd,providerId:W.providerId,mode:K.mode,modelId:W.modelId,toolRoutingRules:W.toolRoutingRules,toolPolicies:A,toolExecutors:H}),F$=d&&x?d.createExtension({includeRules:T,includeSkills:L,includeWorkflows:N,registerSkillsTool:e$,allowedSkillNames:W.skills}):void 0,k0=F$?[...Q??W.extensions??[],F$]:Q??W.extensions;if(K.enableTools){if(U.push(...wQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H)),!K.disableMcpSettingsTools){let l=await zh(W.logger);U.push(...l.tools),k1=l.shutdown}}let A0,f1=K.enableAgentTeams?QX():void 0,H8=f1?.loadRuntime(D),V0=H8?.state,d0=H8?.teammates??[],J1=new Map(d0.map((l)=>[l.agentId,l])),y=W.sessionId||_,j1,k=[],$0=!1,L0=P$({providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey??"",baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,maxIterations:W.maxIterations,hooks:Z,extensions:k0,logger:J??W.logger,telemetry:$.telemetry??W.telemetry,workspaceMetadata:W.workspaceMetadata});if(K.enableSpawnAgent){if(M.configs.length>0)U.push(...JX(E6({configProvider:L0,agents:M.configs,createSubAgentTools:(l)=>K.enableTools?Lh(wQ(W.cwd,l.providerId??W.providerId,K.mode,l.modelId??W.modelId,W.toolRoutingRules,A,l.skills!==void 0&&d?.createSkillsExecutor?d.createSkillsExecutor(l.skills):void 0,H),l):[],hookErrorMode:W.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(y))this.teamRuntimeEntries.set(y,{delegatedAgentConfigProvider:L0});let z0=()=>{if(!K.enableAgentTeams)return;let l=this.teamRuntimeEntries.get(y)??{delegatedAgentConfigProvider:L0};if(this.teamRuntimeEntries.set(y,l),A0=l.runtime,!A0){if(A0=new t2({teamName:_,leadAgentId:W.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(B0)=>{if(G(B0),A0&&f1){if(B0.type==="teammate_spawned"&&B0.teammate?.rolePrompt){let I1={agentId:B0.agentId,rolePrompt:B0.teammate.rolePrompt,modelId:B0.teammate.modelId,maxIterations:B0.teammate.maxIterations};J1.set(I1.agentId,I1)}if(B0.type==="teammate_shutdown"&&!Mh(B0.reason))J1.delete(B0.agentId);f1.handleTeamEvent(D,B0),f1.persistRuntime(D,A0.exportState(),Array.from(J1.values()))}}}),V0)A0.hydrateState(V0),$0=!0;l.runtime=A0}if(!P){if(!A0)return;P=!0;let B0=n8({runtime:A0,leadAgentId:W.sessionId||"lead",restoredFromPersistence:Boolean(V0),restoredTeammates:d0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(I1)=>{k=I1,j1?.addTools(I1)},createBaseTools:K.enableTools?()=>wQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H):void 0,teammateConfigProvider:L0});if($0)A0.recoverActiveRuns("runtime_recovered");if(B0.restoredFromPersistence)Y?.();U.push(...B0.tools)}return A0};if(K.enableSpawnAgent&&X){let l=X();U.push({...l,execute:async(B0,I1)=>{return z0(),l.execute(B0,I1)}})}if(K.enableAgentTeams)z0();let kW=JX(U,A),o6=kW.some((l)=>l.name==="submit_and_exit"&&l.lifecycle?.completesRun===!0),G8=K.enableAgentTeams?()=>{let l=this.teamRuntimeEntries.get(y)?.runtime;if(!l)return;let B0=l.listTasks(),I1=B0.some((A$)=>A$.status==="in_progress"||A$.status==="pending"),IY=l.listRuns({}),w_=IY.some((A$)=>A$.status==="running"||A$.status==="queued");if(I1||w_){let A$=B0.filter((l0)=>l0.status==="in_progress"||l0.status==="pending").map((l0)=>`${l0.id} (${l0.status}): ${l0.title}`).join(", "),xY=IY.filter((l0)=>l0.status==="running"||l0.status==="queued").map((l0)=>`${l0.id} (${l0.status})`).join(", "),z7=[];if(A$)z7.push(`Unfinished tasks: ${A$}`);if(xY)z7.push(`Active runs: ${xY}`);return`[SYSTEM] You still have team obligations. ${z7.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,E_=o6?{requireCompletionTool:!0,...G8?{completionGuard:G8}:{}}:G8?{completionGuard:G8}:void 0;return{tools:kW,logger:J??W.logger,telemetry:j??W.telemetry,teamRuntime:A0,teamRestoredFromPersistence:Boolean(V0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(y)?.delegatedAgentConfigProvider??L0,extensions:k0,completionPolicy:E_,registerLeadAgent:(l)=>{if(j1=l,k.length>0)l.addTools(c1(k,[...f]))},shutdown:async(l)=>{if(qh(A0,l),this.teamRuntimeEntries.delete(y),await k1?.(),!r)d?.stop()}}}}var aU={};w(aU,{requestDesktopToolApproval:()=>XX});import{mkdir as Nh,readFile as Eh,unlink as wh,writeFile as Ch}from"node:fs/promises";import{join as nU}from"node:path";function Ph($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function Sh($){return new Promise((W)=>setTimeout(W,$))}async function jX($){try{await wh($)}catch{}}async function XX($,W={}){let Z=W.approvalDir?.trim(),Q=W.sessionId?.trim();if(!Z||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await Nh(Z,{recursive:!0});let J=Ph(`${$.toolCallId}`),j=nU(Z,`${Q}.request.${J}.json`),X=nU(Z,`${Q}.decision.${J}.json`),Y=W.nowIso??(()=>new Date().toISOString());await Ch(j,`${JSON.stringify({requestId:J,sessionId:Q,createdAt:Y(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
722
- `,"utf8");let V=W.timeoutMs??300000,B=W.pollIntervalMs??200,H=Date.now();while(Date.now()-H<V){try{let G=await Eh(X,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([jX(X),jX(j)]),F}catch{}await Sh(B)}return await jX(j),{approved:!1,reason:"Tool approval request timed out"}}X1();var Bf={};w(Bf,{uninstallMarketplaceSkill:()=>xQ,uninstallMarketplacePlugin:()=>gQ,uninstallMarketplaceMcpServerFromSettings:()=>kQ,uninstallMarketplaceEntry:()=>zX,resolveMarketplaceMcpServerName:()=>TW,marketplaceEntryKey:()=>OX,isMarketplaceSkillInstalled:()=>IQ,getMarketplaceSkillCandidates:()=>OW,getGlobalMarketplaceSkillPaths:()=>zW,findInstalledGlobalMarketplaceSkillName:()=>qW});import{spawn as Ak}from"node:child_process";import{existsSync as Yf,rmSync as Uk}from"node:fs";import{homedir as fk,platform as Dk}from"node:os";import{dirname as _k,join as Xf}from"node:path";import{resolveClineDir as Lk,resolveMcpSettingsPath as Tk}from"@cline/shared/storage";var sU={};w(sU,{parseMcpInstallArgs:()=>UW,installMcpServer:()=>YX,buildMcpInstallTransport:()=>PQ});function bh($){let W=($??"stdio").trim();if(W==="http"||W==="streamable-http")return"streamableHttp";if(W==="stdio"||W==="sse"||W==="streamableHttp")return W;throw Error(`Unsupported MCP transport "${W}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function yh($){let W;try{W=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function hh($){let W=$.indexOf(":");if(W<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Z=$.slice(0,W).trim(),Q=$.slice(W+1).trim();if(!Z||!Q)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Z))throw Error(`Invalid MCP header name "${Z}".`);return[Z,Q]}function kh($){let W=$.indexOf("<");return W>=0&&$.indexOf(">",W+1)>W+1}function oU($){let W=[...$.headers??[]],Z=[],Q=$.transport,J=$.targetArgs??[];for(let j=0;j<J.length;j++){let X=J[j];if($.parseTransport&&X==="--transport"){let Y=J[j+1];if(!Y)throw Error("--transport requires a value");Q=Y,j++;continue}if($.parseTransport&&X?.startsWith("--transport=")){Q=X.slice(12);continue}if(X==="--header"){let Y=J[j+1];if(!Y)throw Error("--header requires a value");W.push(Y),j++;continue}if(X?.startsWith("--header=")){W.push(X.slice(9));continue}Z.push(X)}return{headers:W,targetArgs:Z,transport:Q}}function Ih($){if($.length===0)return{warnings:[]};let W={},Z=[];for(let Q of $){let[J,j]=hh(Q);if(W[J]=j,kh(j))Z.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:W,warnings:Z}}function PQ($){let W=$.name.trim();if(!W)throw Error("MCP server name is required");let{headers:Z,targetArgs:Q,transport:J}=oU({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),j=bh(J),{headers:X,warnings:Y}=Ih(Z);if(j==="stdio"){if(Z.length>0)throw Error("Stdio MCP installs do not support request headers.");let[B,...H]=Q;if(!B?.trim())throw Error("Stdio MCP install requires a command after the server name, for example: cline mcp install fs --yes -- npx -y @modelcontextprotocol/server-filesystem /tmp");return{name:W,transport:{type:j,command:B,args:H.length>0?H:void 0},warnings:Y}}if(Q.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=Q[0]?.trim()??"";return yh(V),{name:W,transport:X?{type:j,url:V,headers:X}:{type:j,url:V},warnings:Y}}function UW($){let[W,...Z]=$;if(!W)throw Error("Marketplace MCP install args must start with a server name.");return{name:W,...oU({parseTransport:!0,targetArgs:Z})}}function xh($,W,Z){A1(Z,(Q)=>{let J=Q.mcpServers,j=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};j[$]={transport:W},Q.mcpServers=j})}function YX($){let{name:W,transport:Z,warnings:Q}=PQ($);return xh(W,Z,$.settingsPath??J0()),{name:W,status:"installed",transport:Z,warnings:Q}}X1();var jf={};w(jf,{uninstallPlugin:()=>_W});import{existsSync as d6,readdirSync as rh,readFileSync as ih,rmdirSync as nh,rmSync as ah,statSync as oh}from"node:fs";import{basename as Z1,dirname as i$,extname as sh,isAbsolute as th,join as H$,relative as eh,resolve as u6,sep as KX}from"node:path";import{discoverPluginModulePaths as $k,resolvePluginConfigSearchPaths as Wk}from"@cline/shared/storage";var Wf={};w(Wf,{syncPluginMcpServersToSettings:()=>fW,removePluginMcpServersFromSettings:()=>DW,disablePluginMcpServersInSettings:()=>GX});import{existsSync as gh,mkdirSync as mh,readFileSync as vh,writeFileSync as ch}from"node:fs";import{dirname as eU,isAbsolute as uh,relative as dh,resolve as tU}from"node:path";function j8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function SQ($,W){let Z=dh(tU($),tU(W));return Z===""||!Z.startsWith("..")&&!uh(Z)}function VX($){if(!gh($))return{mcpServers:{}};try{let W=JSON.parse(vh($,"utf8"));if(j8(W))return W}catch(W){throw Error(`Invalid MCP settings at "${$}": ${W instanceof Error?W.message:String(W)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function BX($){if(j8($.mcpServers))return{...$.mcpServers};return{}}function HX($,W,Z){mh(eU($),{recursive:!0}),ch($,`${JSON.stringify({...W,mcpServers:Z},null,2)}
723
- `,"utf8")}function $f($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((W)=>W.trim()).filter((W)=>W.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((W)=>W.trim()).filter((W)=>W.length>0))]}}function yQ($){if(!j8($))return;let W=$.metadata;return j8(W)?W:void 0}function bQ($,W){let Z=yQ($);if(!Z||Z.source!=="plugin")return!1;let Q=typeof Z.pluginName==="string"?Z.pluginName:typeof Z.plugin==="string"?Z.plugin:void 0,J=typeof Z.pluginPath==="string"?Z.pluginPath:void 0;if(W.pluginName&&Q===W.pluginName){if(!W.pluginPath||J===W.pluginPath)return!0}if(J&&W.pluginPath&&(J===W.pluginPath||SQ(W.pluginPath,J)||SQ(J,W.pluginPath)))return!0;if(Q&&W.pluginNames?.some((j)=>j===Q))return!0;if(J&&W.pluginPaths?.some((j)=>J===j||SQ(j,J)||SQ(J,j)))return!0;return!1}function lh($){let W=j8($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:eU($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...W,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function ph($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let W=await Q6({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Z=[],Q=[],J=(W.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of W.extensions??[]){let X=j.__clinePluginPath;if(!X)continue;if(!j.setup){Z.push({pluginName:j.name,pluginPath:X});continue}let Y=[],V={registerTool:(B)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(B)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');Y.push(B)}};try{await j.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(B){J.push({pluginPath:X,pluginName:j.name,message:B instanceof Error?B.message:String(B)});continue}Z.push({pluginName:j.name,pluginPath:X});for(let B of Y)Q.push({pluginName:j.name,pluginPath:X,server:{...B,metadata:{...B.metadata??{},source:"plugin",pluginName:j.name,pluginPath:X}}})}return{plugins:Z,servers:Q,failures:J}}finally{await W.shutdown().catch(()=>{})}}async function fW($){let W=$.settingsPath??J0(),Z={mutations:[],failures:[]},Q;try{Q=await ph($)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}Z.failures.push(...Q.failures);let J;try{J=VX(W)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}let j=BX(J),X=new Map,Y=new Map;for(let B of Q.plugins)X.set(B.pluginPath,new Set),Y.set(B.pluginPath,B.pluginName);let V=JQ(Q.servers.map((B)=>({server:B.server,owner:B,ownerLabel:B.pluginName})));for(let B of V){let H=B.owner;if(!X.has(H.pluginPath))X.set(H.pluginPath,new Set);if(B.name)X.get(H.pluginPath)?.add(B.name);if(!B.registration){Z.mutations.push({name:B.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:B.loadError??"invalid MCP server registration"});continue}let G=j[B.registration.name];if(G!==void 0){if(!bQ(G,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[B.registration.name]=lh({registration:B.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:j8(G)?G:void 0}),Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:G===void 0?"created":"updated"})}for(let[B,H]of Object.entries(j)){let G=yQ(H),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=X.get(K);if(F&&bQ(H,{pluginPath:K})&&!F.has(B))delete j[B],Z.mutations.push({name:B,pluginName:typeof G?.pluginName==="string"?G.pluginName:Y.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Z.mutations.some((B)=>B.action!=="skipped"))try{HX(W,J,j)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)})}return Z}function GX($){let W=$.settingsPath??J0(),Z;try{Z=VX(W)}catch{return[]}let Q=BX(Z),J=$f($),j=[];for(let[X,Y]of Object.entries(Q)){if(!j8(Y)||!bQ(Y,J))continue;let V=yQ(Y);Q[X]={...Y,disabled:!0},j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(j.length>0)HX(W,Z,Q);return j}function DW($){let W=$.settingsPath??J0(),Z;try{Z=VX(W)}catch{return[]}let Q=BX(Z),J=$f($),j=[];for(let[X,Y]of Object.entries(Q)){if(!bQ(Y,J))continue;let V=yQ(Y);delete Q[X],j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(j.length>0)HX(W,Z,Q);return j}var DX="_installed",Zk="package",Qk=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function FX($){return $.trim().toLowerCase()}function U1($,W){let Z=W?.trim();if(!Z)return;$.add(Z)}function Jk($){return $.replace(/-[0-9a-f]{12}$/i,"")}function AX($){let W=sh($);return W?$.slice(0,-W.length):$}function UX($){if(!d6($))return;try{let W=JSON.parse(ih($,"utf8"));return typeof W.name==="string"?W.name.trim():void 0}catch{return}}function _X($,W){let Z=eh(W,$);return Z===""||!Z.startsWith("..")&&!th(Z)}function Zf($){let Z=u6($).split(KX),Q=Z.lastIndexOf(DX);if(Q<0)return;let J=Z[Q+1];if(!J)return;let j=Qk.get(J)??1,X=Q+2+j;if(Z.length<X)return;let Y=Z.slice(0,X).join(KX)||KX;return d6(Y)?Y:void 0}function hQ($){try{return rh($,{withFileTypes:!0})}catch{return[]}}function jk($){let W=H$($,DX);if(!d6(W))return[];let Z=[];for(let Q of hQ(W)){if(!Q.isDirectory())continue;let J=H$(W,Q.name);if(Q.name==="git"){for(let j of hQ(J)){if(!j.isDirectory())continue;let X=H$(J,j.name);for(let Y of hQ(X))if(Y.isDirectory())Z.push(H$(X,Y.name))}continue}for(let j of hQ(J))if(j.isDirectory())Z.push(H$(J,j.name))}return Z.sort((Q,J)=>Q.localeCompare(J))}function Qf($){try{return $k($)}catch{return[]}}function fX($){let W=Qf($),Z=new Set;U1(Z,Z1($)),U1(Z,Jk(Z1($))),U1(Z,UX(H$($,"package.json"))),U1(Z,UX(H$($,Zk,"package.json")));for(let Q of W)U1(Z,Z1(Q)),U1(Z,AX(Z1(Q)));return{installPath:$,entryPaths:W,names:[...Z].sort((Q,J)=>Q.localeCompare(J)),installed:!0}}function Xk($,W){let Z=u6($),Q=W.find((X)=>_X(Z,X));if(!Q)return;let J=i$(Z);while(J!==Q&&J!==i$(J)){if(d6(H$(J,"package.json")))return J;J=i$(J)}let j=Z1(Z);if((j==="index.ts"||j==="index.js")&&i$(Z)!==Q)return i$(Z);return Z}function Jf($,W){let Z=Xk($,W);if(!Z)return;let Q=new Set;return U1(Q,Z1($)),U1(Q,AX(Z1($))),U1(Q,Z1(Z)),U1(Q,AX(Z1(Z))),U1(Q,UX(H$(Z,"package.json"))),{installPath:Z,entryPaths:[$],names:[...Q].sort((J,j)=>J.localeCompare(j)),installed:!1}}function Yk($){let W=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Wk(W).filter((Z)=>d6(Z))}function Vk($){let W=new Map;for(let Z of $){for(let Q of jk(Z))W.set(Q,fX(Q));for(let Q of Qf(Z)){let J=Zf(Q);if(J){if(!W.has(J))W.set(J,fX(J));continue}let j=Jf(Q,$);if(j)W.set(j.installPath,j)}}return[...W.values()].sort((Z,Q)=>Z.installPath.localeCompare(Q.installPath))}function Bk($,W){let Z=FX(W);if(!Z)return!1;if(FX($.installPath)===Z)return!0;return $.names.some((Q)=>FX(Q)===Z)}function Hk($,W,Z){let Q=u6($);for(let j of W){if(_X(Q,j.installPath))return j;if(j.entryPaths.some((X)=>u6(X)===Q))return j}let J=Zf(Q);if(J)return fX(J);if(d6(Q))return Jf(Q,Z);return}function Gk($){let W=R0(),Z=W.disabledPlugins;if(!Z?.length)return;let Q=Z.filter((J)=>{let j=u6(J);if(_X(j,$.installPath))return!1;return!$.entryPaths.some((X)=>u6(X)===j)});if(Q.length===Z.length)return;_1({...W,disabledPlugins:Q})}function Kk($){let W=i$($);while(W!==i$(W)&&Z1(W)!==DX){try{nh(W)}catch{return}W=i$(W)}}function Fk($){return`${$.names[0]??Z1($.installPath)} at ${$.installPath}`}async function _W($){let W=Yk($),Z=Vk(W),Q=$.path?.trim(),J=$.name?.trim(),j;if(Q){if(j=Hk(Q,Z,W),!j)throw Error(`No plugin found at ${Q}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let Y=Z.filter((V)=>Bk(V,J));if(Y.length===0)throw Error(`No plugin found matching "${J}"`);if(Y.length>1)throw Error(`Multiple plugins match "${J}": ${Y.map(Fk).join(", ")}`);j=Y[0]}let X=oh(j.installPath,{throwIfNoEntry:!1});if(!X)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(DW({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),ah(j.installPath,{recursive:X.isDirectory(),force:!0}),Gk(j),j.installed)Kk(j.installPath);return{name:J||j.names[0]||Z1(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var LX=120000,LW=12000,Ok=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,zk=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,qk=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,Mk=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function TX($){return $.install?.args??[]}function Rk(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||fk()}function Nk($){let W=0,Z=$.length;while(W<Z&&($[W]==="."||$[W]==="-"))W++;while(Z>W&&($[Z-1]==="."||$[Z-1]==="-"))Z--;return $.slice(W,Z)}function Ek($){return Nk($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function Vf($){return $.split(/\r?\n/).map((W)=>{if(!Ok.test(W))return W;return W.replace(zk,"$1[redacted]").replace(qk,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(Mk,"$1 [redacted]").replace(/((?:^|[^\w])(?:api\s+key|access\s+token|refresh\s+token|auth(?:orization)?\s+token|secret|password|credential)\s+(?:is\s+)?)(\S+)/gi,"$1[redacted]")}).join(`
724
- `).slice(-LW)}function wk($){let W=Vf([$.stdout,$.stderr].filter(Boolean).join(`
725
- `)).trim();return W.length>0?W:void 0}function Ck($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function Pk($,W){return[$,...W].map((Z)=>Ck(Vf(Z).trim())).join(" ")}var Sk=async($,W)=>new Promise((Z,Q)=>{let J=!1,j=!1,X=Ak($,W,{env:process.env,shell:Dk()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V="",B=setTimeout(()=>{if(!J)X.kill("SIGKILL")},LX+5000),H=setTimeout(()=>{j=!0,V+=`
726
- Timed out after ${LX/1000}s.`,X.kill("SIGTERM")},LX);B.unref?.(),H.unref?.(),X.stdout?.on("data",(G)=>{if(Y+=String(G),Y.length>LW*2)Y=Y.slice(-LW)}),X.stderr?.on("data",(G)=>{if(V+=String(G),V.length>LW*2)V=V.slice(-LW)}),X.once("error",(G)=>{clearTimeout(H),clearTimeout(B),Q(G)}),X.once("close",(G,K)=>{J=!0,clearTimeout(H),clearTimeout(B),Z({exitCode:j?124:G??(K==="SIGINT"?130:1),stdout:Y,stderr:V})})});function OX($){return`${$.type}:${$.id}`}function TW($){let W=TX($);if(W.length===0)throw Error("Marketplace install args are required.");return UW(W).name}function kQ($,W={}){let Z=TW($),Q=W.mcpSettingsPath??Tk(),J=A1(Q,(j)=>{let X=j.mcpServers&&typeof j.mcpServers==="object"&&!Array.isArray(j.mcpServers)?j.mcpServers:{},Y=Object.hasOwn(X,Z);if(Y)delete X[Z];return j.mcpServers=X,Y});return{name:Z,deleted:J}}function OW($){let W=new Set,Z=(J)=>{let j=Ek(J??"");if(j&&j!=="skill")W.add(j)};Z($.id),Z($.name);let Q=TX($);for(let J=0;J<Q.length;J++){let j=Q[J];if((j==="--skill"||j==="-s")&&Q[J+1]){Z(Q[J+1]),J++;continue}let X=j.split("@").at(1);if(X)Z(X)}return[...W]}function zW($){return[Xf(Lk(),"skills",$,"SKILL.md"),Xf(Rk(),".agents","skills",$,"SKILL.md")].filter((W,Z,Q)=>Q.indexOf(W)===Z)}function qW($){if($.type!=="skill")return;return OW($).find((W)=>zW(W).some((Z)=>Yf(Z)))}function IQ($){return qW($)!==void 0}function bk($){let W=[];if($.type!=="skill")return W;for(let Z of OW($))for(let Q of zW(Z)){if(!Yf(Q))continue;let J=_k(Q);Uk(J,{recursive:!0,force:!0}),W.push(J)}return W}async function xQ($,W={}){let Z=qW($);if(!Z)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let Q="npx",J=["-y","skills@latest","remove",Z,"-g","-y"],j=Pk(Q,J),X=W.spawnCommand??Sk,Y;try{Y=await X(Q,J)}catch(H){throw Error(`Failed to start ${$.name??$.id} uninstall command:
720
+ version = team_outcome_fragments.version + 1`,[Q,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($,W){let Z=u6($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Z]);if(Q.length===0)return[];let J=YX();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
721
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[W,J,Z]),Q.map((j)=>j.run_id)}handleTeamEvent($,W){this.appendTeamEvent($,W.type,W)}}function VX($={}){try{let W=new j8($);return W.init(),W}catch{let W=new D9({teamDir:$.teamDir});return W.init(),W}}function IQ($,W){return Oh($,W)}function qh($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function Mh($,W){return $.filter((Z)=>qh(Z.name,W))}function BX($,W){return u1(Mh($,W))}var Rh={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 Eh($){let W=$.trim().toLowerCase();return Rh[W]??W}function Nh($,W){if(W.tools===void 0)return $;let Z=new Set(W.tools.map(Eh));if(W.skills!==void 0)Z.add("skills");return $.filter((Q)=>Z.has(Q.name))}function gQ(){return`team-${zh(5)}`}function xQ($,W,Z,Q,J,j,X,Y){let V=a0[e1({mode:Z})],B=r8(W,Q,Z,J??p8);return BX(y2({cwd:$,...V,enableSkills:!!X,...B,executors:{...X?{skills:X}:{},...Y??{}}}),j)}function wh($){return xQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,Ch,$.toolExecutors).some((W)=>W.name==="skills")}var Ch=async()=>"";async function Ph($){let W=J0();if(!X$({filePath:W}))return{tools:[]};let Z=new a2({clientFactory:z6({settingsPath:W})}),Q;try{Q=await n2(Z,{filePath:W})}catch(Y){await Z.dispose().catch(()=>{});let V=Y instanceof Error?Y.message:String(Y);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=Q.filter((Y)=>Y.disabled!==!0),j=await Promise.allSettled(J.map((Y)=>M6({serverName:Y.name,provider:Z}))),X=[];for(let[Y,V]of j.entries())if(V.status==="fulfilled")X.push(...V.value);else{let B=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[Y].name}", skipping: ${B}`)}return{tools:X,shutdown:async()=>{await Z.dispose()}}}function Sh($,W){if(!$)return;for(let Z of $.getTeammateIds())try{$.shutdownTeammate(Z,W)}catch{}}function bh($){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 yh($){let W=a0[e1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??W.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??W.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 d6{teamRuntimeEntries=new Map;async build($){let{config:W,hooks:Z,extensions:Q,logger:J,telemetry:j,createSpawnTool:X,onTeamRestored:Y,userInstructionService:V,configExtensions:B,toolExecutors:H}=$,G=$.onTeamEvent??(()=>{}),K=yh(W),F=W.workspaceRoot??W.cwd,A=$.toolPolicies??W.toolPolicies,D=L1(),U=[],f=W.teamName?.trim()||gQ(),_=W.sessionId?.trim()||f,R=K.enableSpawnAgent?w6({workspaceRoot:F}):{configs:[],errors:[]},O=R.configs.some((l)=>l.skills!==void 0),T=IQ(B,"rules"),L=IQ(B,"skills"),C=L||O,E=IQ(B,"workflows"),p=IQ(B,"plugins"),x=T||L||E,P=!1,r=Boolean(V),d=V,I1;for(let l of R.errors)(J??W.logger)?.log?.(`[agents] Failed to load agent config at ${l.path}: ${l.error.message}`);if(!d&&(x||O))d=c$({skills:C?{workspacePath:F,includePluginSkills:p,pluginSkillDirectories:p?$.pluginSkillDirectories:void 0,pluginPaths:W.pluginPaths,cwd:W.cwd}:{workspacePath:F},rules:{workspacePath:W.cwd},workflows:{workspacePath:W.cwd}});if(d)await d.start().catch(()=>{});let $2=K.enableTools&&L&&Boolean(d)&&d?.hasConfiguredSkills(W.skills)===!0&&wh({cwd:W.cwd,providerId:W.providerId,mode:K.mode,modelId:W.modelId,toolRoutingRules:W.toolRoutingRules,toolPolicies:A,toolExecutors:H}),A$=d&&x?d.createExtension({includeRules:T,includeSkills:L,includeWorkflows:E,registerSkillsTool:$2,allowedSkillNames:W.skills}):void 0,I0=A$?[...Q??W.extensions??[],A$]:Q??W.extensions;if(K.enableTools){if(U.push(...xQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H)),!K.disableMcpSettingsTools){let l=await Ph(W.logger);U.push(...l.tools),I1=l.shutdown}}let U0,D1=K.enableAgentTeams?VX():void 0,K8=D1?.loadRuntime(_),V0=K8?.state,d0=K8?.teammates??[],J1=new Map(d0.map((l)=>[l.agentId,l])),y=W.sessionId||f,j1,k=[],W0=!1,T0=S$({providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey??"",baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature,maxIterations:W.maxIterations,hooks:Z,extensions:I0,logger:J??W.logger,telemetry:$.telemetry??W.telemetry,workspaceMetadata:W.workspaceMetadata});if(K.enableSpawnAgent){if(R.configs.length>0)U.push(...BX(C6({configProvider:T0,agents:R.configs,createSubAgentTools:(l)=>K.enableTools?Nh(xQ(W.cwd,l.providerId??W.providerId,K.mode,l.modelId??W.modelId,W.toolRoutingRules,A,l.skills!==void 0&&d?.createSkillsExecutor?d.createSkillsExecutor(l.skills):void 0,H),l):[],hookErrorMode:W.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(y))this.teamRuntimeEntries.set(y,{delegatedAgentConfigProvider:T0});let q0=()=>{if(!K.enableAgentTeams)return;let l=this.teamRuntimeEntries.get(y)??{delegatedAgentConfigProvider:T0};if(this.teamRuntimeEntries.set(y,l),U0=l.runtime,!U0){if(U0=new e2({teamName:f,leadAgentId:W.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(B0)=>{if(G(B0),U0&&D1){if(B0.type==="teammate_spawned"&&B0.teammate?.rolePrompt){let x1={agentId:B0.agentId,rolePrompt:B0.teammate.rolePrompt,modelId:B0.teammate.modelId,maxIterations:B0.teammate.maxIterations};J1.set(x1.agentId,x1)}if(B0.type==="teammate_shutdown"&&!bh(B0.reason))J1.delete(B0.agentId);D1.handleTeamEvent(_,B0),D1.persistRuntime(_,U0.exportState(),Array.from(J1.values()))}}}),V0)U0.hydrateState(V0),W0=!0;l.runtime=U0}if(!P){if(!U0)return;P=!0;let B0=o8({runtime:U0,leadAgentId:W.sessionId||"lead",restoredFromPersistence:Boolean(V0),restoredTeammates:d0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(x1)=>{k=x1,j1?.addTools(x1)},createBaseTools:K.enableTools?()=>xQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H):void 0,teammateConfigProvider:T0});if(W0)U0.recoverActiveRuns("runtime_recovered");if(B0.restoredFromPersistence)Y?.();U.push(...B0.tools)}return U0};if(K.enableSpawnAgent&&X){let l=X();U.push({...l,execute:async(B0,x1)=>{return q0(),l.execute(B0,x1)}})}if(K.enableAgentTeams)q0();let d9=BX(U,A),t6=d9.some((l)=>l.name==="submit_and_exit"&&l.lifecycle?.completesRun===!0),F8=K.enableAgentTeams?()=>{let l=this.teamRuntimeEntries.get(y)?.runtime;if(!l)return;let B0=l.listTasks(),x1=B0.some((U$)=>U$.status==="in_progress"||U$.status==="pending"),rY=l.listRuns({}),hf=rY.some((U$)=>U$.status==="running"||U$.status==="queued");if(x1||hf){let U$=B0.filter((l0)=>l0.status==="in_progress"||l0.status==="pending").map((l0)=>`${l0.id} (${l0.status}): ${l0.title}`).join(", "),iY=rY.filter((l0)=>l0.status==="running"||l0.status==="queued").map((l0)=>`${l0.id} (${l0.status})`).join(", "),N7=[];if(U$)N7.push(`Unfinished tasks: ${U$}`);if(iY)N7.push(`Active runs: ${iY}`);return`[SYSTEM] You still have team obligations. ${N7.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,yf=t6?{requireCompletionTool:!0,...F8?{completionGuard:F8}:{}}:F8?{completionGuard:F8}:void 0;return{tools:d9,logger:J??W.logger,telemetry:j??W.telemetry,teamRuntime:U0,teamRestoredFromPersistence:Boolean(V0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(y)?.delegatedAgentConfigProvider??T0,extensions:I0,completionPolicy:yf,registerLeadAgent:(l)=>{if(j1=l,k.length>0)l.addTools(u1(k,[...D]))},shutdown:async(l)=>{if(Sh(U0,l),this.teamRuntimeEntries.delete(y),await I1?.(),!r)d?.stop()}}}}var JD={};w(JD,{requestDesktopToolApproval:()=>GX});import{mkdir as hh,readFile as kh,unlink as Ih,writeFile as xh}from"node:fs/promises";import{join as QD}from"node:path";function gh($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function mh($){return new Promise((W)=>setTimeout(W,$))}async function HX($){try{await Ih($)}catch{}}async function GX($,W={}){let Z=W.approvalDir?.trim(),Q=W.sessionId?.trim();if(!Z||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await hh(Z,{recursive:!0});let J=gh(`${$.toolCallId}`),j=QD(Z,`${Q}.request.${J}.json`),X=QD(Z,`${Q}.decision.${J}.json`),Y=W.nowIso??(()=>new Date().toISOString());await xh(j,`${JSON.stringify({requestId:J,sessionId:Q,createdAt:Y(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
722
+ `,"utf8");let V=W.timeoutMs??300000,B=W.pollIntervalMs??200,H=Date.now();while(Date.now()-H<V){try{let G=await kh(X,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([HX(X),HX(j)]),F}catch{}await mh(B)}return await HX(j),{approved:!1,reason:"Tool approval request timed out"}}X1();var fD={};w(fD,{uninstallMarketplaceSkill:()=>rQ,uninstallMarketplacePlugin:()=>iQ,uninstallMarketplaceMcpServerFromSettings:()=>lQ,uninstallMarketplaceEntry:()=>NX,resolveMarketplaceMcpServerName:()=>z9,marketplaceEntryKey:()=>EX,isMarketplaceSkillInstalled:()=>pQ,getMarketplaceSkillCandidates:()=>q9,getGlobalMarketplaceSkillPaths:()=>M9,findInstalledGlobalMarketplaceSkillName:()=>R9});import{spawn as zk}from"node:child_process";import{existsSync as DD,rmSync as qk}from"node:fs";import{homedir as Mk,platform as Rk}from"node:os";import{dirname as Ek,join as UD}from"node:path";import{resolveClineDir as Nk,resolveMcpSettingsPath as wk}from"@cline/shared/storage";var XD={};w(XD,{parseMcpInstallArgs:()=>_9,installMcpServer:()=>KX,buildMcpInstallTransport:()=>mQ});function vh($){let W=($??"stdio").trim();if(W==="http"||W==="streamable-http")return"streamableHttp";if(W==="stdio"||W==="sse"||W==="streamableHttp")return W;throw Error(`Unsupported MCP transport "${W}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function ch($){let W;try{W=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function uh($){let W=$.indexOf(":");if(W<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Z=$.slice(0,W).trim(),Q=$.slice(W+1).trim();if(!Z||!Q)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Z))throw Error(`Invalid MCP header name "${Z}".`);return[Z,Q]}function dh($){let W=$.indexOf("<");return W>=0&&$.indexOf(">",W+1)>W+1}function jD($){let W=[...$.headers??[]],Z=[],Q=$.transport,J=$.targetArgs??[];for(let j=0;j<J.length;j++){let X=J[j];if($.parseTransport&&X==="--transport"){let Y=J[j+1];if(!Y)throw Error("--transport requires a value");Q=Y,j++;continue}if($.parseTransport&&X?.startsWith("--transport=")){Q=X.slice(12);continue}if(X==="--header"){let Y=J[j+1];if(!Y)throw Error("--header requires a value");W.push(Y),j++;continue}if(X?.startsWith("--header=")){W.push(X.slice(9));continue}Z.push(X)}return{headers:W,targetArgs:Z,transport:Q}}function lh($){if($.length===0)return{warnings:[]};let W={},Z=[];for(let Q of $){let[J,j]=uh(Q);if(W[J]=j,dh(j))Z.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:W,warnings:Z}}function mQ($){let W=$.name.trim();if(!W)throw Error("MCP server name is required");let{headers:Z,targetArgs:Q,transport:J}=jD({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),j=vh(J),{headers:X,warnings:Y}=lh(Z);if(j==="stdio"){if(Z.length>0)throw Error("Stdio MCP installs do not support request headers.");let[B,...H]=Q;if(!B?.trim())throw Error("Stdio MCP install requires a command after the server name, for example: cline mcp install fs --yes -- npx -y @modelcontextprotocol/server-filesystem /tmp");return{name:W,transport:{type:j,command:B,args:H.length>0?H:void 0},warnings:Y}}if(Q.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=Q[0]?.trim()??"";return ch(V),{name:W,transport:X?{type:j,url:V,headers:X}:{type:j,url:V},warnings:Y}}function _9($){let[W,...Z]=$;if(!W)throw Error("Marketplace MCP install args must start with a server name.");return{name:W,...jD({parseTransport:!0,targetArgs:Z})}}function ph($,W,Z){A1(Z,(Q)=>{let J=Q.mcpServers,j=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};j[$]={transport:W},Q.mcpServers=j})}function KX($){let{name:W,transport:Z,warnings:Q}=mQ($);return ph(W,Z,$.settingsPath??J0()),{name:W,status:"installed",transport:Z,warnings:Q}}X1();var AD={};w(AD,{uninstallPlugin:()=>T9});import{existsSync as p6,readdirSync as $k,readFileSync as Wk,rmdirSync as Zk,rmSync as Qk,statSync as Jk}from"node:fs";import{basename as Z1,dirname as n$,extname as jk,isAbsolute as Xk,join as G$,relative as Yk,resolve as l6,sep as _X}from"node:path";import{discoverPluginModulePaths as Vk,resolvePluginConfigSearchPaths as Bk}from"@cline/shared/storage";var HD={};w(HD,{syncPluginMcpServersToSettings:()=>f9,removePluginMcpServersFromSettings:()=>L9,disablePluginMcpServersInSettings:()=>DX});import{existsSync as rh,mkdirSync as ih,readFileSync as nh,writeFileSync as ah}from"node:fs";import{dirname as VD,isAbsolute as oh,relative as sh,resolve as YD}from"node:path";function X8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function vQ($,W){let Z=sh(YD($),YD(W));return Z===""||!Z.startsWith("..")&&!oh(Z)}function FX($){if(!rh($))return{mcpServers:{}};try{let W=JSON.parse(nh($,"utf8"));if(X8(W))return W}catch(W){throw Error(`Invalid MCP settings at "${$}": ${W instanceof Error?W.message:String(W)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function AX($){if(X8($.mcpServers))return{...$.mcpServers};return{}}function UX($,W,Z){ih(VD($),{recursive:!0}),ah($,`${JSON.stringify({...W,mcpServers:Z},null,2)}
723
+ `,"utf8")}function BD($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((W)=>W.trim()).filter((W)=>W.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((W)=>W.trim()).filter((W)=>W.length>0))]}}function uQ($){if(!X8($))return;let W=$.metadata;return X8(W)?W:void 0}function cQ($,W){let Z=uQ($);if(!Z||Z.source!=="plugin")return!1;let Q=typeof Z.pluginName==="string"?Z.pluginName:typeof Z.plugin==="string"?Z.plugin:void 0,J=typeof Z.pluginPath==="string"?Z.pluginPath:void 0;if(W.pluginName&&Q===W.pluginName){if(!W.pluginPath||J===W.pluginPath)return!0}if(J&&W.pluginPath&&(J===W.pluginPath||vQ(W.pluginPath,J)||vQ(J,W.pluginPath)))return!0;if(Q&&W.pluginNames?.some((j)=>j===Q))return!0;if(J&&W.pluginPaths?.some((j)=>J===j||vQ(j,J)||vQ(J,j)))return!0;return!1}function th($){let W=X8($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:VD($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...W,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function eh($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let W=await j6({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Z=[],Q=[],J=(W.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of W.extensions??[]){let X=j.__clinePluginPath;if(!X)continue;if(!j.setup){Z.push({pluginName:j.name,pluginPath:X});continue}let Y=[],V={registerTool:(B)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(B)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');Y.push(B)}};try{await j.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(B){J.push({pluginPath:X,pluginName:j.name,message:B instanceof Error?B.message:String(B)});continue}Z.push({pluginName:j.name,pluginPath:X});for(let B of Y)Q.push({pluginName:j.name,pluginPath:X,server:{...B,metadata:{...B.metadata??{},source:"plugin",pluginName:j.name,pluginPath:X}}})}return{plugins:Z,servers:Q,failures:J}}finally{await W.shutdown().catch(()=>{})}}async function f9($){let W=$.settingsPath??J0(),Z={mutations:[],failures:[]},Q;try{Q=await eh($)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}Z.failures.push(...Q.failures);let J;try{J=FX(W)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}let j=AX(J),X=new Map,Y=new Map;for(let B of Q.plugins)X.set(B.pluginPath,new Set),Y.set(B.pluginPath,B.pluginName);let V=FQ(Q.servers.map((B)=>({server:B.server,owner:B,ownerLabel:B.pluginName})));for(let B of V){let H=B.owner;if(!X.has(H.pluginPath))X.set(H.pluginPath,new Set);if(B.name)X.get(H.pluginPath)?.add(B.name);if(!B.registration){Z.mutations.push({name:B.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:B.loadError??"invalid MCP server registration"});continue}let G=j[B.registration.name];if(G!==void 0){if(!cQ(G,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[B.registration.name]=th({registration:B.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:X8(G)?G:void 0}),Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:G===void 0?"created":"updated"})}for(let[B,H]of Object.entries(j)){let G=uQ(H),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=X.get(K);if(F&&cQ(H,{pluginPath:K})&&!F.has(B))delete j[B],Z.mutations.push({name:B,pluginName:typeof G?.pluginName==="string"?G.pluginName:Y.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Z.mutations.some((B)=>B.action!=="skipped"))try{UX(W,J,j)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)})}return Z}function DX($){let W=$.settingsPath??J0(),Z;try{Z=FX(W)}catch{return[]}let Q=AX(Z),J=BD($),j=[];for(let[X,Y]of Object.entries(Q)){if(!X8(Y)||!cQ(Y,J))continue;let V=uQ(Y);Q[X]={...Y,disabled:!0},j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(j.length>0)UX(W,Z,Q);return j}function L9($){let W=$.settingsPath??J0(),Z;try{Z=FX(W)}catch{return[]}let Q=AX(Z),J=BD($),j=[];for(let[X,Y]of Object.entries(Q)){if(!cQ(Y,J))continue;let V=uQ(Y);delete Q[X],j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(j.length>0)UX(W,Z,Q);return j}var zX="_installed",Hk="package",Gk=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function fX($){return $.trim().toLowerCase()}function U1($,W){let Z=W?.trim();if(!Z)return;$.add(Z)}function Kk($){return $.replace(/-[0-9a-f]{12}$/i,"")}function LX($){let W=jk($);return W?$.slice(0,-W.length):$}function TX($){if(!p6($))return;try{let W=JSON.parse(Wk($,"utf8"));return typeof W.name==="string"?W.name.trim():void 0}catch{return}}function qX($,W){let Z=Yk(W,$);return Z===""||!Z.startsWith("..")&&!Xk(Z)}function GD($){let Z=l6($).split(_X),Q=Z.lastIndexOf(zX);if(Q<0)return;let J=Z[Q+1];if(!J)return;let j=Gk.get(J)??1,X=Q+2+j;if(Z.length<X)return;let Y=Z.slice(0,X).join(_X)||_X;return p6(Y)?Y:void 0}function dQ($){try{return $k($,{withFileTypes:!0})}catch{return[]}}function Fk($){let W=G$($,zX);if(!p6(W))return[];let Z=[];for(let Q of dQ(W)){if(!Q.isDirectory())continue;let J=G$(W,Q.name);if(Q.name==="git"){for(let j of dQ(J)){if(!j.isDirectory())continue;let X=G$(J,j.name);for(let Y of dQ(X))if(Y.isDirectory())Z.push(G$(X,Y.name))}continue}for(let j of dQ(J))if(j.isDirectory())Z.push(G$(J,j.name))}return Z.sort((Q,J)=>Q.localeCompare(J))}function KD($){try{return Vk($)}catch{return[]}}function OX($){let W=KD($),Z=new Set;U1(Z,Z1($)),U1(Z,Kk(Z1($))),U1(Z,TX(G$($,"package.json"))),U1(Z,TX(G$($,Hk,"package.json")));for(let Q of W)U1(Z,Z1(Q)),U1(Z,LX(Z1(Q)));return{installPath:$,entryPaths:W,names:[...Z].sort((Q,J)=>Q.localeCompare(J)),installed:!0}}function Ak($,W){let Z=l6($),Q=W.find((X)=>qX(Z,X));if(!Q)return;let J=n$(Z);while(J!==Q&&J!==n$(J)){if(p6(G$(J,"package.json")))return J;J=n$(J)}let j=Z1(Z);if((j==="index.ts"||j==="index.js")&&n$(Z)!==Q)return n$(Z);return Z}function FD($,W){let Z=Ak($,W);if(!Z)return;let Q=new Set;return U1(Q,Z1($)),U1(Q,LX(Z1($))),U1(Q,Z1(Z)),U1(Q,LX(Z1(Z))),U1(Q,TX(G$(Z,"package.json"))),{installPath:Z,entryPaths:[$],names:[...Q].sort((J,j)=>J.localeCompare(j)),installed:!1}}function Uk($){let W=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Bk(W).filter((Z)=>p6(Z))}function Dk($){let W=new Map;for(let Z of $){for(let Q of Fk(Z))W.set(Q,OX(Q));for(let Q of KD(Z)){let J=GD(Q);if(J){if(!W.has(J))W.set(J,OX(J));continue}let j=FD(Q,$);if(j)W.set(j.installPath,j)}}return[...W.values()].sort((Z,Q)=>Z.installPath.localeCompare(Q.installPath))}function _k($,W){let Z=fX(W);if(!Z)return!1;if(fX($.installPath)===Z)return!0;return $.names.some((Q)=>fX(Q)===Z)}function fk($,W,Z){let Q=l6($);for(let j of W){if(qX(Q,j.installPath))return j;if(j.entryPaths.some((X)=>l6(X)===Q))return j}let J=GD(Q);if(J)return OX(J);if(p6(Q))return FD(Q,Z);return}function Lk($){let W=E0(),Z=W.disabledPlugins;if(!Z?.length)return;let Q=Z.filter((J)=>{let j=l6(J);if(qX(j,$.installPath))return!1;return!$.entryPaths.some((X)=>l6(X)===j)});if(Q.length===Z.length)return;f1({...W,disabledPlugins:Q})}function Tk($){let W=n$($);while(W!==n$(W)&&Z1(W)!==zX){try{Zk(W)}catch{return}W=n$(W)}}function Ok($){return`${$.names[0]??Z1($.installPath)} at ${$.installPath}`}async function T9($){let W=Uk($),Z=Dk(W),Q=$.path?.trim(),J=$.name?.trim(),j;if(Q){if(j=fk(Q,Z,W),!j)throw Error(`No plugin found at ${Q}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let Y=Z.filter((V)=>_k(V,J));if(Y.length===0)throw Error(`No plugin found matching "${J}"`);if(Y.length>1)throw Error(`Multiple plugins match "${J}": ${Y.map(Ok).join(", ")}`);j=Y[0]}let X=Jk(j.installPath,{throwIfNoEntry:!1});if(!X)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(L9({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),Qk(j.installPath,{recursive:X.isDirectory(),force:!0}),Lk(j),j.installed)Tk(j.installPath);return{name:J||j.names[0]||Z1(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var MX=120000,O9=12000,Ck=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,Pk=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,Sk=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,bk=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function RX($){return $.install?.args??[]}function yk(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||Mk()}function hk($){let W=0,Z=$.length;while(W<Z&&($[W]==="."||$[W]==="-"))W++;while(Z>W&&($[Z-1]==="."||$[Z-1]==="-"))Z--;return $.slice(W,Z)}function kk($){return hk($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function _D($){return $.split(/\r?\n/).map((W)=>{if(!Ck.test(W))return W;return W.replace(Pk,"$1[redacted]").replace(Sk,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(bk,"$1 [redacted]").replace(/((?:^|[^\w])(?:api\s+key|access\s+token|refresh\s+token|auth(?:orization)?\s+token|secret|password|credential)\s+(?:is\s+)?)(\S+)/gi,"$1[redacted]")}).join(`
724
+ `).slice(-O9)}function Ik($){let W=_D([$.stdout,$.stderr].filter(Boolean).join(`
725
+ `)).trim();return W.length>0?W:void 0}function xk($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function gk($,W){return[$,...W].map((Z)=>xk(_D(Z).trim())).join(" ")}var mk=async($,W)=>new Promise((Z,Q)=>{let J=!1,j=!1,X=zk($,W,{env:process.env,shell:Rk()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V="",B=setTimeout(()=>{if(!J)X.kill("SIGKILL")},MX+5000),H=setTimeout(()=>{j=!0,V+=`
726
+ Timed out after ${MX/1000}s.`,X.kill("SIGTERM")},MX);B.unref?.(),H.unref?.(),X.stdout?.on("data",(G)=>{if(Y+=String(G),Y.length>O9*2)Y=Y.slice(-O9)}),X.stderr?.on("data",(G)=>{if(V+=String(G),V.length>O9*2)V=V.slice(-O9)}),X.once("error",(G)=>{clearTimeout(H),clearTimeout(B),Q(G)}),X.once("close",(G,K)=>{J=!0,clearTimeout(H),clearTimeout(B),Z({exitCode:j?124:G??(K==="SIGINT"?130:1),stdout:Y,stderr:V})})});function EX($){return`${$.type}:${$.id}`}function z9($){let W=RX($);if(W.length===0)throw Error("Marketplace install args are required.");return _9(W).name}function lQ($,W={}){let Z=z9($),Q=W.mcpSettingsPath??wk(),J=A1(Q,(j)=>{let X=j.mcpServers&&typeof j.mcpServers==="object"&&!Array.isArray(j.mcpServers)?j.mcpServers:{},Y=Object.hasOwn(X,Z);if(Y)delete X[Z];return j.mcpServers=X,Y});return{name:Z,deleted:J}}function q9($){let W=new Set,Z=(J)=>{let j=kk(J??"");if(j&&j!=="skill")W.add(j)};Z($.id),Z($.name);let Q=RX($);for(let J=0;J<Q.length;J++){let j=Q[J];if((j==="--skill"||j==="-s")&&Q[J+1]){Z(Q[J+1]),J++;continue}let X=j.split("@").at(1);if(X)Z(X)}return[...W]}function M9($){return[UD(Nk(),"skills",$,"SKILL.md"),UD(yk(),".agents","skills",$,"SKILL.md")].filter((W,Z,Q)=>Q.indexOf(W)===Z)}function R9($){if($.type!=="skill")return;return q9($).find((W)=>M9(W).some((Z)=>DD(Z)))}function pQ($){return R9($)!==void 0}function vk($){let W=[];if($.type!=="skill")return W;for(let Z of q9($))for(let Q of M9(Z)){if(!DD(Q))continue;let J=Ek(Q);qk(J,{recursive:!0,force:!0}),W.push(J)}return W}async function rQ($,W={}){let Z=R9($);if(!Z)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let Q="npx",J=["-y","skills@latest","remove",Z,"-g","-y"],j=gk(Q,J),X=W.spawnCommand??mk,Y;try{Y=await X(Q,J)}catch(H){throw Error(`Failed to start ${$.name??$.id} uninstall command:
727
727
  ${j}
728
- ${H instanceof Error?H.message:String(H)}`)}let V=wk(Y);if(Y.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${Y.exitCode}.
728
+ ${H instanceof Error?H.message:String(H)}`)}let V=Ik(Y);if(Y.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${Y.exitCode}.
729
729
  Command:
730
730
  ${j}${V?`
731
731
 
732
- ${V}`:""}`);let B=bk($);if(IQ($))throw Error(`Skill uninstall completed, but ${$.name??$.id} is still present in Cline's global skills directories.`);return{id:$.id,type:"skill",status:"uninstalled",message:`Uninstalled ${$.name??$.id}.`,output:[V,...B.map((H)=>`Removed: ${H}`)].filter(Boolean).join(`
733
- `)||void 0}}async function gQ($,W={}){let[Z]=TX($),Q=Z?.trim()||$.id;if(!Q)throw Error("Plugin marketplace uninstalls require a plugin name.");let J=await _W({name:Q,workspaceRoot:W.workspaceRoot});return{id:$.id,type:"plugin",status:"uninstalled",message:`Uninstalled ${$.name??J.name??$.id}.`,output:[`Path: ${J.installPath}`,...J.removedPaths.map((j)=>`Removed: ${j}`)].join(`
734
- `)}}async function zX($,W={}){if($.type==="mcp"){let Z=TW($);if(W.deleteMcpServer)await W.deleteMcpServer(Z);else kQ($,W);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Z??$.id}.`}}if($.type==="skill")return xQ($,W);if($.type==="plugin")return gQ($,W);throw Error(`Unsupported marketplace entry type: ${$.type}`)}var qf={};w(qf,{parsePluginSource:()=>iQ,isOfficialPluginSlug:()=>rQ,installPlugin:()=>wX,collectPluginMcpOAuthCandidates:()=>nQ});import{spawn as yk}from"node:child_process";import{createHash as hk}from"node:crypto";import{existsSync as y1,mkdirSync as RX,readdirSync as kk,readFileSync as Ik,renameSync as mQ,rmSync as uQ,statSync as NX}from"node:fs";import{cp as MX,mkdir as Df,writeFile as dQ}from"node:fs/promises";import{homedir as Hf}from"node:os";import{basename as K$,dirname as Gf,extname as xk,join as s,relative as _f,resolve as n$,sep as gk}from"node:path";import{isPluginModulePath as cQ,resolveClineDir as mk,resolvePluginModuleEntries as vk}from"@cline/shared/storage";var l6="_installed",lQ="package",ck="https://github.com/cline/plugins.git",Kf=30000,vQ=10485760,Ff="@cline/",uk=["dependencies","devDependencies","optionalDependencies","peerDependencies"],dk={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function pQ($){if($==="~")return Hf();if($.startsWith("~/"))return s(Hf(),$.slice(2));return $}function Lf($){return $.split(gk).join("/")}function X8($){return hk("sha256").update($).digest("hex").slice(0,12)}function lk($){let W=0;while(W<$.length&&$[W]==="-")W++;let Z=$.length;while(Z>W&&$[Z-1]==="-")Z--;return $.slice(W,Z)}function G$($){let W="",Z=!1,Q=$.startsWith("@")?$.slice(1):$;for(let j of Q.slice(0,256)){if(j>="a"&&j<="z"||j>="A"&&j<="Z"||j>="0"&&j<="9"||j==="."||j==="_"||j==="-")W+=j,Z=j==="-";else if(!Z)W+="-",Z=!0;if(W.length>=80)break}return lk(W)||"plugin"}function rQ($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function pk($){return $?.trim()||ck}function Af($){let Z=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Z?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Z[1]}}function rk($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[W,...Z]=$.split("/");return!!W&&Z.length>=2&&W.includes(".")&&!W.startsWith(".")&&!W.endsWith(".")}function ik($){let W=$.match(/^git@([^:]+):(.+)$/);if(W){let X=W[2]??"",Y=X.indexOf("@");if(Y<0)return{repo:$};return{repo:`git@${W[1]}:${X.slice(0,Y)}`,ref:X.slice(Y+1)||void 0}}if($.includes("://"))try{let X=new URL($),Y=X.pathname.replace(/^\/+/,""),V=Y.indexOf("@");if(V<0)return{repo:$};return X.pathname=`/${Y.slice(0,V)}`,{repo:X.toString().replace(/\/$/,""),ref:Y.slice(V+1)||void 0}}catch{return{repo:$}}let Z=$.indexOf("/");if(Z<0)return{repo:$};let Q=$.slice(0,Z),J=$.slice(Z+1),j=J.indexOf("@");if(j<0)return{repo:$};return{repo:`${Q}/${J.slice(0,j)}`,ref:J.slice(j+1)||void 0}}function nk($){try{return decodeURIComponent($)}catch{return $}}function ak($){return K$(nk($))||"plugin"}function ok($){let W=$.split("/").filter(Boolean);return W.length>=5&&(W[2]==="blob"||W[2]==="raw")}function Uf($){if(!/^https?:\/\//i.test($))return null;let W;try{W=new URL($)}catch{return null}let Z=W.hostname.toLowerCase(),Q=ak(W.pathname),J=cQ(Q),j=(Z==="github.com"||Z==="www.github.com")&&ok(W.pathname);if(W.protocol!=="https:"){if(j||Z==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Z==="github.com"||Z==="www.github.com"){let X=W.pathname.split("/").filter(Boolean);if(!j)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[X[0],X[1],...X.slice(3)].join("/")}`,filename:Q}}if(Z==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:W.toString(),filename:Q}}if(!J)return null;return{type:"remote",url:W.toString(),filename:Q}}function ff($,W={}){let Z=$.trim(),Q=Z.startsWith("git:")&&!Z.startsWith("git://"),J=Q?Z.slice(4).trim():Z;if(!W.force&&!Q&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:j,ref:X}=ik(J),Y="",V="";if(j.startsWith("git@")){let G=j.match(/^git@([^:]+):(.+)$/);Y=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(j)){let G=new URL(j);Y=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=j.indexOf("/");if(G<0)return null;Y=j.slice(0,G),V=j.slice(G+1)}let B=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!Y||!B||B.split("/").length<2)return null;return{type:"git",repo:j.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(j)?j:`https://${j}`,ref:X,host:Y,path:B}}function iQ($,W){let Z=$.trim();if(!Z)throw Error("plugin install requires a source");if(W==="npm"){let X=Z.startsWith("npm:")?Z.slice(4).trim():Z,{name:Y}=Af(X);return{type:"npm",spec:X,name:Y}}if(W==="git"){let X=ff(Z,{force:!0});if(!X)throw Error(`Invalid git plugin source: ${$}`);return X}if(W==="local")return{type:"local",path:$};if(W==="remote"){let X=Uf(Z);if(!X)throw Error(`Invalid remote plugin source: ${$}`);return X}if(Z.startsWith("npm:")){let X=Z.slice(4).trim(),{name:Y}=Af(X);return{type:"npm",spec:X,name:Y}}if(Z.startsWith(".")||Z.startsWith("/")||Z==="~"||Z.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Z))return{type:"local",path:$};let J=Uf(Z);if(J)return J;let j=ff(Z);if(j)return j;if(rQ(Z))return{type:"official",slug:Z};if(rk(Z))throw Error(`Unrecognized plugin source "${$}". Use --git for hostname-style repositories or pass an explicit local path such as ./github.com/owner/repo.`);return{type:"local",path:$}}function sk($){return $?s($,".cline","plugins"):s(mk(),"plugins")}function tk($,W,Z){if(W.type==="npm")return s($,l6,"npm",`${G$(W.name)}-${X8(Z)}`);if(W.type==="git")return s($,l6,"git",G$(W.host),`${G$(W.path)}-${X8(Z)}`);if(W.type==="remote")return s($,l6,"remote",`${G$(W.filename)}-${X8(Z)}`);if(W.type==="official")return s($,l6,"official",`${G$(W.slug)}-${X8(Z)}`);return s($,l6,"local",`${G$(K$(pQ(W.path)))}-${X8(Z)}`)}function ek($,W,Z){if($.type==="npm")return`npm:${$.spec}`;if($.type==="git")return`git:${$.repo}${$.ref?`#${$.ref}`:""}`;if($.type==="remote")return`remote:${$.url}`;if($.type==="official")return`official:${Z}#plugins/${$.slug}`;return`local:${n$(W,pQ($.path))}`}function $I($,W){if($.type==="npm")return $.name;if($.type==="git")return G$(K$($.path));if($.type==="remote")return G$(K$($.filename,xk($.filename)));if($.type==="official")return $.slug;return G$(K$(n$(W,pQ($.path))))}async function p6($,W,Z={}){await new Promise((Q,J)=>{let j=yk($,W,{cwd:Z.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),X="";j.stderr.on("data",(Y)=>{X+=String(Y)}),j.on("error",J),j.on("close",(Y)=>{if(Y===0){Q();return}let V=X.trim();J(Error(`${$} ${W.join(" ")} failed with exit code ${Y}${V?`: ${V}`:""}`))})})}function Tf($){let W=s($,"package.json");if(!y1(W))return null;try{return JSON.parse(Ik(W,"utf8"))}catch{return null}}function WI($){let W=$?.cline?.plugins;if(!Array.isArray(W))return[];return W.flatMap((Z)=>{if(typeof Z==="string")return[Z];return Z.paths??[]})}async function ZI($){let W=s($,"package.json"),Z=Tf($);if(!Z)return;let Q=!1;for(let J of uk){let j=Z[J];if(!j||typeof j!=="object")continue;for(let X of Object.keys(j)){if(!X.startsWith(Ff))continue;delete j[X],delete Z.peerDependenciesMeta?.[X],Q=!0}if(Object.keys(j).length===0)delete Z[J]}if(Z.peerDependenciesMeta){for(let J of Object.keys(Z.peerDependenciesMeta)){if(!J.startsWith(Ff))continue;delete Z.peerDependenciesMeta[J],Q=!0}if(Object.keys(Z.peerDependenciesMeta).length===0)delete Z.peerDependenciesMeta}if(!Q)return;await dQ(W,`${JSON.stringify(Z,null,2)}
735
- `,"utf8")}function QI($,W){let Z=s($,"node_modules","@cline");if(!y1(Z))return;for(let Q of zf(Z)){if(`@cline/${Q.name}`===W)continue;uQ(s(Z,Q.name),{recursive:!0,force:!0})}}function Of($){let W=WI(Tf($)).map((j)=>n$($,j)).filter((j)=>y1(j)&&NX(j).isFile()&&cQ(j));if(W.length>0)return W;let Z=vk($);if(Z?.length)return Z;let Q=[],J=[$];while(J.length>0){let j=J.pop();if(!j)continue;for(let X of zf(j)){let Y=s(j,X.name);if(X.name==="node_modules"||X.name===".git")continue;if(X.isDirectory()){J.push(Y);continue}if(X.isFile()&&!X.name.startsWith(".")&&cQ(Y))Q.push(Y)}}return Q.sort((j,X)=>j.localeCompare(X))}function zf($){try{return kk($,{withFileTypes:!0})}catch{return[]}}function JI($,W){let Z=Of(W);if(Z.length===0)throw Error(`No plugin entry files found in ${W}`);return Z.map((Q)=>`./${Lf(_f($,Q))}`)}async function jI($,W,Z){let Q=JI($,W);return await dQ(s($,"package.json"),JSON.stringify({...dk,name:Z,cline:{plugins:[{paths:Q}]}},null,2),"utf8"),Q}async function XI($,W,Z){let Q=s(W,lQ);return await Df(Q,{recursive:!0}),await dQ(s(Q,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await p6(Z,["install",$.spec,"--prefix",Q,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),QI(Q,$.name),s(Q,"node_modules",$.name)}async function EX($,W){if(!y1(s($,"package.json")))return;await ZI($),await p6(W,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function YI($,W,Z){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let Q=s(W,lQ),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,Q);try{await p6("git",J)}catch(j){if(!$.ref)throw j;await p6("git",["clone","--filter=blob:none","--",$.repo,Q]),await p6("git",["checkout","--detach",$.ref],{cwd:Q})}return await EX(Q,Z),Q}async function VI($,W,Z,Q){let J=s(W,"repo");await p6("git",["clone","--filter=blob:none","--depth","1","--",Q,J]);let j=s(J,"plugins",$.slug);if(!y1(j)||!NX(j).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${Q}`);let X=s(W,lQ);return await MX(j,X,{recursive:!0,filter:(Y)=>{let V=K$(Y);return V!==".git"&&V!=="node_modules"}}),uQ(J,{recursive:!0,force:!0}),await EX(X,Z),X}function qX($){return Error(`Remote plugin file from ${$} exceeds the ${vQ} byte limit`)}function BI($){let W=$.headers.get("content-length");if(!W)return;let Z=Number(W);if(!Number.isFinite(Z)||Z<0)return;return Z}async function HI($,W){let Z=BI($);if(Z!==void 0&&Z>vQ)throw qX(W);if(!$.body){let X=Buffer.from(await $.text(),"utf8");if(X.byteLength>vQ)throw qX(W);return X}let Q=$.body.getReader(),J=[],j=0;try{while(!0){let{done:X,value:Y}=await Q.read();if(X)break;let V=Buffer.from(Y);if(j+=V.byteLength,j>vQ)throw await Q.cancel().catch(()=>{return}),qX(W);J.push(V)}return Buffer.concat(J,j)}finally{Q.releaseLock()}}async function GI($,W){let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},Kf);try{let J=await fetch($.url,{signal:Z.signal});if(!J.ok){let X=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${X}`)}let j=await HI(J,$.url);return RX(W,{recursive:!0}),await dQ(s(W,$.filename),j),W}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${Kf}ms`);throw J}finally{clearTimeout(Q)}}async function KI($,W,Z,Q){let J=n$(Z,pQ($.path));if(!y1(J))throw Error(`Plugin source path does not exist: ${J}`);let j=NX(J);if(j.isFile()){if(!cQ(J))throw Error(`Plugin file must be .js or .ts: ${J}`);RX(W,{recursive:!0});let Y=s(W,K$(J));return await MX(J,Y),W}if(!j.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let X=s(W,lQ);return await MX(J,X,{recursive:!0,filter:(Y)=>{let V=K$(Y);return V!==".git"&&V!=="node_modules"}}),await EX(X,Q),X}function FI($,W){if(y1($)&&!W)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function AI($,W,Z){if(RX(Gf(W),{recursive:!0}),!y1(W)){mQ($,W);return}if(!Z)throw Error(`Plugin is already installed at ${W}. Use --force to replace it.`);let Q=s(Gf(W),`.replace-${K$(W)}-${Date.now()}-${process.pid}-${X8(`${W}:${Math.random()}`)}`);mQ(W,Q);try{mQ($,W)}catch(J){if(!y1(W)&&y1(Q))mQ(Q,W);throw J}try{uQ(Q,{recursive:!0,force:!0})}catch{}}function UI($){let W=$.transport;if(W.type==="stdio")return!1;return W.headers!==void 0&&Object.keys(W.headers).length>0}function fI($){let W=$.oauth?.tokens?.access_token;return typeof W==="string"&&W.trim().length>0}function DI($){let W=$.metadata;if(!W||W.source!=="plugin"||typeof W.pluginName!=="string"||typeof W.pluginPath!=="string")return;return{pluginName:W.pluginName,pluginPath:W.pluginPath}}function nQ($){let W=new Set($.pluginPaths.map((J)=>n$(J)));if(W.size===0)return[];let Z;try{Z=t0({filePath:$.settingsPath??J0()})}catch{return[]}let Q=[];for(let J of Z){let j=DI(J);if(!j||!W.has(n$(j.pluginPath)))continue;let X=J.transport.type;if(X==="stdio")continue;if(UI(J)||fI(J))continue;Q.push({name:J.name,pluginName:j.pluginName,pluginPath:j.pluginPath,transportType:X,lastError:J.oauth?.lastError})}return Q.sort((J,j)=>J.name.localeCompare(j.name))}async function wX($){let W=$.source.trim(),Z=iQ(W,$.sourceType),Q=$.cwd?.trim(),J=Q?n$(Q):process.cwd(),j=sk(Q?J:void 0),X=pk($.officialPluginsRepo),Y=ek(Z,J,X),V=tk(j,Z,Y),B=$I(Z,J),H=s(j,l6,".tmp"),G=s(H,`${Date.now()}-${process.pid}-${X8(`${W}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;FI(V,F),await Df(H,{recursive:!0});let A;try{if(Z.type==="npm")A=await XI(Z,G,K);else if(Z.type==="git")A=await YI(Z,G,K);else if(Z.type==="official")A=await VI(Z,G,K,X);else if(Z.type==="remote")A=await GI(Z,G);else A=await KI(Z,G,J,K);let f=(Z.type==="local"||Z.type==="remote")&&A===G?Of(G).map((D)=>`./${Lf(_f(G,D))}`):await jI(G,A,B);if(f.length===0)throw Error(`No plugin entry files found for ${W}`);AI(G,V,F);let U={source:W,installPath:V,entryPaths:f.map((D)=>n$(V,D)),mcpSyncFailures:[],mcpOAuthCandidates:[]},_=await fW({pluginPaths:U.entryPaths,cwd:J,workspacePath:J});return U.mcpSyncFailures=_.failures,U.mcpOAuthCandidates=nQ({pluginPaths:U.entryPaths}),U}catch(f){throw uQ(G,{recursive:!0,force:!0}),f}}var lf={};w(lf,{updateLocalProvider:()=>Z7,saveLocalProviderSettings:()=>xX,saveLocalProviderOAuthCredentials:()=>cX,resolveLocalClineAuthToken:()=>dX,refreshProviderModelsFromSource:()=>gX,normalizeOAuthProvider:()=>mX,markLocalProviderEnabled:()=>hX,loginLocalProvider:()=>vX,loginAndSaveLocalProviderOAuthCredentials:()=>uX,listLocalProviders:()=>kX,getLocalProviderModels:()=>IX,ensureCustomProvidersLoaded:()=>eQ,deleteLocalProvider:()=>Q7,addLocalProvider:()=>yX});import*as h0 from"@cline/llms";import{existsSync as _I,mkdirSync as LI,readFileSync as TI,writeFileSync as OI}from"node:fs";import{mkdir as zI,readFile as qI,writeFile as MI}from"node:fs/promises";import{dirname as CX,join as RI}from"node:path";import*as v0 from"@cline/llms";import{ModelCapabilitySchema as NI,ProviderCapabilitySchema as EI,ProviderClientSchema as wI,ProviderProtocolSchema as CI}from"@cline/shared";import{z as t}from"zod";var PI=t.object({id:t.string().optional(),name:t.string().optional(),maxTokens:t.number().optional(),contextWindow:t.number().optional(),maxInputTokens:t.number().optional(),capabilities:t.array(NI).optional(),supportsVision:t.boolean().optional(),supportsAttachments:t.boolean().optional(),supportsReasoning:t.boolean().optional()}).passthrough(),SI=t.object({name:t.string(),baseUrl:t.string(),defaultModelId:t.string().optional(),protocol:CI.optional(),client:wI.optional(),capabilities:t.array(EI).optional(),modelsSourceUrl:t.string().optional()}).passthrough(),Mf=t.object({provider:SI.optional(),models:t.record(t.string(),PI).optional()}).passthrough(),Rf=t.object({version:t.literal(1),providers:t.record(t.string(),Mf)}),bI=t.object({version:t.literal(1),providers:t.record(t.string(),t.unknown())}),aQ=new Set;function Nf($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function Y8($){return RI(CX($.getFilePath()),"models.json")}function oQ(){return{version:1,providers:{}}}function Ef($){let W=bI.safeParse($);if(!W.success)return oQ();let Z={};for(let[Q,J]of Object.entries(W.data.providers)){let j=Mf.safeParse(J);if(j.success)Z[Q]=j.data}return{version:1,providers:Z}}function PX($){if(!_I($))return oQ();try{let W=TI($,"utf8");return Ef(JSON.parse(W))}catch{}return oQ()}async function r6($){try{let W=await qI($,"utf8");return Ef(JSON.parse(W))}catch{}return oQ()}function wf($,W){LI(CX($),{recursive:!0});let Z=Rf.parse(W);OI($,`${JSON.stringify(Z,null,2)}
736
- `,"utf8")}async function sQ($,W){await zI(CX($),{recursive:!0});let Z=Rf.parse(W);await MI($,`${JSON.stringify(Z,null,2)}
737
- `,"utf8")}function Cf($,W){return{id:$,name:W.name??$,supportsAttachments:W.capabilities?.includes("files"),supportsVision:W.capabilities?.includes("images"),supportsReasoning:W.capabilities?.includes("reasoning")||W.thinkingConfig!=null}}function Pf($){if(!$||$.length===0)return;let W=new Set;if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("tools"))W.add("tools");return W.size>0?[...W]:void 0}function Sf($){let W=new Set;if(!$||$.length===0)return[...W];if($.includes("streaming"))W.add("streaming");if($.includes("tools"))W.add("tools");if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("vision"))W.add("images"),W.add("files");return[...W]}function yI($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function bf($,W){return $??W??"openai-chat"}function yf($,W,Z){return $??Z??(W==="openai-responses"?"openai":"openai-compatible")}function hf($,W,Z){let Q=new Set(W?.capabilities??Z??[]);if(W?.supportsVision)Q.add("images");if(W?.supportsAttachments)Q.add("files");if(W?.supportsReasoning)Q.add("reasoning");return{id:$,name:W?.name??$,maxTokens:W?.maxTokens,contextWindow:W?.contextWindow,maxInputTokens:W?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function hI($,W){for(let[Z,Q]of Object.entries(W??{})){let J=Q.id?.trim()||Z.trim();if(!J)continue;v0.registerModel($,J,hf(J,Q))}}function kI($,W,Z){return{...W??{},id:$,name:W?.name??$,capabilities:W?.capabilities??Z}}function II($){return Object.assign({},...v0.resolveProviderModelCatalogKeys($).map((Z)=>v0.getGeneratedModelsForProvider(Z)))}function xI($){let W=$.provider.trim();if(!W||v0.isBuiltInProviderId(W))return;let Z=$.baseUrl?.trim();if(!Z)return;let Q=v0.MODEL_COLLECTIONS_BY_PROVIDER_ID[W],J=II(W),j=Sf($.capabilities),X=j.length>0?j:void 0,Y=$.model?.trim(),V={...J,...Q?.models??{}};if(Y)V[Y]=kI(Y,V[Y],X);let B=Object.keys(V).filter(Boolean),H=Y||B[0];if(!H)return;let G=bf($.protocol,Q?.provider.protocol),K=yf($.client,G,Q?.provider.client);v0.registerProvider({provider:{id:W,name:Q?.provider.name??Nf(W),description:Q?.provider.description,protocol:G,client:K,baseUrl:Z,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:H,capabilities:Pf($.capabilities)??Q?.provider.capabilities,source:"file"},models:V})}function tQ($){for(let W of Object.values($.providers))xI(W.settings)}function MW($,W){let Z=W.models??{};if(!yI(W.provider)){hI($,Z);return}let Q=Sf(W.provider.capabilities),J=Object.entries(Z).map(([B,H])=>({id:H.id?.trim()||B.trim(),model:H})).filter(({id:B})=>B.length>0),j=W.provider.defaultModelId?.trim()||J[0]?.id||"default",X=bf(W.provider.protocol,void 0),Y=yf(W.provider.client,X,void 0),V=Object.fromEntries(J.map(({id:B,model:H})=>[B,{...hf(B,H,Q.length>0?Q:void 0),status:"active"}]));v0.registerProvider({provider:{id:$,name:W.provider.name.trim()||Nf($),protocol:X,client:Y,baseUrl:W.provider.baseUrl,modelsSourceUrl:W.provider.modelsSourceUrl,defaultModelId:j,capabilities:Pf(W.provider.capabilities),source:"file"},models:V})}function kf($){let W=Y8($);if(aQ.has(W))return;let Z=PX(W);for(let[Q,J]of Object.entries(Z.providers))MW(Q,J);aQ.add(W)}async function eQ($){let W=Y8($);if(aQ.has(W))return;let Z=await r6(W);for(let[Q,J]of Object.entries(Z.providers))MW(Q,J);aQ.add(W)}var xf="cline-pass";function gI($){return $.apiKey??$.auth?.apiKey}function mI($){return($.auth?.accessToken?.trim()??"").length>0}function gf($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function vI($){let W=$.split(/\s+/).filter(Boolean);if(W.length===0)return"?";if(W.length===1)return W[0].slice(0,2).toUpperCase();return`${W[0][0]}${W[1][0]}`.toUpperCase()}function cI($){let W=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Z=0;for(let Q of $)Z=Z*31+Q.charCodeAt(0)>>>0;return W[Z%W.length]}function mf($){return Object.entries($).sort(([W],[Z])=>W.localeCompare(Z)).map(([W,Z])=>Cf(W,Z))}async function uI($,W){let Z=await h0.getModelsForProvider($),Q=$===xf;if(!W&&!Q)return Z;let J=await q5($,{loadLatestOnInit:Q,loadPrivateOnAuth:!0,failOnError:!1},W);if($==="litellm"&&J?.knownModels)return J.knownModels;if(Q&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Z,...J.knownModels}:Z}function SX($){return[...new Set(($??[]).map((W)=>W.trim()).filter(Boolean))]}function dI($){if(!$?.length)return;return[...new Set($)]}function lI($,W){return dI([...$??[],...W??[]])}function pI($){let W=$?.popularRank;return typeof W==="number"&&Number.isFinite(W)?W:Number.MAX_SAFE_INTEGER}function rI($){if(!$||typeof $!=="object")return!1;let W=$;return typeof W.path==="string"&&W.path.trim().length>0&&typeof W.label==="string"&&W.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(W.type))}function iI($){let W=$?.configFields;if(!Array.isArray(W))return;return W.filter(rI)}var $7={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},If={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function nI($){if(!$)return[$7];if($.source!=="system")return $.baseUrl?[$7,If]:[$7];let W=[];if($.env?.length)W.push($7);if($.baseUrl)W.push(If);return W}function aI($,W){return W.split(".").reduce((Z,Q)=>{if(!Z||typeof Z!=="object")return;return Z[Q]},$)}function oI($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function sI($,W,Z){if(!$?.length)return;let Q={};for(let J of $){let X=oI(J.path==="baseUrl"&&W?.baseUrl===void 0?Z?.baseUrl:aI(W,J.path))??J.defaultValue;if(X!==void 0)Q[J.path]=X}return Q}function vf($){let W=Object.entries($??{}).filter(([Z])=>Z.trim().length>0);return W.length>0?Object.fromEntries(W):void 0}function bX($,W){let Z=W?.includes("vision")??!1,Q=W?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Z,supportsAttachments:Z,supportsReasoning:Q}]))}async function cf($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let W=$.modelsSourceUrl?await _Z($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...W])]}function uf($,W){let Z=$.read(),Q=!1;if(Z.providers[W])delete Z.providers[W],Q=!0;if(Z.lastUsedProvider===W)delete Z.lastUsedProvider,Q=!0;if(Q)$.write(Z);h0.unregisterProvider(W)}async function yX($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=W.baseUrl.trim(),J=W.apiKey?.trim()??"";if(!Q&&!J){let A=Y8($);if((await r6(A)).providers[Z]){let U=await Q7($,{providerId:Z});return{providerId:Z,settingsPath:U.settingsPath,modelsPath:U.modelsPath,modelsCount:0}}return uf($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(h0.hasProvider(Z))throw Error(`provider "${Z}" already exists`);let j=W.name.trim();if(!j)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let X=SX(W.models),Y=W.modelsSourceUrl?.trim(),V=await cf({providerId:Z,explicitModels:X,modelsSourceUrl:Y,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let B=W.defaultModelId?.trim()&&V.includes(W.defaultModelId.trim())?W.defaultModelId.trim():V[0],H=W.capabilities?.length?[...new Set(W.capabilities)]:void 0,G=vf(W.headers);$.saveProviderSettings({provider:Z,apiKey:J||void 0,baseUrl:Q,headers:G,timeout:W.timeoutMs,model:B,protocol:W.protocol,client:W.client},{setLastUsed:!1});let K=Y8($),F=await r6(K);return F.providers[Z]={provider:{name:j,baseUrl:Q,defaultModelId:B,protocol:W.protocol,client:W.client,capabilities:H,modelsSourceUrl:Y},models:bX(V,H)},await sQ(K,F),MW(Z,F.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function Z7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=Y8($),J=await r6(Q),j=J.providers[Z];if(!j){let O=$.getProviderSettings(Z);if(!O)throw Error(`provider "${Z}" does not exist`);let T=W.modelsSourceUrl?.trim(),L=SX(W.models)[0]??O.model?.trim();if(!L&&!T)throw Error(`provider "${Z}" cannot be updated because no model is configured`);j={provider:{name:W.name?.trim()||gf(Z),baseUrl:W.baseUrl?.trim()??O.baseUrl?.trim()??"",defaultModelId:L,protocol:O.protocol,client:O.client,capabilities:O.capabilities},models:L?bX([L],O.capabilities):{}}}if(!j.provider)throw Error(`provider "${Z}" cannot be updated because it is a model overlay (no provider metadata)`);let X=W.name?.trim()??j.provider.name.trim();if(!X)throw Error("name is required");let Y=W.baseUrl?.trim()??j.provider.baseUrl.trim();if(!Y)throw Error("baseUrl is required");let V=W.capabilities===void 0?j.provider.capabilities:W.capabilities===null?void 0:[...new Set(W.capabilities)],B=W.protocol===void 0?j.provider.protocol:W.protocol??void 0,H=W.client===void 0?j.provider.client:W.client??void 0,G=SX(W.models),K=W.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:W.modelsSourceUrl?.trim()||void 0,F=W.models!==void 0||W.modelsSourceUrl!==void 0&&!!K,A=Object.keys(j.models??{}).map((O)=>O.trim()).filter(Boolean),f=await cf({providerId:Z,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(f.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let U=W.defaultModelId===void 0?j.provider.defaultModelId?.trim():W.defaultModelId?.trim(),_=U&&f.includes(U)?U:f[0],M={...$.getProviderSettings(Z)??{},provider:Z,baseUrl:Y,model:_};if(B)M.protocol=B;else delete M.protocol;if(H)M.client=H;else delete M.client;if(W.apiKey!==void 0){let O=W.apiKey?.trim()??"";if(O)M.apiKey=O;else delete M.apiKey}if(W.headers!==void 0){let O=vf(W.headers);if(O)M.headers=O;else delete M.headers}if(W.timeoutMs!==void 0)if(typeof W.timeoutMs==="number")M.timeout=W.timeoutMs;else delete M.timeout;return $.saveProviderSettings(M,{setLastUsed:!1}),J.providers[Z]={provider:{name:X,baseUrl:Y,defaultModelId:_,protocol:B,client:H,capabilities:V,modelsSourceUrl:K},models:bX(f,V)},await sQ(Q,J),MW(Z,J.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:f.length}}async function Q7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=Y8($),J=await r6(Q);if(!J.providers[Z])throw Error(`provider "${Z}" does not exist`);return delete J.providers[Z],await sQ(Q,J),h0.unregisterProvider(Z),uf($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q}}function hX($,W,Z={}){let Q=W.trim();if(!Q)throw Error("providerId is required");let J=$.read().providers[Q]?.settings;return $.saveProviderSettings({...J??{},provider:Q},{setLastUsed:!1,tokenSource:Z.tokenSource}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function kX($,W={}){let Z=$.read(),Q=h0.getProviderIds(),J=await Promise.all(Q.map(async(X)=>{let[Y,V]=await Promise.all([h0.getProvider(X),h0.getModelsForProvider(X)]),B=mf(V),H=Z.providers[X]?.settings,G=$.getProviderSettings(X),K=Y?.name??gf(X),F=lI(Y?.capabilities,G?.capabilities),A=iI(Y?.metadata)??nI(Y);return{provider:{id:X,name:K,models:B.length,color:cI(X),letter:vI(K),enabled:Boolean(H),apiKey:G?gI(G):void 0,oauthAccessTokenPresent:G?mI(G):void 0,baseUrl:G?.baseUrl??Y?.baseUrl,defaultModelId:Y?.defaultModelId,protocol:G?.protocol??Y?.protocol,client:G?.client??Y?.client,capabilities:F,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:A,configValues:sI(A,G,Y),modelList:B},rank:pI(Y?.metadata)}}));J.sort((X,Y)=>{if(X.rank!==Y.rank)return X.rank-Y.rank;return X.provider.name.localeCompare(Y.provider.name)||X.provider.id.localeCompare(Y.provider.id)});let j=J.map((X)=>X.provider);if(W.isClinePassEnabled!==!0)j=j.filter((X)=>X.id!==xf);return{providers:j,settingsPath:$.getFilePath()}}async function IX($,W){let Z=$.trim(),Q=await uI(Z,W),J=mf(Q);return{providerId:Z,models:J}}function W7($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function df($,W){if(!W7(W))return W7($)?{...$}:void 0;let Z=W7($)?{...$}:{};for(let[Q,J]of Object.entries(W)){if(J==null||J===""){delete Z[Q];continue}if(W7(J)){let j=df(Z[Q],J);if(j&&Object.keys(j).length>0)Z[Q]=j;else delete Z[Q];continue}Z[Q]=J}return Object.keys(Z).length>0?Z:void 0}function xX($,W){let Z=W.providerId.trim();if(W.enabled===!1){let j=$.read();if(delete j.providers[Z],j.lastUsedProvider===Z)delete j.lastUsedProvider;return $.write(j),{providerId:Z,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Z)??{},provider:Z};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(W,j)&&typeof W[j]==="string")if(W[j].trim().length===0)delete J[j];else J[j]=W[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(W,j))J[j]=W[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(W,j)&&W[j]!=null){let X=df(J[j],W[j]);if(X)J[j]=X;else delete J[j]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Z,enabled:!0,settingsPath:$.getFilePath()}}async function gX($,W){let Z=W.trim(),Q=$.getProviderSettings(Z),j=h0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z]?.provider,X=Q?.baseUrl?.trim()||j?.baseUrl?.trim(),Y=LZ(X,j?.baseUrl,j?.modelsSourceUrl);if(!Q||!j||!X||!Y)return{providerId:Z,refreshed:!1};let V=await Z7($,{providerId:Z,name:j.name,baseUrl:X,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:Y,protocol:Q.protocol??j.protocol??null,client:Q.client??j.client??null,capabilities:Q.capabilities??null});return{providerId:Z,refreshed:!0,modelsCount:V.modelsCount}}function mX($){let W=$.trim().toLowerCase(),Z=H0(W);if(Z)return Z.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function vX($,W,Z,Q){let J=H0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let j=A6({onPrompt:async(X)=>X.defaultValue??"",openUrl:Z,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return J.login({settings:W,callbacks:j,telemetry:Q})}function cX($,W,Z,Q,J){return K2({manager:$,providerId:W,settings:Z,credentials:Q,setLastUsed:J?.setLastUsed})}async function uX($,W,Z,Q){let J=A6({onPrompt:async(j)=>j.defaultValue??"",openUrl:Z,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return E4($,W,{callbacks:J,telemetry:Q})}function dX($){let W=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return W&&W.length>0?W:void 0}var pf={};w(pf,{getProviderConfigFields:()=>lX});import*as J7 from"@cline/llms";var tI=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],eI={"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 $x($,W){let Z={};for(let Q of tI){let J=$[Q],j=W[Q];if(J||j)Z[Q]={...J,...j}}return Z}function Wx($){let W=eI[$.providerId];if(!W)return $;return{...$,description:W.description??$.description,fields:W.mode==="replace"?W.fields:$x($.fields,W.fields)}}var Zx=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Qx($,W){if(!W?.provider.baseUrl)return!1;if(W.provider.source!=="system")return!0;return Zx.has($)}function lX($){let W=J7.normalizeProviderId($);if(G2(W))return{providerId:W,authMethod:"oauth",fields:{}};let Z=J7.MODEL_COLLECTIONS_BY_PROVIDER_ID[W];if(Z?.provider.capabilities?.includes("local-auth"))return{providerId:W,authMethod:"local",fields:{}};let Q=Z?.provider.baseUrl,J={apiKey:{}};if(Qx(W,Z))J.baseUrl={defaultValue:Q};return Wx({providerId:W,authMethod:"api-key",fields:J})}var of={};w(of,{resolveLegacyClineAuth:()=>iX,migrateLegacyProviderSettings:()=>RW});import{existsSync as Jx,readFileSync as jx}from"node:fs";import{dirname as Xx,join as pX}from"node:path";import*as i6 from"@cline/llms";import{resolveClineDataDir as Yx}from"@cline/shared/storage";var j7="openai",af=i6.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,rf=128000;function iX($){let W=$?.trim();if(!W)return;try{let Z=JSON.parse(W);if(!Z)return;let Q=typeof Z.expiresAt==="number"&&Number.isFinite(Z.expiresAt)?Z.expiresAt<10000000000?Z.expiresAt*1000:Z.expiresAt:void 0;return{accessToken:Z.idToken,refreshToken:Z.refreshToken,expiresAt:Q,accountId:Z.userInfo?.id}}catch{return}}function b($){let W=$?.trim();return W?W:void 0}function Vx($){return $==="credentials"?"iam":$}function nf($){if(!Jx($))return;try{let W=jx($,"utf8"),Z=JSON.parse(W);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function Bx($){let W=$.dataDir??Yx(),Z=$.globalStatePath??pX(W,"globalState.json"),Q=$.secretsPath??pX(W,"secrets.json"),J=nf(Z),j=nf(Q);if(!J&&!j)return;return{globalState:J??{},secrets:j??{}}}function rX($){if($===j7)return af;return $}function Hx($,W,Z,Q){let J=Z==="plan"?"planMode":"actMode",j=W===Q?b(Z==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,Y={openrouter:`${J}OpenRouterModelId`,cline:`${J}ClineModelId`,openai:`${J}OpenAiModelId`,ollama:`${J}OllamaModelId`,lmstudio:`${J}LmStudioModelId`,litellm:`${J}LiteLlmModelId`,requesty:`${J}RequestyModelId`,together:`${J}TogetherModelId`,fireworks:`${J}FireworksModelId`,sapaicore:`${J}SapAiCoreModelId`,groq:`${J}GroqModelId`,baseten:`${J}BasetenModelId`,huggingface:`${J}HuggingFaceModelId`,"huawei-cloud-maas":`${J}HuaweiCloudMaasModelId`,oca:`${J}OcaModelId`,aihubmix:`${J}AihubmixModelId`,hicap:`${J}HicapModelId`,nousResearch:`${J}NousResearchModelId`,"vercel-ai-gateway":`${J}VercelAiGatewayModelId`}[W];return(Y?b(typeof $[Y]==="string"?$[Y]:void 0):void 0)??j}function Gx($,W,Z){let Q=Z==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...W==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...W==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(b).find(Boolean),j=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&X===void 0)return;return{...j?{effort:j}:{},...X!==void 0?{budgetTokens:X}:{}}}function Kx($){let W=$["openai-codex-oauth-credentials"];if(!W)return;try{let Z=JSON.parse(W),Q=b(Z.access_token),J=b(Z.refresh_token),j=b(Z.accountId);if(!Q&&!J&&!j)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...J?{refreshToken:J}:{},...j?{accountId:j}:{}}}}catch{return}}function Fx($){let W=i6.getGeneratedModelsForProvider($),Q=i6.getProviderCollectionSync($)?.provider.defaultModelId;if(Q&&W[Q])return Q;return Object.keys(W)[0]??void 0}function Ax($,W,Z,Q){let J=rX($),j=b(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),X=Hx(W,$,Q,j)??Fx(J),Y=Gx(W,J,Q),V=typeof W.requestTimeoutMs==="number"&&Number.isInteger(W.requestTimeoutMs)&&W.requestTimeoutMs>0?W.requestTimeoutMs:void 0,B={anthropic:Z.apiKey,cline:Z.clineApiKey,openai:Z.openAiApiKey,"openai-native":Z.openAiNativeApiKey,openrouter:Z.openRouterApiKey,bedrock:Z.awsBedrockApiKey,gemini:Z.geminiApiKey,ollama:Z.ollamaApiKey,deepseek:Z.deepSeekApiKey,requesty:Z.requestyApiKey,together:Z.togetherApiKey,fireworks:Z.fireworksApiKey,qwen:Z.qwenApiKey,doubao:Z.doubaoApiKey,mistral:Z.mistralApiKey,litellm:Z.liteLlmApiKey,asksage:Z.asksageApiKey,xai:Z.xaiApiKey,moonshot:Z.moonshotApiKey,zai:Z.zaiApiKey,huggingface:Z.huggingFaceApiKey,nebius:Z.nebiusApiKey,sambanova:Z.sambanovaApiKey,cerebras:Z.cerebrasApiKey,groq:Z.groqApiKey,"huawei-cloud-maas":Z.huaweiCloudMaasApiKey,baseten:Z.basetenApiKey,"vercel-ai-gateway":Z.vercelAiGatewayApiKey,dify:Z.difyApiKey,minimax:Z.minimaxApiKey,hicap:Z.hicapApiKey,aihubmix:Z.aihubmixApiKey,nousResearch:Z.nousResearchApiKey,oca:Z.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,Kx(Z));if($==="cline")try{let _=b(Z["cline:clineAccountId"]);if(_)H.auth={...H.auth??{},...iX(_)}}catch{}if($===j7&&W.openAiHeaders)H.headers=W.openAiHeaders;if($==="bedrock"){let _=Vx(W.awsAuthentication),D=_==="profile"||W.awsUseProfile===!0;H.aws={accessKey:b(Z.awsAccessKey),secretKey:b(Z.awsSecretKey),sessionToken:b(Z.awsSessionToken),region:b(W.awsRegion),authentication:_,profile:D?b(W.awsProfile):void 0,usePromptCache:W.awsBedrockUsePromptCache,useCrossRegionInference:W.awsUseCrossRegionInference,useGlobalInference:W.awsUseGlobalInference,endpoint:b(W.awsBedrockEndpoint),customModelBaseId:b(Q==="plan"?W.planModeAwsBedrockCustomModelBaseId:W.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:b(W.vertexProjectId),region:b(W.vertexRegion)};if($===j7&&(W.azureApiVersion||W.azureIdentity!==void 0))H.azure={apiVersion:b(W.azureApiVersion),useIdentity:W.azureIdentity};if($==="sapaicore"){let _=W.sapAiCoreUseOrchestrationMode??!0;H.sap={clientId:b(Z.sapAiCoreClientId),clientSecret:b(Z.sapAiCoreClientSecret),tokenUrl:b(W.sapAiCoreTokenUrl),resourceGroup:b(W.sapAiResourceGroup),deploymentId:_?void 0:b(Q==="plan"?W.planModeSapAiCoreDeploymentId:W.actModeSapAiCoreDeploymentId),useOrchestrationMode:_}}if($==="oca"){H.oca={mode:W.ocaMode};let _=b(Z.ocaRefreshToken);if(_)H.auth={...H.auth??{},refreshToken:_}}if($==="qwen")H.apiLine=W.qwenApiLine;if($==="moonshot")H.apiLine=W.moonshotApiLine;if($==="zai")H.apiLine=W.zaiApiLine;if($==="minimax")H.apiLine=W.minimaxApiLine;let G={anthropic:W.anthropicBaseUrl,openai:W.openAiBaseUrl,ollama:W.ollamaBaseUrl,lmstudio:W.lmStudioBaseUrl,litellm:W.liteLlmBaseUrl,gemini:W.geminiBaseUrl,requesty:W.requestyBaseUrl,asksage:W.asksageApiUrl,dify:W.difyBaseUrl,oca:W.ocaBaseUrl,aihubmix:W.aihubmixBaseUrl,sapaicore:W.sapAiCoreBaseUrl},K=b(B[$]),F=b(G[$]),A={provider:J,...K?{apiKey:K}:{},...X?{model:X}:{},...F?{baseUrl:F}:{},...Y?{reasoning:Y}:{},...V?{timeout:V}:{},...H},f=G6.safeParse(A);if(!f.success)return;return Object.keys(A).filter((_)=>_!=="provider").length>0?f.data:void 0}function Ux($,W){if($!==af)return;if(!W.baseUrl||!W.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:W.baseUrl,defaultModelId:W.model},models:{[W.model]:{id:W.model,name:W.model,contextWindow:rf,maxInputTokens:rf,capabilities:["streaming","tools","images"]}}}}function fx($,W){let Z=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let j=b(J);if(j)Z.add(j)}if(b(W.apiKey))Z.add("anthropic");if(b(W.openRouterApiKey))Z.add("openrouter");if(b(W.openAiApiKey))Z.add(j7);if(b(W.openAiNativeApiKey))Z.add("openai-native");if(b(W["openai-codex-oauth-credentials"]))Z.add("openai-codex");if(b(W.geminiApiKey))Z.add("gemini");if(b(W.ollamaApiKey))Z.add("ollama");if(b(W.awsAccessKey)||b(W.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||b($.awsProfile))Z.add("bedrock");if(b($.vertexProjectId)||b($.vertexRegion))Z.add("vertex");if(b(W.clineApiKey))Z.add("cline");let Q=iX(b(W["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)Z.add("cline");if(b(W.ocaApiKey))Z.add("oca");if(b(W.sapAiCoreClientId)||b(W.sapAiCoreClientSecret)||b($.sapAiCoreTokenUrl)||b($.sapAiCoreBaseUrl)||b($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Z.add("sapaicore");return Z}function RW($){let W=$.providerSettingsManager.read(),Z=Bx($);if(!Z)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let{globalState:Q,secrets:J}=Z,j=Q.mode==="plan"?"plan":"act",X=fx(Q,J),Y=m$();Y.providers={...W.providers},Y.lastUsedProvider=W.lastUsedProvider;let V=new Date().toISOString(),B=0,H=pX(Xx($.providerSettingsManager.getFilePath()),"models.json"),G=PX(H),K=0;for(let f of X){let U=rX(f);if(Y.providers[U])continue;let _=Ax(f,Q,J,j);if(!_)continue;Y.providers[U]={settings:_,updatedAt:V,tokenSource:"migration"},B+=1;let D=Ux(U,_);if(D&&!G.providers[U])G.providers[U]=D,K+=1}if(B===0&&K===0)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let F=b(j==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),A=F?rX(F):void 0;if(Y.lastUsedProvider=W.lastUsedProvider??(A&&Y.providers[A]?A:Object.keys(Y.providers)[0]),$.providerSettingsManager.write(Y),K>0)wf(H,G);return{migrated:B>0||K>0,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider}}qQ();M0();H9();var sf={};w(sf,{SessionVersioningService:()=>a$,SessionVersioningError:()=>c0});class c0 extends Error{code;constructor($,W){super(W);this.code=$;this.name="SessionVersioningError"}}function Dx($){let W=$.sessionId.trim();if(!W)throw new c0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new c0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new c0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new c0("invalid_restore","checkpointRunCount must be a positive integer");return W}class a${async restoreCheckpoint($){let W=$.restore?.messages!==!1,Z=$.restore?.workspace!==!1,Q=Dx({sessionId:$.sessionId,restoreMessages:W,restoreWorkspace:Z,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(Q);if(!J)throw new c0("session_not_found",`Session ${Q} not found`);let j=W?await $.readMessages(Q):void 0;if(W&&j?.length===0)throw new c0("session_messages_not_found",`No messages found for session ${Q}`);let X=aj({session:J,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:W});if(Z)await($.applyWorkspaceCheckpoint??oj)(X.cwd,X.checkpoint);let Y=E1({session:J,messages:j});if(!W)return{checkpoint:X.checkpoint,sourceSnapshot:Y};let V=ij(J,$.checkpointRunCount),B=$.restore?.omitCheckpointMessageFromSession?nj(j??[],$.checkpointRunCount):X.messages??[],H={sourceSession:J,sourceMessages:j,sourceSnapshot:Y,plan:X,restoredCheckpointMetadata:V,initialMessages:B,restoreMessages:W,restoreWorkspace:Z,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new c0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??yK)(X.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:X.messages,checkpoint:X.checkpoint,sourceSnapshot:Y,...A?{restoredSnapshot:E1({session:A,messages:B})}:{}}}}var tf={};w(tf,{FileTeamPersistenceStore:()=>X7});import{appendFileSync as _x,existsSync as nX,mkdirSync as Lx,readFileSync as Tx,renameSync as Ox,unlinkSync as zx,writeFileSync as qx}from"node:fs";import{join as aX}from"node:path";import{resolveTeamDataDir as Mx}from"@cline/shared/storage";function Rx($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class X7{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let W=Rx($.teamName),Z=$.baseDir?.trim()||Mx();this.dirPath=aX(Z,W),this.statePath=aX(this.dirPath,"state.json"),this.taskHistoryPath=aX(this.dirPath,"task-history.jsonl")}loadState(){if(!nX(this.statePath))return;try{let $=Tx(this.statePath,"utf8"),W=JSON.parse($);if(W.version!==1||!W.teamState)return;for(let Z of W.teammates??[])this.teammateSpecs.set(Z.agentId,Z);return DU(W.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 W={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Z=`${this.statePath}.tmp`;qx(Z,`${JSON.stringify(W,null,2)}
738
- `,"utf8"),Ox(Z,this.statePath)}appendTaskHistory($){let W={};switch($.type){case"team_task_updated":W=$.task;break;case"team_message":W={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":W={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":W={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":W={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":W={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),_x(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:W})}
739
- `,"utf8")}ensureDir(){if(!nX(this.dirPath))Lx(this.dirPath,{recursive:!0})}hasPersistableState($){let W=$.exportState();if(this.teammateSpecs.size>0)return!0;if(W.members.some((Z)=>Z.role==="teammate"))return!0;return W.tasks.length>0||W.mailbox.length>0||W.missionLog.length>0}clearPersistedState(){if(nX(this.statePath))zx(this.statePath)}}var ef={};w(ef,{ChatViewStateSchema:()=>oX,ChatSummarySchema:()=>G7,ChatSessionStatusSchema:()=>V7,ChatSessionConfigSchema:()=>Y7,ChatMessageSchema:()=>H7,ChatMessageRoleSchema:()=>B7});import{z as I}from"zod";var Y7=I.object({workspaceRoot:I.string().min(1),cwd:I.string().optional(),provider:I.string().min(1),model:I.string().min(1),mode:I.enum(["act","plan"]).default("act"),apiKey:I.string(),systemPrompt:I.string().optional(),rules:I.string().optional(),maxIterations:I.number().int().positive().optional(),enableTools:I.boolean(),enableSpawn:I.boolean().optional(),enableTeams:I.boolean().optional(),autoApproveTools:I.boolean().optional(),missionStepInterval:I.number().int().positive().optional(),missionTimeIntervalMs:I.number().int().positive().optional()}),V7=I.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),B7=I.enum(["user","assistant","tool","system","status","error"]),H7=I.object({id:I.string().min(1),sessionId:I.string().nullable(),role:B7,content:I.string(),createdAt:I.number().int().nonnegative(),meta:I.object({stream:I.enum(["stdout","stderr"]).optional(),toolName:I.string().optional(),iteration:I.number().int().nonnegative().optional(),agentId:I.string().optional(),conversationId:I.string().optional(),hookEventName:I.string().optional(),inputTokens:I.number().int().nonnegative().optional(),outputTokens:I.number().int().nonnegative().optional(),checkpoint:I.object({ref:I.string(),createdAt:I.number().int().nonnegative(),runCount:I.number().int().positive(),kind:I.enum(["stash","commit"]).optional()}).optional()}).optional()}),G7=I.object({toolCalls:I.number().int().nonnegative(),tokensIn:I.number().int().nonnegative(),tokensOut:I.number().int().nonnegative()}),oX=I.object({sessionId:I.string().nullable(),status:V7,config:Y7,messages:I.array(H7),rawTranscript:I.string(),error:I.string().nullable(),summary:G7});var $D={};w($D,{CORE_BUILD_VERSION:()=>sX});var sX=q8;import{Agent as zg,createAgentRuntime as qg}from"@cline/agents";var WD={};w(WD,{fetchClineRecommendedModels:()=>eX,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>K7});import{getClineEnvironmentConfig as Nx}from"@cline/shared";var Ex=5000,K7={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"]}],clinePass:[]};function wx($){return{recommended:$.recommended.map((W)=>({...W,tags:[...W.tags]})),free:$.free.map((W)=>({...W,tags:[...W.tags]})),clinePass:$.clinePass.map((W)=>({...W,tags:[...W.tags]}))}}function tX($){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||W.id.length===0)return null;return{id:W.id,name:typeof W.name==="string"&&W.name.length>0?W.name:W.id,description:typeof W.description==="string"?W.description:"",tags:Array.isArray(W.tags)?W.tags.filter((Z)=>typeof Z==="string"):[]}}function Cx($){if(!$||typeof $!=="object")return null;let W=$,Z=Array.isArray(W.recommended)?W.recommended:[],Q=Array.isArray(W.free)?W.free:[],J=Array.isArray(W.clinePass)?W.clinePass:[],j=Z.map(tX).filter((V)=>V!==null),X=Q.map(tX).filter((V)=>V!==null),Y=J.map(tX).filter((V)=>V!==null);if(j.length===0&&X.length===0&&Y.length===0)return null;return{recommended:j,free:X,clinePass:Y}}function Px($){let W=$.baseUrl?.trim();if(W)return W;let Z=Nx().apiBaseUrl;try{return($.providerSettingsManager??new h1).getProviderSettings("cline")?.baseUrl?.trim()||Z}catch{return Z}}async function Sx($,W,Z){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await $(W,{signal:Q.signal})}finally{clearTimeout(J)}}async function eX($={}){try{let W=Px($),Z=$.fetchImpl??fetch,Q=await Sx(Z,`${W}/api/v1/ai/cline/recommended-models`,$.timeoutMs??Ex);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let J=await Q.json(),j=Cx(J);if(j)return j}catch{}return wx(K7)}var ZD={};w(ZD,{loadLlmsConfigFromFile:()=>WY,defineLlmsConfig:()=>$Y});import{readFile as bx}from"node:fs/promises";import yx from"node:path";function $Y($){return $}async function WY($){let W=yx.resolve($),Z=await bx(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(J){let j=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${W}": ${j}`)}return hx(Q,W)}function hx($,W){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${W}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${W}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${W}": "providers" cannot be empty.`);return $}var VD={};w(VD,{createLlmsSdk:()=>QY,DefaultLlmsSdk:()=>NW});import{BUILT_IN_PROVIDER_IDS as jD,createHandler as xx,createHandlerAsync as gx,getProviderCollection as mx,hasProvider as XD,registerAsyncHandler as vx,registerHandler as cx,registerModel as ux,registerProvider as YD}from"@cline/llms";function QD($){return $?{...$}:{}}function kx($,W){if($)return $;if(!W)return;let Z=globalThis.process;if(!Z?.env)return;return Z.env[W]}function Ix($,W){if(!W.length)throw Error(`Provider "${$}" must include at least one model.`)}function JD($){let W=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:W,defaultModel:$.collection.provider.defaultModelId,modelCount:W.length}}class ZY{providers=new Map;register($){Ix($.id,$.models);let W=$.defaultModel??$.models[0];if(!W)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(W))throw Error(`Default model "${W}" is not included in configured models for "${$.id}".`);let Z=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Z?.models??[],...$.models]),defaultModel:W,defaults:{...Z?.defaults??{},...QD($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:kx($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...QD($.settings)}})}registerModel($,W){let Z=this.providers.get($);if(!Z){this.providers.set($,{id:$,models:new Set([W]),defaultModel:W,defaults:{}});return}Z.models.add(W)}createHandlerConfig($){let W=this.require($.providerId),Z=$.modelId??W.defaultModel;if(!W.models.has(Z))throw Error(`Model "${Z}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Z,...W.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($,W){return this.providers.get($)?.models.has(W)??!1}require($){let W=this.providers.get($);if(!W)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return W}}class NW{configuredProviders=new ZY;constructor($){this.applyConfig($)}createHandler($){return xx(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return gx(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(YD($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)cx($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)vx($.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 W=$.exposeModels??Object.keys($.models),Z=$.defaultModel??W[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);YD({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Z,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:W,defaultModel:Z,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){ux($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...jD]}async getBuiltInProviders(){return(await Promise.all(jD.map((W)=>mx(W)))).filter((W)=>W!==void 0).map((W)=>JD({collection:W}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,W){return this.configuredProviders.hasModel($,W)}applyConfig($){for(let W of $.providers)this.configuredProviders.registerSelectionConfig(W);for(let W of $.models??[])this.registerModel(W);for(let W of $.customProviders??[])this.registerProvider(W);for(let W of this.configuredProviders.list()){let Z=XD(W.id),Q=this.configuredProviders.createHandlerConfig({providerId:W.id,modelId:W.defaultModel}).routingProviderId,J=typeof Q==="string"&&XD(Q);if(!Z&&!J)throw Error(`Provider "${W.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function QY($){return new NW($)}v7();async function dx(){return Promise.resolve().then(() => (qQ(),mU))}function Pg(){return new Date().toISOString()}var Sg="cline",bg="cline-pass";function yg($){if(fD($)!=="providers.json")return;let W=XY($);if(fD(W)!=="settings")return;return XY(W)}class h1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Cg(),this.dataDir=$.dataDir??yg(this.filePath),this.dataDir||!$.filePath)RW({providerSettingsManager:this,dataDir:this.dataDir});if(kf(this),tQ(this.read()),jY(this.filePath))try{UD(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!jY(this.filePath))return m$();try{let $=Rg(this.filePath,"utf8"),W=JSON.parse($),Z=K6.safeParse(W);if(Z.success){tQ(Z.data);let Q=Z.data.providers.cline?.settings?.auth;return Q0(`providers.read providers=[${Object.keys(Z.data.providers).join(",")}] lastUsed=${Z.data.lastUsedProvider??"none"} clineAuthPresent=${!!Q?.accessToken} clineAccessTokenHash=${N0(Q?.accessToken)} clineRefreshTokenHash=${N0(Q?.refreshToken)}`),Z.data}}catch{}return m$()}write($){let W=K6.parse($),Z=XY(this.filePath);if(!jY(Z))Mg(Z,{recursive:!0,mode:448});let Q=`${this.filePath}.${process.pid}.tmp`;try{wg(Q,`${JSON.stringify(W,null,2)}
740
- `,{encoding:"utf8",mode:384}),Ng(Q,this.filePath)}catch(J){throw Eg(Q,{force:!0}),J}try{UD(this.filePath,384)}catch{}tQ(W)}saveProviderSettings($,W={}){let Z=G6.parse($),Q=this.read(),J=Z.provider,j=W.setLastUsed!==!1,X=Q.providers[J],Y=W.tokenSource??X?.tokenSource??"manual",V={...Q,providers:{...Q.providers,[J]:{settings:Z,updatedAt:Pg(),tokenSource:Y}},lastUsedProvider:j?J:Q.lastUsedProvider};this.write(V);let B=Q.providers.cline?.settings?.auth,H=Z.provider==="cline"?Z.auth:V.providers.cline?.settings?.auth,G=!!B?.accessToken&&!H?.accessToken;return Q0(`providers.save providerId=${J} tokenSource=${Y} clineAuthWasPresent=${!!B?.accessToken} clineAuthIsPresent=${!!H?.accessToken} authDropped=${G}`),V}resolveProviderSettings($,W){let Z=$.providers[W]?.settings,J=H0(W)?.storageProviderId;if(!J||J===W)return Z;let j=$.providers[J]?.settings;if(!j)return Z;return G6.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Z??{},provider:W})}getProviderSettings($){let W=this.read();return this.resolveProviderSettings(W,$)}resolveLastUsedProviderId($,W){let Z=$.lastUsedProvider;if(Z===bg&&W.isClinePassEnabled===!1)return Sg;return Z}getLastUsedProviderSettings($={}){let W=this.read(),Z=this.resolveLastUsedProviderId(W,$);if(!Z)return;return this.resolveProviderSettings(W,Z)}getProviderConfig($,W){let Z=this.getProviderSettings($);if(!Z)return;return s0(Z,W)}getLastUsedProviderConfig($={}){let W=this.getLastUsedProviderSettings($);if(!W)return;return s0(W,$)}async refreshCatalog(){try{await B6({})}catch{}}}M0();L8();function hg($,W){let Z=$?.expiresAt,Q=W?.expiresAt;return $?.accessToken===W?.accessToken&&$?.refreshToken===W?.refreshToken&&$?.accountId===W?.accountId&&Z===Q}class f7 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 YY{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new h1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let W=H0($.providerId);if(!W)return null;return this.resolveWithSingleFlight(W.providerId,W.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,W,Z=!1){let Q=this.refreshInFlight.get(W);if(Q)return Q;let J=this.resolveProviderApiKeyInternal($,W,Z).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(W)});return this.refreshInFlight.set(W,J),J}async resolveProviderApiKeyInternal($,W,Z){let Q=H0($);if(!Q)return null;let J=this.providerSettingsManager.getProviderSettings(W);if(!J)return Q0(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_settings`),null;let j=w4($,J);if(!j)return Q0(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_credentials`),null;Q0(`oauth.resolve.start providerId=${$} storageProviderId=${W} forceRefresh=${Z} accessTokenHash=${N0(j.access)} refreshTokenHash=${N0(j.refresh)}`);let X=await Q.refresh({settings:J,credentials:j,forceRefresh:Z,telemetry:this.telemetry});if(!X)throw Q0(`oauth.resolve providerId=${$} outcome=refresh_returned_null`),new f7($);let Y=K2({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:X,setLastUsed:!1,save:!1}),V=!hg(J.auth,Y.auth);if(V)Q0(`oauth.resolve.refreshed providerId=${$} newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} savingToDisk=true`),this.providerSettingsManager.saveProviderSettings(Y,{setLastUsed:!1,tokenSource:"oauth"});else Q0(`oauth.resolve providerId=${$} outcome=not_refreshed`);return{apiKey:Q.getApiKey(Y)??X.access,accountId:X.accountId,refreshed:V}}}import{normalizeUserInput as kg}from"@cline/shared";import{nanoid as Ig}from"nanoid";class DD{list($){return $?Q1($):[]}update($,W){if(!$)return{sessionId:W.sessionId,prompts:[],updated:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((V)=>V.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let J=$.pendingPrompts[Q];if(!J)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let j=W.prompt===void 0?J.prompt:kg(W.prompt).trim();if(!j)throw Error("prompt cannot be empty");let X=W.delivery??J.delivery,Y={...J,prompt:j,mode:W.mode??J.mode,delivery:X};return $.pendingPrompts.splice(Q,1),xg($,Y,Q,J.delivery),{sessionId:W.sessionId,prompts:Q1($),prompt:D7(Y),updated:!0}}delete($,W){if(!$)return{sessionId:W.sessionId,prompts:[],removed:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((j)=>j.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),removed:!1};let[J]=$.pendingPrompts.splice(Q,1);return{sessionId:W.sessionId,prompts:Q1($),prompt:J?D7(J):void 0,removed:!0}}enqueue($,W){let{prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X}=W,Y=$.pendingPrompts.findIndex((V)=>V.prompt===Z);if(Y>=0){let[V]=$.pendingPrompts.splice(Y,1),B={...V,prompt:Z,mode:Q??V.mode,userImages:j??V.userImages,userFiles:X??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...B,delivery:"steer"});else $.pendingPrompts.push(B)}else{let V={id:`pending_${Date.now()}_${Ig(5)}`,prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return Q1($)}consumeSteer($){let W=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(W<0)return{prompts:Q1($)};let[Z]=$.pendingPrompts.splice(W,1);return{entry:Z,prompts:Q1($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:Q1($)}}requeueFront($,W){return $.pendingPrompts.unshift(W),Q1($)}clear($){return $.pendingPrompts.length=0,[]}}class VY{deps;service=new DD;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Z=this.service.update(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}delete($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Z=this.service.delete(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}enqueue($,W){let Z=this.deps.getSession($);if(!Z||Z.aborting)return;this.service.enqueue(Z,W),this.emitPrompts(Z),this.scheduleDrain($,Z)}consumeSteer($){let W=this.deps.getSession($);if(!W)return;let{entry:Z}=this.service.consumeSteer(W);if(!Z)return;return this.emitPrompts(W),this.emitSubmitted(W,Z),Z}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:Q1($)}})}scheduleDrain($,W){if(W.pendingPrompts.length===0||W.aborting||W.drainingPendingPrompts||!W.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let W=this.deps.getSession($);if(!W)return;if(W.aborting||W.drainingPendingPrompts)return;if(!W.agent.canStartRun())return;let{entry:Z}=this.service.shiftNext(W);if(!Z)return;this.emitPrompts(W),this.emitSubmitted(W,Z),W.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:Z.prompt,...Z.mode?{mode:Z.mode}:{},userImages:Z.userImages,userFiles:Z.userFiles})}catch{Q=!1,this.service.requeueFront(W,Z),this.emitPrompts(W)}finally{if(W.drainingPendingPrompts=!1,Q&&W.pendingPrompts.length>0&&W.status!=="failed"&&W.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,W){let Z=D7(W);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}})}}function D7($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function Q1($){return $.pendingPrompts.map(D7)}function xg($,W,Z,Q){if(W.delivery==="steer")$.pendingPrompts.unshift(W);else if(Q==="steer")$.pendingPrompts.push(W);else $.pendingPrompts.splice(Z,0,W)}M0();class HY{deps;constructor($){this.deps=$}dispatchAgentEvent($,W,Z){let Q=this.deps.getSession($),J={sessionId:$,config:W,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=UJ(Z),X=!!Q&&(!j.agentId||j.agentId===BY(Q.agent));fJ(J,Z,X?{isPrimaryAgentEvent:!0,agentId:BY(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,W){let Z=this.deps.getSession($);if(Z){if(bj(Z,W),W.type==="agent_event"){let Q={sessionId:$,config:Z.config,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};fJ(Q,W.event,{agentId:W.agentId,teamRole:"teammate",teamAgentId:W.agentId,isPrimaryAgentEvent:!1})}if(W.type==="teammate_spawned"){let Q=$$({agentId:W.teammate.runtimeAgentId??W.agentId,conversationId:W.teammate.conversationId,parentAgentId:W.teammate.parentAgentId,createdByAgentId:BY(Z.agent),teamId:Z.runtime.teamRuntime?.getTeamId(),teamName:Z.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:W.agentId});if(Q)L$(Z.config.telemetry,{ulid:$,modelId:W.teammate.modelId??Z.config.modelId,provider:Z.config.providerId,...Q})}}if(await yj($,W,this.deps.invokeBackendOptional),Z)hj(Z,$,W,this.deps.emit)}async handlePluginEvent($,W,Z){if(W.name==="plugin_log"){this.handlePluginLog($,W.payload);return}if(W.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Z;if(!V)return;let B=W.payload&&typeof W.payload==="object"?W.payload:void 0;if(!B)return;await V.ingestEvent(B);return}if(W.name!=="steer_message"&&W.name!=="queue_message"&&W.name!=="pending_prompt")return;let Q=W.payload&&typeof W.payload==="object"?W.payload:void 0,J=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,j=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!j)return;let X=W.name==="steer_message"?"steer":W.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:j,delivery:X})}handlePluginLog($,W,Z){let Q=this.deps.getSession($),J=Z??Q?.config.extensionContext?.logger??Q?.config.logger;if(!J||!W||typeof W!=="object")return;let j=W,X=typeof j.message==="string"?j.message:"";if(!X)return;let Y=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(Y.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)Y.pluginName=j.pluginName;if(j.level==="debug"){J.debug(X,Y);return}if(j.level==="error"){if(J.error)J.error(X,Y);else J.log(X,{...Y,severity:"error"});return}J.log(X,Y)}}function BY($){return $.getAgentId()}function GY($){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:W$($.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 KY($,W){let Z=$[W];return typeof Z==="function"?Z:null}async function _D($,W,...Z){let Q=KY($,W);if(!Q)throw Error(`session service method not available: ${W}`);return Promise.resolve(Q.apply($,Z))}async function LD($,W,...Z){let Q=KY($,W);if(!Q)return;await Promise.resolve(Q.apply($,Z))}async function TD($,W,...Z){let Q=KY($,W);if(!Q)return;return await Promise.resolve(Q.apply($,Z))}X1();M0();function FY($,W,Z){return{onSubAgentEvent:(Q)=>$.onAgentEvent(Z,W,Q),onSubAgentStart:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:Z});let j=$$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)L$(W.telemetry,{ulid:Z,modelId:W.modelId,provider:W.providerId,...j});Y4(W.telemetry,{event:"started",ulid:Z,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Z,Q)},onSubAgentEnd:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime,j=$.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
741
- `).length:0;Y4(W.telemetry,{event:"ended",ulid:Z,durationMs:X,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...$$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Z,Q)}}}function AY($,W,Z,Q){let J=FY($,W,Z);return b$({configProvider:{getRuntimeConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,maxIterations:W.maxIterations,hooks:W.hooks,extensions:W.extensions,logger:W.logger,telemetry:W.telemetry},getConnectionConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let X=W.enableTools?b2({cwd:W.cwd,...a0[t1({mode:W.mode})],executors:Q}):[];if(W.enableSpawnAgent)X.push(AY($,W,Z,Q));return c1(X)},...J})}import{readFile as gg,stat as mg}from"node:fs/promises";var vg=20480000;async function OD($){let W=await mg($);if(!W.isFile())throw Error("Path is not a file");if(W.size>vg)throw Error("File is too large to read into context.");let Z=await gg($,"utf8");if(Z.includes("\x00"))throw Error("Cannot read binary file into context.");return Z}var zD=5000;function SW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function ng($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=SW(W.inputTokens),Q=SW(W.outputTokens),J=SW(W.cacheReadTokens),j=SW(W.cacheWriteTokens),X=SW(W.totalCost);if(Z===void 0||Q===void 0||J===void 0||j===void 0||X===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:J,cacheWriteTokens:j,totalCost:X}}function ag($,W){return{inputTokens:Math.max($.inputTokens,W.inputTokens),outputTokens:Math.max($.outputTokens,W.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,W.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,W.cacheWriteTokens),totalCost:Math.max($.totalCost,W.totalCost)}}function qD($,W){if(!W)return!1;if($.source_message_count!==W.source_message_count)return $.source_message_count<W.source_message_count;return Date.parse($.updated_at)<Date.parse(W.updated_at)}class b1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new $W;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new a$;constructor($){let W=ug();if(W)ig(W);let Z=I0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new c6,this.createAgentInstance=$.createAgent??((Q)=>new C$(Q)),this.defaultCapabilities=C0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new h1,this.oauthTokenManager=$.oauthTokenManager??new YY({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Z),this.defaultFetch=$.fetch,this.pendingPromptsController=new VY({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new HY({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,J,j)=>{this.invoke("persistSessionMessages",Q,J,j)},enqueuePendingPrompt:(Q,J)=>this.pendingPromptsController.enqueue(Q,J),invokeBackendOptional:(Q,...J)=>this.invokeOptional(Q,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let W=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!W?.apiKey)return $;return{...$,config:{...$.config,apiKey:W.apiKey}}}async startSession($){let W=$.source??F0.CLI,Z=X0(),Q=$.config.sessionId?.trim()??"",J=Q||lg(),j=await this.applyInitialOAuthCredentials($),X=j.initialMessages??[],Y=X.length>0?t8(X):O0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let B=UY(V,J),H=UY(B,`${J}.messages.json`),G=UY(B,`${J}.json`),K=W$($.config),F=g0.parse({version:1,session_id:J,source:W,pid:process.pid,started_at:Z,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:K,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}),A,f;if(Q.length>0&&X.length>0&&!j.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",J);if(k)F=k,A={manifestPath:G,messagesPath:k.messages_path||H,compactionPath:k.compaction_path,manifest:k},f=await this.invokeOptionalValue("readSessionCompactionState",J)}let _=await this.seedAggregateUsageFromArtifacts({initialUsage:Y,sessionDir:B,rootMessagesPath:A?.messagesPath??H,manifest:F});this.usageBySession.set(J,Y),this.aggregateUsageBySession.set(J,_);let D=C0(this.defaultCapabilities,$.capabilities),M=D?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,C,N={getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,$0,L0)=>this.eventBridge.dispatchAgentEvent(k,$0,L0),invokeBackendOptional:(k,...$0)=>this.invokeOptional(k,...$0)};C=await JF({input:j,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:D,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(J,k.payload,T);return}this.eventBridge.handlePluginEvent(J,k,L)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(J,k),C.config.onTeamEvent?.(k)},createSpawnTool:()=>AY(N,C.config,J,M),createSubAgentLifecycleCallbacks:(k)=>FY(N,k,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(J,()=>k)}});let p=gW(j.sessionMetadata??A?.manifest.metadata,C.gitState);if(!A)F.metadata=p;let x=await this.runtimeBuilder.build(C.runtimeBuilderInput),P=C.config,r=C.providerConfig;if(x.teamRuntime&&!P.teamName?.trim())P.teamName=x.teamRuntime.getTeamName();let d=[...x.tools,...P.extraTools??[]],k1=x.extensions??C.extensions,e$=j.initialCompactionState,F$,k0=x4(P),A0=e$??f,f1=k0&&A0?{...A0,conversation_id:A0.conversation_id?.trim()||J}:void 0,H8=k0?g4({compact:k0,getState:()=>F$?.compactionState,saveState:async(k)=>{let $0=F$;if(!$0)return;let L0={...k,conversation_id:$0.sessionId};try{if(!(await this.persistActiveSessionCompactionState($0,L0)).updated)P.logger?.debug?.("Skipped stale session compaction state",{sessionId:$0.sessionId,sourceMessageCount:L0.source_message_count})}catch(z0){P.logger?.error?.("Failed to persist session compaction state",{sessionId:$0.sessionId,error:z0}),o$(P.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:z0,context:{sessionId:$0.sessionId,providerId:P.providerId,modelId:P.modelId}})}}}):void 0,V0={sessionId:J,providerId:r.providerId,modelId:r.modelId,apiKey:r.apiKey,baseUrl:r.baseUrl,headers:r.headers,knownModels:r.knownModels,providerConfig:r,thinking:P.thinking,reasoningEffort:P.reasoningEffort??r.reasoningEffort,thinkingBudgetTokens:P.thinkingBudgetTokens,maxTokensPerTurn:P.maxTokensPerTurn,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:H8,tools:d,hooks:C.hooks,extensions:k1,hookErrorMode:P.hookErrorMode,initialMessages:C.effectiveInput.initialMessages,userFileContentLoader:OD,toolPolicies:C.toolPolicies,requestToolApproval:C.requestToolApproval?async(k)=>{let $0=C.requestToolApproval,L0=this.sessions.get(J);if(L0)await this.markTurnPending(L0);try{if(!$0)return{approved:!1,reason:"Tool approval callback is not configured."};return await $0(k)}finally{let z0=this.sessions.get(J);if(z0?.status==="pending")await this.markTurnRunning(z0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:x.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(J);return k?BW(k.prompt,k.mode??P.mode):void 0},logger:x.logger??P.logger,extensionContext:P.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(J,P,k)};V0.hooks={...V0.hooks,onEvent:async(k)=>{if(await C.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let $0=this.sessions.get(J);if(!$0)return;let L0=$0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,L0,P.systemPrompt)}catch(z0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:z0}),o$(P.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:z0,severity:"warn",handled:!0,context:{sessionId:J,providerId:P.providerId,modelId:P.modelId}})}}};let d0=this.createAgentInstance(V0);if(V0.onEvent)d0.subscribeEvents(V0.onEvent);x.registerLeadAgent?.(d0);let J1=$$({agentId:d0.getAgentId(),conversationId:d0.getConversationId(),teamId:x.teamRuntime?.getTeamId(),teamName:x.teamRuntime?.getTeamName(),teamRole:x.teamRuntime?"lead":void 0});if(XF(P,J,Q.length>0,K,J1),J1)L$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...J1});if(x.teamRuntime)$9(P.telemetry,{ulid:J,teamId:x.teamRuntime.getTeamId(),teamName:x.teamRuntime.getTeamName(),leadAgentId:d0.getAgentId(),restoredFromPersistence:x.teamRestoredFromPersistence===!0});let y={sessionId:J,config:P,sessionMetadata:p,...A?{artifacts:A}:{},source:W,startedAt:A?.manifest.started_at??Z,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Z,pendingPrompt:F.prompt,runtime:x,agent:d0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:X,compactionState:f1,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:C.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(F$=y,y.compactionState&&!this.isCompactionStateForSession(y.sessionId,y.compactionState,y))y.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:y.sessionId,conversationId:y.compactionState.conversation_id}),y.compactionState=void 0;if(this.sessions.set(J,y),A)await this.refreshActiveSessionGitMetadata(y,C.gitState);if(this.emitStatus(J,"running"),X.length>0&&!A){if(await this.ensureSessionPersisted(y),await this.invoke("persistSessionMessages",y.sessionId,X,y.config.systemPrompt),y.compactionState){if(!(await this.persistActiveSessionCompactionState(y,y.compactionState)).updated)y.compactionState=void 0}if(!j.prompt?.trim())await this.updateStatus(y,"completed",0)}let j1;try{if(j.prompt?.trim())if(j1=await this.executeTurn(y,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!y.interactive)await this.finalizeSingleRun(y,j1.finishReason);else await this.completeInteractiveTurn(y,j1.finishReason)}catch(k){if(y.interactive&&y.aborting)j1=await this.completeAbortedInteractiveTurn(y);else{o$(y.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:y.sessionId,providerId:y.config.providerId,modelId:y.config.modelId}});try{await this.failSession(y)}catch($0){y.config.logger?.error?.("Session failure cleanup threw",{sessionId:y.sessionId,error:$0})}throw k}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:H,result:j1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(W)=>this.getSession(W),readMessages:(W)=>this.readSessionMessages(W),buildStartInput:(W,Z)=>{let Q=W.restoredCheckpointMetadata?{...Z.sessionMetadata??{},checkpoint:W.restoredCheckpointMetadata}:Z.sessionMetadata;return{...Z,...Q?{sessionMetadata:Q}:{},initialMessages:W.initialMessages}},startSession:(W)=>this.startSession(W),getStartedSessionId:(W)=>W.sessionId,readRestoredSession:(W)=>this.getSession(W)})}async runTurn($){let W=this.getSessionOrThrow($.sessionId),Z=W.agent.canStartRun(),Q=$.delivery??(W.interactive&&!Z?"queue":void 0);if(W.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(W,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!W.interactive)await this.finalizeSingleRun(W,J.finishReason);else await this.completeInteractiveTurn(W,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(W.interactive&&W.aborting)return await this.completeAbortedInteractiveTurn(W);throw o$(W.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:W.sessionId,providerId:W.config.providerId,modelId:W.config.modelId}}),await this.failSession(W),J}}async getAccumulatedUsage($){let W=Oj(this.usageBySession.get($)),Z=Oj(this.aggregateUsageBySession.get($));return W||Z?{usage:W,aggregateUsage:Z}:void 0}async abort($,W){let Z=this.sessions.get($);if(!Z)return;Z.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Z.aborting=!0,this.pendingPromptsController.clearAborted(Z),Z.agent.abort(W)}async stopSession($){let W=this.sessions.get($);if(!W)return;if(W.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),W.interactive&&!K0(W.status)){await this.releaseSessionRuntime(W,"session_stop");return}if(W.interactive&&W.agent.canStartRun()){await this.shutdownSession(W,{status:this.resolveInteractiveStopStatus(W),exitCode:this.resolveInteractiveStopExitCode(W),shutdownReason:"session_stop",endReason:"stopped"});return}W.aborting=!0,W.agent.abort(Error("session_stop")),await this.shutdownSession(W,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let W=[...this.sessions.values()];if(W.length===0)return;await Promise.allSettled(W.map((Z)=>Z.interactive&&!K0(Z.status)?this.releaseSessionRuntime(Z,$):Z.interactive&&Z.agent.canStartRun()?this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let W=this.sessions.get($);if(W)return GY(W);let Z=$.trim();if(!Z)return;let Q=await this.getRow(Z);if(Q)return V5(Q);let J=await this.readManifest(Z);return J?HQ(J):void 0}async listSessions($=200){let Z=(await this.listRows($)).map(V5),Q=new Set(Z.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(Q.has(J.sessionId))continue;Z.unshift(GY(J))}return Z.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let W=await this.invoke("deleteSession",$);if(W.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return W.deleted}async updateSession($,W){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:W.prompt,metadata:W.metadata,title:W.title}))?.updated===!0}}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=this.sessions.get(Z),J=Q?void 0:await this.getSession(Z);if(!(Q??J))return{updated:!1};if(Q){let Y=await this.readSessionMessages(Z),V=W.source_message_count>0&&Y.length>=W.source_message_count,B=V?Y:void 0;if(V){if(!await this.canPersistCompactionState(Z,W,Q,void 0,Y))return{updated:!1};Q.agent.restore(Y)}return await this.persistActiveSessionCompactionState(Q,W,B)}if(!await this.canPersistCompactionState(Z,W,void 0,J))return{updated:!1};let X=await this.invokeOptionalValue("readSessionCompactionState",Z);if(qD(W,X))return{updated:!1};return await this.invoke("persistSessionCompactionState",Z,W),{updated:!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=this.sessions.get(W);if(Z)for(;;){let Q=Z.compactionStateWriteQueue;if(!Q)return Z.compactionState;await Q.catch(()=>{return})}return await this.invokeOptionalValue("readSessionCompactionState",W)}isCompactionStateForSession($,W,Z,Q){let J=W.conversation_id?.trim();if(!J)return!0;if(J===$)return!0;let j=Z?.agent.getConversationId()?.trim()||Q?.conversationId?.trim();return j?J===j:!1}async canPersistCompactionState($,W,Z,Q,J){if(!W.conversation_id?.trim())return!1;if(!this.isCompactionStateForSession($,W,Z,Q))return!1;let j=J??Z?.agent.getMessages()??await this.readSessionMessages($);return F2(W,j)!==void 0}async persistActiveSessionCompactionState($,W,Z){if(!await this.canPersistCompactionState($.sessionId,W,$,void 0,Z))return{updated:!1};return await this.enqueueCompactionStateWrite($,async()=>{if(qD(W,$.compactionState))return{updated:!1};return await this.invoke("persistSessionCompactionState",$.sessionId,W),$.compactionState=W,{updated:!0}})}async enqueueCompactionStateWrite($,W){let Q=($.compactionStateWriteQueue??Promise.resolve()).catch(()=>{return}).then(W),J=Q.then(()=>{return},()=>{return});$.compactionStateWriteQueue=J;try{return await Q}finally{if($.compactionStateWriteQueue===J)$.compactionStateWriteQueue=void 0}}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.getRow(W);if(Z?.messagesPath)return l$(Z.messagesPath);let Q=await this.readManifest(W);return l$(Q?.messages_path)}async dispatchHookEvent($){await NA($,{queueSpawnRequest:(W)=>this.invokeOptional("queueSpawnRequest",W),upsertSubagentSessionFromHook:(W)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",W),appendSubagentHookAudit:(W,Z)=>this.invokeOptional("appendSubagentHookAudit",W,Z),applySubagentStatus:(W,Z)=>this.invokeOptional("applySubagentStatus",W,Z)})}subscribe($,W){return this.events.subscribe($,W)}async updateSessionModel($,W){await this.updateSessionConnection($,{modelId:W})}async updateSessionConnection($,W){let Z=E2(W),Q=this.getSessionOrThrow($);if(Z.providerId!==void 0)Q.config.providerId=Z.providerId;if(Z.modelId!==void 0)Q.config.modelId=Z.modelId;if(Z.apiKey!==void 0)Q.config.apiKey=Z.apiKey;if(Z.baseUrl!==void 0)Q.config.baseUrl=Z.baseUrl;if(Z.headers!==void 0)Q.config.headers=Z.headers;if(Z.providerConfig!==void 0)Q.config.providerConfig=Z.providerConfig;if(Object.hasOwn(Z,"reasoningEffort"))Q.config.reasoningEffort=Z.reasoningEffort??void 0;if(Object.hasOwn(Z,"thinkingBudgetTokens"))Q.config.thinkingBudgetTokens=Z.thinkingBudgetTokens??void 0;if(Object.hasOwn(Z,"thinking")){if(Q.config.thinking=Z.thinking??void 0,Z.thinking===!1||Z.thinking===null)Q.config.reasoningEffort=void 0,Q.config.thinkingBudgetTokens=void 0}let J={...Z.providerId!==void 0?{providerId:Z.providerId}:{},...Z.modelId!==void 0?{modelId:Z.modelId}:{},...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{},...Z.providerConfig!==void 0?{providerConfig:Z.providerConfig}:{},...Object.hasOwn(Z,"reasoningEffort")?{reasoningEffort:Z.reasoningEffort??void 0}:{},...Object.hasOwn(Z,"thinking")?{thinking:Z.thinking??void 0}:{},...Object.hasOwn(Z,"thinkingBudgetTokens")?{thinkingBudgetTokens:Z.thinkingBudgetTokens??void 0}:{}};if(Z.thinking===!1||Z.thinking===null)J.reasoningEffort=void 0,J.thinkingBudgetTokens=void 0;let j={...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{}};if(Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults(J),Q.agent.updateConnection(Z),Q.runtime.teamRuntime?.updateTeammateConnections(j),Z.providerId||Z.modelId)await this.mutateSessionManifest(Q,(X)=>{if(Z.providerId)X.provider=Z.providerId;if(Z.modelId)X.model=Z.modelId})}async mutateSessionManifest($,W){let Z=$.artifacts;if(!Z)return;let Q=$.sessionId,j=(this.manifestMutationQueues.get(Q)??Promise.resolve()).then(async()=>{let Y=await this.invokeOptionalValue("readSessionManifest",Q)??Z.manifest;return W(Y),Z.manifest=Y,await this.invoke("writeSessionManifest",Z.manifestPath,Y),Y}),X=j.then(()=>{return},()=>{return});this.manifestMutationQueues.set(Q,X);try{return await j}finally{if(this.manifestMutationQueues.get(Q)===X)this.manifestMutationQueues.delete(Q)}}handlePluginEvent($,W,Z){return this.eventBridge.handlePluginEvent($,W,Z)}async executeTurn($,W){let Z=await this.prepareTurnInput($,W),Q=Z.prompt.trim(),J=Z?.userImages?.length,j=Z?.userFiles?.length;if(!Q&&!J&&!j)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.refreshActiveSessionGitMetadata($),await this.syncOAuthCredentials($),await this.markTurnRunning($);try{let X=await this.executeAgentTurn($,Q,Z.userImages,Z.userFiles);while(kj($,X.finishReason)){let Y=await Ij($);if(Y.length===0)break;let V=xj($,Y);X=await this.executeAgentTurn($,V)}return X}finally{await this.refreshActiveSessionGitMetadata($)}}async completeInteractiveTurn($,W){if(VW($))return;$.lastInteractiveTurnFinishReason=W,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let W=$.lastInteractiveTurnFinishReason;if(!W)return"cancelled";switch(W){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return W}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let W=new Date,Z=$.agent.getMessages(),Q=O0();return $.persistedMessages=Z,$.started=$.started||Z.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:Z,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:W,endedAt:W,durationMs:0}}async executeAgentTurn($,W,Z,Q){let J=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),X=this.usageBySession.get($.sessionId)??O0(),Y=this.aggregateUsageBySession.get($.sessionId)??X;$.turnUsageBaseline=X,$.turnAggregateUsageBaseline=Y,$.turnPrimaryUsage=O0(),$.turnUsageByAgent=new Map,nW($.config.telemetry,$.sessionId,$.config.mode),D8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(W,Z,Q):()=>$.agent.run(W,Z,Q),B=await this.runWithAuthRetry($,V,j);$.started=!0;let H=YZ(B.messages,B,j);$.persistedMessages=H;let G=H5($.turnUsageByAgent?.values()??[]),K=_0(X,B.usage),F=_0(_0(O0(),B.usage),G),A=_0(Y,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(f)=>({...f??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,B),B}catch(V){throw o$($.config.telemetry,{component:"core",operation:"session.turn",error:V,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),V}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,W){if($.submitAndExitObserved)return;if(!W.toolCalls.some((Q)=>Q.name===T0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,j4($.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($,W){let Z=W$($.config),Q=rg(W.prompt).trim();if(!Q)return{prompt:"",userImages:W.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles)};let J=await c8(Q,Z);YF($.config.telemetry,J);let j=BW(J.prompt,W.mode??$.config.mode),X=this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles),Y=this.resolveAbsoluteFilePaths(Z,J.matchedFiles),V=Array.from(new Set([...X,...Y]));return{prompt:j,userImages:W.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let W=W$($.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:W,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 refreshActiveSessionGitMetadata($,W){try{let Z=W??await N7(W$($.config));if(!Z||!$.artifacts)return;if(R7($.artifacts.manifest.metadata,Z))return;await this.persistSessionMetadata($.sessionId,(Q)=>gW({...Q??{},...$.sessionMetadata??{}},Z))}catch(Z){$.config.logger?.debug?.("Failed to refresh session git metadata",{sessionId:$.sessionId,error:Z})}}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,W){let Z=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??Z?.artifacts?.manifest,J=W(Q?.metadata);if(!Z?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Z.sessionMetadata=J,Z.artifacts.manifest.metadata=J}async finalizeSingleRun($,W){if(VW($))return;let Z=W==="aborted"||$.aborting,Q=W==="error";await this.shutdownSession($,{status:Z?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:W})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,W){if(W.status==="completed"&&!$.submitAndExitObserved)j4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});fQ($);let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),o$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:W.status,shutdownReason:W.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){await this.refreshActiveSessionGitMetadata($);try{await this.updateStatus($,W.status,W.exitCode)}catch(J){Q("update_status",J)}try{await $.agent.shutdown(W.shutdownReason)}catch(J){Q("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(W.shutdownReason))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:W.endReason,ts:Date.now()}}),Z.length>0&&W.status==="failed")throw Z[0]}async releaseSessionRuntime($,W){let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),o$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:W,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(W)}catch(J){Q("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(W))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Z.length>0)throw Z[0]}async updateStatus($,W,Z){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,W,Z);if(!Q.updated)return;let J=await this.mutateSessionManifest($,(j)=>{if(j.status=W,K0(W))delete j.ended_at,j.exit_code=null;else j.ended_at=Q.endedAt??X0(),j.exit_code=typeof Z==="number"?Z:null});if(!J)return;$.status=W,$.updatedAt=Q.endedAt??X0(),$.endedAt=K0(W)?null:J.ended_at,$.exitCode=J.exit_code,this.emitStatus($.sessionId,W)}async runWithAuthRetry($,W,Z){try{return await W()}catch(Q){if(!G2($.config.providerId)||!pg(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Z),W()}}async syncOAuthCredentials($,W){let Z=null;try{Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:W?.forceRefresh})}catch(Q){if(Q instanceof f7)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!Z?.apiKey||$.config.apiKey===Z.apiKey)return;$.config.apiKey=Z.apiKey,$.agent.updateConnection({apiKey:Z.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Z.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Z.apiKey})}getSessionOrThrow($){let W=this.sessions.get($);if(!W){let Z=new d1($);throw o$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Z,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Z}return W}resolveAbsoluteFilePaths($,W){if(!W||W.length===0)return[];let Z=W.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>dg(Q)?Q:fY($,Q));return Array.from(new Set(Z))}getSessionAgentTelemetryIdentity($){return $$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let W=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Z=_0($.initialUsage,W);return this.withPersistedAggregateUsageFloor(Z,$.manifest)}async summarizePersistedTeammateUsage($,W,Z){let Q=fY(W),J=`${Z}.messages.json`,j;try{j=cg($)}catch{return O0()}let X=O0();for(let Y of j){if(!Y.endsWith(".messages.json"))continue;if(Y===J)continue;let V=fY($,Y);if(V===Q)continue;let B=await l$(V);if(B.length===0)continue;X=_0(X,t8(B))}return X}withPersistedAggregateUsageFloor($,W){let Z=ng(W.metadata?.aggregateUsage);if(Z)return ag($,Z);let Q=W.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,W){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:W}})}async emitSessionSnapshot($){let W=await this.getSession($);if(!W)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:E1({session:W,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($)),zD))}async getRow($){let W=$.trim();if(!W)return;return(await this.listRows(zD)).find((Q)=>Q.sessionId===W)}async readManifest($){let W=$.trim();if(!W)return;return await this.invokeOptionalValue("readSessionManifest",W)}invoke($,...W){return _D(this.sessionService,$,...W)}invokeOptional($,...W){return LD(this.sessionService,$,...W)}invokeOptionalValue($,...W){return TD(this.sessionService,$,...W)}}function sg($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function tg($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function GD($={}){let W=new b1({sessionService:new S1(new C1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:og(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:tg(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:sg(J)}},async abortSession(Z){return await W.abort(Z,Error("hub schedule abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}import{resolveClineBuildEnv as R_}from"@cline/shared";function eg($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Z)=>{if(Z&&typeof Z==="object"&&"type"in Z&&Z.type==="text"&&"text"in Z&&typeof Z.text==="string")return Z.text.trim();return""}).filter(Boolean).join(`
742
- `).trim()||void 0}var MD=120,DY="...";function EW($){let W=$.trim();if(!W)return"";if(Buffer.byteLength(W,"utf8")<=MD)return W;let Z=MD-Buffer.byteLength(DY,"utf8");if(Z<=0)return DY;let Q="";for(let J of W){if(Buffer.byteLength(Q+J,"utf8")>Z)break;Q+=J}return`${Q}${DY}`}async function RD($){let W=$?.sessionId?.trim()||"unknown",Z=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await l$(Z)].reverse().find((V)=>V.role==="assistant"),j=J?eg(J.content):void 0,X=$?.workspaceRoot?.trim()||"workspace",Y=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():X;return{title:`Task completed (${W})`,body:EW(j&&j.length>0?j:Y.length>0?Y:X),severity:"info"}}import{captureSdkError as O7,createSessionId as $v}from"@cline/shared";import{createSessionId as Qm}from"@cline/shared";import{createSessionId as Zm}from"@cline/shared";function $m($){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 Wm($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())W.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())W.parentAgentId=$.parentAgentId;if($.agentId?.trim())W.agentId=$.agentId;if($.conversationId?.trim())W.conversationId=$.conversationId;if($.messagesPath?.trim())W.messagesPath=$.messagesPath;if($.prompt?.trim())W.prompt=$.prompt;if($.provider?.trim())W.provider=$.provider;if($.model?.trim())W.model=$.model;if($.source?.trim())W.source=$.source;if(typeof $.pid==="number")W.pid=$.pid;return Object.keys(W).length>0?W:void 0}function _7($,W,Z,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:W?.createdByClientId??"hub",status:$m($.status),participants:W?[...W.participants.values()]:[],metadata:Wm($),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,...Z?{usage:{...Z}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function u($,W){return{version:$.version,requestId:$.requestId,ok:!0,...W!==void 0?{payload:W}:{}}}function h($,W,Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:W,message:Z}}}function a6($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function P0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function V8($,W,Z){return{version:"v1",event:$,eventId:Zm("hevt_"),sessionId:Z,timestamp:Date.now(),payload:W}}async function S0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let Q=await $.sessionHost.getAccumulatedUsage?.(W);return _7(Z,$.sessionState.get(W),Q?.usage,Q?.aggregateUsage)}async function u0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let[Q,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(W):[],$.sessionHost.getAccumulatedUsage?.(W)]);return E1({session:Z,messages:Q,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function _Y($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(Q==="creator"&&!j.createdByClientId)j.createdByClientId=Z;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={createdByClientId:Z,interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}function ND($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}async function LY($,W){let Z=Qm("approval_"),Q=W.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Z,{sessionId:Q,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Z,sessionId:W.sessionId,agentId:W.agentId,conversationId:W.conversationId,iteration:W.iteration,toolCallId:W.toolCallId,toolName:W.toolName,inputJson:JSON.stringify(W.input??null),policy:W.policy},Q))})}function TY($,W,Z){let Q=$.pendingApprovals.get(W);if(!Q)return;return $.pendingApprovals.delete(W),Q.resolve(Z),{sessionId:Q.sessionId}}function OY($,W,Z){let Q=0;for(let[J,j]of[...$.pendingApprovals.entries()]){if(!W({approvalId:J,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(J),j.resolve({approved:!1,reason:Z}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Z},j.sessionId)),Q+=1}return Q}async function ED($,W){let Z=typeof W.payload?.approvalId==="string"?W.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Z))return h(W,"approval_not_found",`Unknown approval: ${Z}`);let J=typeof W.payload?.reason==="string"?W.payload.reason:W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)&&typeof W.payload.payload.reason==="string"?W.payload.payload.reason:void 0,j=W.payload?.approved===!0,X=TY($,Z,{approved:j,reason:J});if(!X)return h(W,"approval_not_found",`Unknown approval: ${Z}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:j,reason:J},X.sessionId)),u(W,{approvalId:Z,approved:j})}import{createSessionId as Xm}from"@cline/shared";function Jm($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var wD={debug:10,info:20,warn:30,error:40,silent:50};function jm(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function i($,W,Z={}){if(wD[$]<wD[jm()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:W,...Object.fromEntries(Object.entries(Z).map(([J,j])=>[J,Jm(j)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function zY($,W){let Z=W instanceof Error?W.stack||W.message:String(W);i("error",$,{error:Z})}async function CD($,W,Z,Q,J,j){let X=Xm("capreq_"),Y=performance.now();return i("info","capability.request.start",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J}),await new Promise((V,B)=>{$.pendingCapabilityRequests.set(X,{sessionId:W,targetClientId:J,capabilityName:Z,onProgress:j,resolve:(H)=>{if(i(H.ok?"info":"warn","capability.request.end",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-Y)}),!H.ok){B(Error(H.error||`Capability ${Z} was rejected by ${J}.`));return}V(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:X,targetClientId:J,capabilityName:Z,payload:Q},W)),i("info","capability.request.published",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J})})}function PD($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);if((W.clientId?.trim()||"")!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{};return Q.onProgress?.(j),u(W,{requestId:Z})}function s$($,W,Z){let Q=0;for(let[J,j]of[...$.pendingCapabilityRequests.entries()]){if(!W({requestId:J,...j}))continue;$.pendingCapabilityRequests.delete(J),i("warn","capability.request.cancelled",{requestId:J,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Z}),j.resolve({ok:!1,error:Z}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Z},j.sessionId)),Q+=1}return Q}async function SD($,W){let Z=typeof W.payload?.sessionId==="string"?W.payload.sessionId.trim():W.sessionId?.trim()||"",Q=typeof W.payload?.capabilityName==="string"?W.payload.capabilityName.trim():"",J=typeof W.payload?.targetClientId==="string"?W.payload.targetClientId.trim():"";if(!Z||!Q||!J)return h(W,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{},X=await $.requestCapability(Z,Q,j,J);return u(W,X)}catch(j){return h(W,"capability_request_failed",j instanceof Error?j.message:String(j))}}function bD($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);let J=W.clientId?.trim()||"";if(J!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(Z);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:void 0,X=typeof W.payload?.error==="string"?W.payload.error:void 0,Y=W.payload?.ok===!0;return i(Y?"info":"warn","capability.respond",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,error:X}),Q.resolve({ok:Y,payload:j,error:X}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,payload:j,error:X},Q.sessionId)),u(W,{requestId:Z,ok:Y})}import{createSessionId as Ym}from"@cline/shared";function yD($,W){let Z=W.payload,Q=Z?.clientId?.trim()||W.clientId?.trim()||Ym("client_");return $.clients.set(Q,{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,actorKind:Z?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Z?.transport??"native",capabilities:Z?.capabilities??[],metadata:Z?.metadata,workspaceContext:Z?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,connectedAt:Date.now()})),u(W,{clientId:Q})}function hD($,W){let Z=W.clientId?.trim(),Q=Z?$.clients.get(Z):void 0;if(!Z||!Q)return h(W,"client_not_found","Client is not registered with this hub.");let J=a6(W.payload?.metadata);if(Q.lastSeenAt=Date.now(),J)Q.metadata=JSON.parse(JSON.stringify(J));return u(W)}function kD($,W,Z){let Q=W.clientId?.trim();if(Q)$.clients.delete(Q),Z(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return u(W)}function ID($,W){return u(W,{clients:[...$.clients.values()]})}M0();import{existsSync as mD,mkdirSync as Vm,readdirSync as Bm,readFileSync as Hm,rmSync as Gm,writeFileSync as Km}from"node:fs";import{dirname as Fm,join as xD}from"node:path";import{CONNECTOR_PLATFORMS as Am,connectorChannelsFromPlatforms as Um,listConnectorCatalog as vD,shouldIncludeConnectorField as fm}from"@cline/shared";import{resolveConnectorDataDir as Dm,resolveConnectorSettingsPath as MY}from"@cline/shared/storage";var _m=1,gD={startedAt:($)=>typeof $.startedAt==="string"?$.startedAt:void 0,port:($)=>typeof $.port==="number"?$.port:void 0,baseUrl:($)=>typeof $.baseUrl==="string"?$.baseUrl:void 0,connectionMode:($)=>typeof $.connectionMode==="string"?$.connectionMode:void 0,userName:($)=>typeof $.userName==="string"?$.userName:void 0,botUsername:($)=>typeof $.botUsername==="string"?$.botUsername:void 0,applicationId:($)=>typeof $.applicationId==="string"?$.applicationId:void 0,phoneNumberId:($)=>typeof $.phoneNumberId==="string"?$.phoneNumberId:void 0},Lm={discord:{required:["userName","applicationId"],optional:["startedAt","port","baseUrl"]},telegram:{required:["botUsername"],optional:["startedAt"]},gchat:{required:["userName"],optional:["startedAt","port","baseUrl"]},linear:{required:["userName"],optional:["startedAt","port","baseUrl"]},slack:{required:["userName"],optional:["startedAt","connectionMode","port","baseUrl"]},whatsapp:{required:["userName"],optional:["startedAt","phoneNumberId","port","baseUrl"]}};function t$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function bW($){return typeof $==="string"?$.trim():void 0}function cD($){if(!mD($))return;try{let W=JSON.parse(Hm($,"utf8"));return t$(W)?W:void 0}catch{return}}function RY(){let $=cD(MY()),W=t$($?.connectors)?$.connectors:{},Z={};for(let[Q,J]of Object.entries(W)){if(!t$(J))continue;let j=bW(J.type),X=bW(J.configuredAt),Y=bW(J.updatedAt);if(!j||!X||!Y)continue;let V=L7(J.values),B=t$(J.security)?{enabled:J.security.enabled===!0,values:L7(J.security.values)}:void 0;Z[Q]={type:j,values:V,security:B,configuredAt:X,updatedAt:Y}}return{version:_m,connectors:Z}}function uD($){let W=MY();Vm(Fm(W),{recursive:!0}),Km(W,`${JSON.stringify($,null,2)}
743
- `,"utf8")}function L7($){if(!t$($))return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q.trim();return W}function Tm($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function Om($){let W=xD(Dm(),$);if(!mD(W))return[];return Bm(W).filter((Z)=>Z.endsWith(".json")&&!Z.endsWith(".threads.json")).map((Z)=>xD(W,Z))}function zm($,W,Z){let Q=W.botUsername??W.userName??W.applicationId??W.phoneNumberId??String(Z);return`${$}:${Q}`}function qm($,W){let Z=cD(W);if(!Z)return;let Q=typeof Z.pid==="number"?Z.pid:void 0,J=typeof Z.hubUrl==="string"?Z.hubUrl:typeof Z.rpcAddress==="string"?Z.rpcAddress:void 0;if(!Q||!J||!Tm(Q))return;let j=Lm[$];if(!j)return;let X={};for(let Y of j.required){let V=gD[Y](Z);if(!V||typeof V==="string"&&!V.trim())return;X[Y]=V}for(let Y of j.optional){let V=gD[Y](Z);if(V!==void 0)X[Y]=V}return{id:zm($,X,Q),type:$,pid:Q,hubUrl:J,...X}}function Mm(){let $=[];for(let{name:W}of vD())for(let Z of Om(W)){let Q=qm(W,Z);if(Q)$.push(Q)}return $.sort((W,Z)=>{if(W.type!==Z.type)return W.type.localeCompare(Z.type);let Q=W.botUsername??W.userName??"",J=Z.botUsername??Z.userName??"";return Q.localeCompare(J)})}function Rm(){let $=RY();return Object.entries($.connectors).map(([W,Z])=>({id:W,type:Z.type,configuredAt:Z.configuredAt,updatedAt:Z.updatedAt})).sort((W,Z)=>W.type.localeCompare(Z.type))}function NY(){return{available:Um(),active:Mm(),configured:Rm()}}function Nm($,W){if($.required&&!W[$.flag]?.trim())throw Error(`${$.label} is required`)}function Em($,W){let Z={};for(let J of $.fields)Z[J.flag]=W[J.flag]??J.initialValue??"";let Q={};for(let J of $.fields){if(!fm(J,Z))continue;Nm(J,Z),Q[J.flag]=Z[J.flag]}return Q}function wm($){if(!t$($))throw Error("connector.configure payload must be an object.");let W=bW($.channel);if(!W)throw Error("channel is required");let Z=Am.find((K)=>K.id===W);if(!Z)throw Error(`unknown connector channel: ${W}`);if(!new Set(vD().map((K)=>K.name)).has(Z.id))throw Error(`connector channel is not available: ${W}`);let J=L7($.values),j=Em(Z,J),X=t$($.security)?$.security:{},Y=X.enabled===!0,V=L7(X.values);if(Y&&Z.security)for(let K of Z.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let B=RY(),H=new Date().toISOString(),G=B.connectors[W];return B.connectors[W]={type:W,values:j,security:Y?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??H,updatedAt:H},uD(B),NY()}function Cm($){if(!t$($))throw Error("connector.delete_config payload must be an object.");let W=bW($.channel);if(!W)throw Error("channel is required");let Z=RY();if(delete Z.connectors[W],Object.keys(Z.connectors).length>0)uD(Z);else Gm(MY(),{force:!0});return NY()}function Pm($){return $==="connector.configure"||$==="connector.delete_config"}function qY($,W,Z){if(!Pm(W.command))return;_8($.telemetry,{ulid:W.sessionId??W.requestId??"hub",tool:W.command,success:Z})}async function dD($,W){try{if(W.command==="connector.channels")return u(W,NY());if(W.command==="connector.configure"){let Z=wm(W.payload);return qY($,W,!0),u(W,Z)}if(W.command==="connector.delete_config"){let Z=Cm(W.payload);return qY($,W,!0),u(W,Z)}return h(W,"unsupported_connector_command",`unsupported connector command: ${W.command}`)}catch(Z){return qY($,W,!1),h(W,"connector_command_failed",Z instanceof Error?Z.message:String(Z))}}var Sm=30000;function bm($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function ym($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function hm($,W,Z){let Q=Z instanceof Error&&Z.message.trim()?Z.message:`Unknown session: ${W}`;return h($,j2,Q)}function km($){return $?$:void 0}function Im($){let W=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(W&&Number.isFinite(W)&&W>0)return Math.floor(W);let Z=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z*1000);return}async function xm($,W,Z,Q){let J=performance.now(),j=!1,X={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z.sessionId,timeoutMs:Q},Y=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-J);i("warn","run.heartbeat",{...X,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:W.requestId,elapsedMs:H,...Q?{timeoutMs:Q}:{}},Z.sessionId))},Sm),V=$.sessionHost.runTurn(Z);V.then((H)=>{if(!j)return;i("warn","run.late_end",{...X,elapsedMs:Math.round(performance.now()-J),finishReason:H?.finishReason})},(H)=>{if(!j)return;i("error","run.late_error",{...X,elapsedMs:Math.round(performance.now()-J),error:H})});let B;try{if(!Q)return await V;return await Promise.race([V,new Promise((H,G)=>{B=setTimeout(()=>{let K=`Hub run ${W.command} timed out after ${Q}ms.`;j=!0,clearInterval(Y),G(Error(K)),i("error","run.timeout",{...X,elapsedMs:Math.round(performance.now()-J)}),OY($,(F)=>F.sessionId===Z.sessionId,K),s$($,(F)=>F.sessionId===Z.sessionId,K),$.sessionHost.abort(Z.sessionId,K).catch((F)=>{i("error","run.timeout_abort_failed",{...X,error:F})})},Q)})])}finally{if(j=!0,clearInterval(Y),B)clearTimeout(B)}}async function lD($,W){let Z=P0(W),Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!J.trim())return h(W,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Z));let j=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,X=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,Y=Im(Q);$.suppressNextTerminalEventBySession.set(Z,"run.start.reply");let V;try{V=await xm($,W,{sessionId:Z,prompt:J,mode:km(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:X,timeoutMs:Y},Y)}catch(H){if($.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z);if(l1(H))return hm(W,Z,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Z)),H}if(V){let H=await u0($,Z),G=ym(V);if($.publish($.buildEvent(bm(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...H?{snapshot:H}:{}},Z)),$.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z)}else $.suppressNextTerminalEventBySession.delete(Z);let B=await u0($,Z);return u(W,V||B?{...V?{result:V}:{},...B?{snapshot:B}:{}}:void 0)}async function pD($,W){let Z=P0(W),Q=typeof W.payload?.reason==="string"?W.payload.reason:"Run was aborted before pending approval or capability request was resolved.";OY($,(J)=>J.sessionId===Z,Q);try{await $.sessionHost.abort(Z,W.payload?.reason)}catch(J){i("warn","run.abort_failed",{command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z,error:J})}finally{s$($,(J)=>J.sessionId===Z,Q)}return u(W,{applied:!0})}async function rD($,W){let Z=x6(W.payload?.payload);if(!Z)return h(W,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Z),u(W,{applied:!0})}async function iD($,W){switch(W.type){case"chunk":return;case"agent_event":await gm($,W);return;case"hook":if(W.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:W.payload.toolName},W.payload.sessionId));else if(W.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:W.payload.toolName},W.payload.sessionId));return;case"team_progress":{let Z={type:"team_progress_projection",version:1,sessionId:W.payload.sessionId,summary:W.payload.summary,lastEvent:W.payload.lifecycle};$.publish($.buildEvent("team.progress",Z,W.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:W.payload.sessionId,prompts:W.payload.prompts},W.payload.sessionId));return;case"pending_prompt_submitted":{let Z={id:W.payload.id,prompt:W.payload.prompt,delivery:W.payload.delivery,attachmentCount:W.payload.attachmentCount,userImages:W.payload.userImages,userFiles:W.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:W.payload.sessionId,prompt:Z},W.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:W.payload.sessionId,snapshot:W.payload.snapshot},W.payload.sessionId));return;case"status":{let[Z,Q]=await Promise.all([S0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(Z)$.publish($.buildEvent("session.updated",{session:Z,...Q?{snapshot:Q}:{}},W.payload.sessionId));return}case"ended":await mm($,W);return;default:return}}async function gm($,W){let{sessionId:Z,event:Q}=W.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},Z));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},Z));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},Z));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Z));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},Z));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},Z));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},Z));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},Z));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},Z));break}return}if(Q.type==="notice"){$.publish($.buildEvent("session.notice",{sessionId:Z,message:Q.message,noticeType:Q.noticeType,...Q.displayRole?{displayRole:Q.displayRole}:{},...Q.reason?{reason:Q.reason}:{},...Q.metadata?{metadata:Q.metadata}:{},agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Z)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Z,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},Z))}async function mm($,W){let Z=$.suppressNextTerminalEventBySession.get(W.payload.sessionId),Q=Z===W.payload.reason||Z==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(W.payload.sessionId);let[J,j]=await Promise.all([S0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(W.payload.reason==="completed"){let X=await RD(J);$.publish($.buildEvent("ui.notify",X,W.payload.sessionId))}if(Q)return;$.publish($.buildEvent(W.payload.reason==="aborted"?"run.aborted":W.payload.reason==="error"||W.payload.reason==="failed"?"run.failed":"run.completed",{reason:W.payload.reason,...j?{snapshot:j}:{}},W.payload.sessionId))}import{createSessionId as sD,parseRuntimeConfigExtensions as tD}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as b20,HUB_COMPACTION_CAPABILITY as y20,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as h20,HUB_HOOK_CAPABILITY_PREFIX as k20,HUB_MISTAKE_LIMIT_CAPABILITY as I20,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as x20,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as g20,isHubToolExecutorName as vm}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as d20,HUB_COMPACTION_CAPABILITY as l20,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as p20,HUB_HOOK_CAPABILITY_PREFIX as r20,HUB_MISTAKE_LIMIT_CAPABILITY as i20,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as n20,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as a20}from"@cline/shared";var cm=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function B8($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function um($,W){let Z=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=B8($.inputSchema);if(!Z||!Q||!j||!J||W.has(J))return;return W.add(J),{kind:"tool",capabilityName:J,name:Z,description:Q,inputSchema:j,...B8($.lifecycle)?{lifecycle:B8($.lifecycle)}:{}}}function wY($){if(!Array.isArray($))return[];let W=[],Z=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let J=Q,j=J.kind,X=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!X||Z.has(X))continue;if(j==="tool"){let Y=um(J,Z);if(Y)W.push(Y);continue}if(j==="toolExecutor"){let Y=J.executor;if(!vm(Y))continue;Z.add(X),W.push({kind:"toolExecutor",capabilityName:X,executor:Y});continue}if(j==="hook"){let Y=typeof J.name==="string"?J.name.trim():"";if(!Y)continue;Z.add(X),W.push({kind:"hook",capabilityName:X,name:Y});continue}if(j==="compaction"){Z.add(X),W.push({kind:"compaction",capabilityName:X,...B8(J.config)?{config:B8(J.config)}:{}});continue}if(j==="checkpoint"){Z.add(X),W.push({kind:"checkpoint",capabilityName:X,...B8(J.config)?{config:B8(J.config)}:{}});continue}if(j==="mistakeLimit"){Z.add(X),W.push({kind:"mistakeLimit",capabilityName:X});continue}if(j==="userInstructionService")Z.add(X),W.push({kind:"userInstructionService",capabilityName:X})}return W}function aD($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function dm($){return Object.hasOwn($,"update")?$.update:$}function yW($){return $.trim().replace(/^\/+/,"").toLowerCase()}function lm($){let W=($??[]).map(yW).filter(Boolean);return W.length>0?new Set(W):void 0}function pm($,W,Z){if(!Z)return!0;let Q=yW($),J=yW(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function EY($,W){let Z=lm(W);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>pm(Q.id,Q.name,Z))}function nD($,W){let Z=async(Q,J)=>{let j=yW(Q),Y=EY($,W).filter((K)=>K.id===j||yW(K.name)===j||K.id.endsWith(`:${j}`)).filter((K)=>!K.disabled);if(Y.length!==1)return Y.length>1?`Skill "${Q}" is ambiguous. Use one of: ${Y.map((K)=>K.id).join(", ")}`:`Skill "${Q}" not found.`;let V=Y[0].skill,B=J?.trim(),H=B?`
732
+ ${V}`:""}`);let B=vk($);if(pQ($))throw Error(`Skill uninstall completed, but ${$.name??$.id} is still present in Cline's global skills directories.`);return{id:$.id,type:"skill",status:"uninstalled",message:`Uninstalled ${$.name??$.id}.`,output:[V,...B.map((H)=>`Removed: ${H}`)].filter(Boolean).join(`
733
+ `)||void 0}}async function iQ($,W={}){let[Z]=RX($),Q=Z?.trim()||$.id;if(!Q)throw Error("Plugin marketplace uninstalls require a plugin name.");let J=await T9({name:Q,workspaceRoot:W.workspaceRoot});return{id:$.id,type:"plugin",status:"uninstalled",message:`Uninstalled ${$.name??J.name??$.id}.`,output:[`Path: ${J.installPath}`,...J.removedPaths.map((j)=>`Removed: ${j}`)].join(`
734
+ `)}}async function NX($,W={}){if($.type==="mcp"){let Z=z9($);if(W.deleteMcpServer)await W.deleteMcpServer(Z);else lQ($,W);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Z??$.id}.`}}if($.type==="skill")return rQ($,W);if($.type==="plugin")return iQ($,W);throw Error(`Unsupported marketplace entry type: ${$.type}`)}var bD={};w(bD,{parsePluginSource:()=>Z7,isOfficialPluginSlug:()=>W7,installPlugin:()=>yX,collectPluginMcpOAuthCandidates:()=>Q7});import{spawn as ck}from"node:child_process";import{createHash as uk}from"node:crypto";import{existsSync as y1,mkdirSync as PX,readdirSync as dk,readFileSync as lk,renameSync as nQ,rmSync as sQ,statSync as SX}from"node:fs";import{cp as CX,mkdir as ED,writeFile as tQ}from"node:fs/promises";import{homedir as LD}from"node:os";import{basename as F$,dirname as TD,extname as pk,join as t,relative as ND,resolve as a$,sep as rk}from"node:path";import{isPluginModulePath as oQ,resolveClineDir as ik,resolvePluginModuleEntries as nk}from"@cline/shared/storage";var r6="_installed",eQ="package",ak="https://github.com/cline/plugins.git",OD=30000,aQ=10485760,zD="@cline/",ok=["dependencies","devDependencies","optionalDependencies","peerDependencies"],sk={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function $7($){if($==="~")return LD();if($.startsWith("~/"))return t(LD(),$.slice(2));return $}function wD($){return $.split(rk).join("/")}function Y8($){return uk("sha256").update($).digest("hex").slice(0,12)}function tk($){let W=0;while(W<$.length&&$[W]==="-")W++;let Z=$.length;while(Z>W&&$[Z-1]==="-")Z--;return $.slice(W,Z)}function K$($){let W="",Z=!1,Q=$.startsWith("@")?$.slice(1):$;for(let j of Q.slice(0,256)){if(j>="a"&&j<="z"||j>="A"&&j<="Z"||j>="0"&&j<="9"||j==="."||j==="_"||j==="-")W+=j,Z=j==="-";else if(!Z)W+="-",Z=!0;if(W.length>=80)break}return tk(W)||"plugin"}function W7($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function ek($){return $?.trim()||ak}function qD($){let Z=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Z?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Z[1]}}function $I($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[W,...Z]=$.split("/");return!!W&&Z.length>=2&&W.includes(".")&&!W.startsWith(".")&&!W.endsWith(".")}function WI($){let W=$.match(/^git@([^:]+):(.+)$/);if(W){let X=W[2]??"",Y=X.indexOf("@");if(Y<0)return{repo:$};return{repo:`git@${W[1]}:${X.slice(0,Y)}`,ref:X.slice(Y+1)||void 0}}if($.includes("://"))try{let X=new URL($),Y=X.pathname.replace(/^\/+/,""),V=Y.indexOf("@");if(V<0)return{repo:$};return X.pathname=`/${Y.slice(0,V)}`,{repo:X.toString().replace(/\/$/,""),ref:Y.slice(V+1)||void 0}}catch{return{repo:$}}let Z=$.indexOf("/");if(Z<0)return{repo:$};let Q=$.slice(0,Z),J=$.slice(Z+1),j=J.indexOf("@");if(j<0)return{repo:$};return{repo:`${Q}/${J.slice(0,j)}`,ref:J.slice(j+1)||void 0}}function ZI($){try{return decodeURIComponent($)}catch{return $}}function QI($){return F$(ZI($))||"plugin"}function JI($){let W=$.split("/").filter(Boolean);return W.length>=5&&(W[2]==="blob"||W[2]==="raw")}function MD($){if(!/^https?:\/\//i.test($))return null;let W;try{W=new URL($)}catch{return null}let Z=W.hostname.toLowerCase(),Q=QI(W.pathname),J=oQ(Q),j=(Z==="github.com"||Z==="www.github.com")&&JI(W.pathname);if(W.protocol!=="https:"){if(j||Z==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Z==="github.com"||Z==="www.github.com"){let X=W.pathname.split("/").filter(Boolean);if(!j)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[X[0],X[1],...X.slice(3)].join("/")}`,filename:Q}}if(Z==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:W.toString(),filename:Q}}if(!J)return null;return{type:"remote",url:W.toString(),filename:Q}}function RD($,W={}){let Z=$.trim(),Q=Z.startsWith("git:")&&!Z.startsWith("git://"),J=Q?Z.slice(4).trim():Z;if(!W.force&&!Q&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:j,ref:X}=WI(J),Y="",V="";if(j.startsWith("git@")){let G=j.match(/^git@([^:]+):(.+)$/);Y=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(j)){let G=new URL(j);Y=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=j.indexOf("/");if(G<0)return null;Y=j.slice(0,G),V=j.slice(G+1)}let B=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!Y||!B||B.split("/").length<2)return null;return{type:"git",repo:j.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(j)?j:`https://${j}`,ref:X,host:Y,path:B}}function Z7($,W){let Z=$.trim();if(!Z)throw Error("plugin install requires a source");if(W==="npm"){let X=Z.startsWith("npm:")?Z.slice(4).trim():Z,{name:Y}=qD(X);return{type:"npm",spec:X,name:Y}}if(W==="git"){let X=RD(Z,{force:!0});if(!X)throw Error(`Invalid git plugin source: ${$}`);return X}if(W==="local")return{type:"local",path:$};if(W==="remote"){let X=MD(Z);if(!X)throw Error(`Invalid remote plugin source: ${$}`);return X}if(Z.startsWith("npm:")){let X=Z.slice(4).trim(),{name:Y}=qD(X);return{type:"npm",spec:X,name:Y}}if(Z.startsWith(".")||Z.startsWith("/")||Z==="~"||Z.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Z))return{type:"local",path:$};let J=MD(Z);if(J)return J;let j=RD(Z);if(j)return j;if(W7(Z))return{type:"official",slug:Z};if($I(Z))throw Error(`Unrecognized plugin source "${$}". Use --git for hostname-style repositories or pass an explicit local path such as ./github.com/owner/repo.`);return{type:"local",path:$}}function jI($){return $?t($,".cline","plugins"):t(ik(),"plugins")}function XI($,W,Z){if(W.type==="npm")return t($,r6,"npm",`${K$(W.name)}-${Y8(Z)}`);if(W.type==="git")return t($,r6,"git",K$(W.host),`${K$(W.path)}-${Y8(Z)}`);if(W.type==="remote")return t($,r6,"remote",`${K$(W.filename)}-${Y8(Z)}`);if(W.type==="official")return t($,r6,"official",`${K$(W.slug)}-${Y8(Z)}`);return t($,r6,"local",`${K$(F$($7(W.path)))}-${Y8(Z)}`)}function YI($,W,Z){if($.type==="npm")return`npm:${$.spec}`;if($.type==="git")return`git:${$.repo}${$.ref?`#${$.ref}`:""}`;if($.type==="remote")return`remote:${$.url}`;if($.type==="official")return`official:${Z}#plugins/${$.slug}`;return`local:${a$(W,$7($.path))}`}function VI($,W){if($.type==="npm")return $.name;if($.type==="git")return K$(F$($.path));if($.type==="remote")return K$(F$($.filename,pk($.filename)));if($.type==="official")return $.slug;return K$(F$(a$(W,$7($.path))))}async function i6($,W,Z={}){await new Promise((Q,J)=>{let j=ck($,W,{cwd:Z.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),X="";j.stderr.on("data",(Y)=>{X+=String(Y)}),j.on("error",J),j.on("close",(Y)=>{if(Y===0){Q();return}let V=X.trim();J(Error(`${$} ${W.join(" ")} failed with exit code ${Y}${V?`: ${V}`:""}`))})})}function CD($){let W=t($,"package.json");if(!y1(W))return null;try{return JSON.parse(lk(W,"utf8"))}catch{return null}}function BI($){let W=$?.cline?.plugins;if(!Array.isArray(W))return[];return W.flatMap((Z)=>{if(typeof Z==="string")return[Z];return Z.paths??[]})}async function HI($){let W=t($,"package.json"),Z=CD($);if(!Z)return;let Q=!1;for(let J of ok){let j=Z[J];if(!j||typeof j!=="object")continue;for(let X of Object.keys(j)){if(!X.startsWith(zD))continue;delete j[X],delete Z.peerDependenciesMeta?.[X],Q=!0}if(Object.keys(j).length===0)delete Z[J]}if(Z.peerDependenciesMeta){for(let J of Object.keys(Z.peerDependenciesMeta)){if(!J.startsWith(zD))continue;delete Z.peerDependenciesMeta[J],Q=!0}if(Object.keys(Z.peerDependenciesMeta).length===0)delete Z.peerDependenciesMeta}if(!Q)return;await tQ(W,`${JSON.stringify(Z,null,2)}
735
+ `,"utf8")}function GI($,W){let Z=t($,"node_modules","@cline");if(!y1(Z))return;for(let Q of SD(Z)){if(`@cline/${Q.name}`===W)continue;sQ(t(Z,Q.name),{recursive:!0,force:!0})}}function PD($){let W=BI(CD($)).map((j)=>a$($,j)).filter((j)=>y1(j)&&SX(j).isFile()&&oQ(j));if(W.length>0)return W;let Z=nk($);if(Z?.length)return Z;let Q=[],J=[$];while(J.length>0){let j=J.pop();if(!j)continue;for(let X of SD(j)){let Y=t(j,X.name);if(X.name==="node_modules"||X.name===".git")continue;if(X.isDirectory()){J.push(Y);continue}if(X.isFile()&&!X.name.startsWith(".")&&oQ(Y))Q.push(Y)}}return Q.sort((j,X)=>j.localeCompare(X))}function SD($){try{return dk($,{withFileTypes:!0})}catch{return[]}}function KI($,W){let Z=PD(W);if(Z.length===0)throw Error(`No plugin entry files found in ${W}`);return Z.map((Q)=>`./${wD(ND($,Q))}`)}async function FI($,W,Z){let Q=KI($,W);return await tQ(t($,"package.json"),JSON.stringify({...sk,name:Z,cline:{plugins:[{paths:Q}]}},null,2),"utf8"),Q}async function AI($,W,Z){let Q=t(W,eQ);return await ED(Q,{recursive:!0}),await tQ(t(Q,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await i6(Z,["install",$.spec,"--prefix",Q,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),GI(Q,$.name),t(Q,"node_modules",$.name)}async function bX($,W){if(!y1(t($,"package.json")))return;await HI($),await i6(W,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function UI($,W,Z){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let Q=t(W,eQ),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,Q);try{await i6("git",J)}catch(j){if(!$.ref)throw j;await i6("git",["clone","--filter=blob:none","--",$.repo,Q]),await i6("git",["checkout","--detach",$.ref],{cwd:Q})}return await bX(Q,Z),Q}async function DI($,W,Z,Q){let J=t(W,"repo");await i6("git",["clone","--filter=blob:none","--depth","1","--",Q,J]);let j=t(J,"plugins",$.slug);if(!y1(j)||!SX(j).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${Q}`);let X=t(W,eQ);return await CX(j,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),sQ(J,{recursive:!0,force:!0}),await bX(X,Z),X}function wX($){return Error(`Remote plugin file from ${$} exceeds the ${aQ} byte limit`)}function _I($){let W=$.headers.get("content-length");if(!W)return;let Z=Number(W);if(!Number.isFinite(Z)||Z<0)return;return Z}async function fI($,W){let Z=_I($);if(Z!==void 0&&Z>aQ)throw wX(W);if(!$.body){let X=Buffer.from(await $.text(),"utf8");if(X.byteLength>aQ)throw wX(W);return X}let Q=$.body.getReader(),J=[],j=0;try{while(!0){let{done:X,value:Y}=await Q.read();if(X)break;let V=Buffer.from(Y);if(j+=V.byteLength,j>aQ)throw await Q.cancel().catch(()=>{return}),wX(W);J.push(V)}return Buffer.concat(J,j)}finally{Q.releaseLock()}}async function LI($,W){let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},OD);try{let J=await fetch($.url,{signal:Z.signal});if(!J.ok){let X=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${X}`)}let j=await fI(J,$.url);return PX(W,{recursive:!0}),await tQ(t(W,$.filename),j),W}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${OD}ms`);throw J}finally{clearTimeout(Q)}}async function TI($,W,Z,Q){let J=a$(Z,$7($.path));if(!y1(J))throw Error(`Plugin source path does not exist: ${J}`);let j=SX(J);if(j.isFile()){if(!oQ(J))throw Error(`Plugin file must be .js or .ts: ${J}`);PX(W,{recursive:!0});let Y=t(W,F$(J));return await CX(J,Y),W}if(!j.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let X=t(W,eQ);return await CX(J,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),await bX(X,Q),X}function OI($,W){if(y1($)&&!W)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function zI($,W,Z){if(PX(TD(W),{recursive:!0}),!y1(W)){nQ($,W);return}if(!Z)throw Error(`Plugin is already installed at ${W}. Use --force to replace it.`);let Q=t(TD(W),`.replace-${F$(W)}-${Date.now()}-${process.pid}-${Y8(`${W}:${Math.random()}`)}`);nQ(W,Q);try{nQ($,W)}catch(J){if(!y1(W)&&y1(Q))nQ(Q,W);throw J}try{sQ(Q,{recursive:!0,force:!0})}catch{}}function qI($){let W=$.transport;if(W.type==="stdio")return!1;return W.headers!==void 0&&Object.keys(W.headers).length>0}function MI($){let W=$.oauth?.tokens?.access_token;return typeof W==="string"&&W.trim().length>0}function RI($){let W=$.metadata;if(!W||W.source!=="plugin"||typeof W.pluginName!=="string"||typeof W.pluginPath!=="string")return;return{pluginName:W.pluginName,pluginPath:W.pluginPath}}function Q7($){let W=new Set($.pluginPaths.map((J)=>a$(J)));if(W.size===0)return[];let Z;try{Z=t0({filePath:$.settingsPath??J0()})}catch{return[]}let Q=[];for(let J of Z){let j=RI(J);if(!j||!W.has(a$(j.pluginPath)))continue;let X=J.transport.type;if(X==="stdio")continue;if(qI(J)||MI(J))continue;Q.push({name:J.name,pluginName:j.pluginName,pluginPath:j.pluginPath,transportType:X,lastError:J.oauth?.lastError})}return Q.sort((J,j)=>J.name.localeCompare(j.name))}async function yX($){let W=$.source.trim(),Z=Z7(W,$.sourceType),Q=$.cwd?.trim(),J=Q?a$(Q):process.cwd(),j=jI(Q?J:void 0),X=ek($.officialPluginsRepo),Y=YI(Z,J,X),V=XI(j,Z,Y),B=VI(Z,J),H=t(j,r6,".tmp"),G=t(H,`${Date.now()}-${process.pid}-${Y8(`${W}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;OI(V,F),await ED(H,{recursive:!0});let A;try{if(Z.type==="npm")A=await AI(Z,G,K);else if(Z.type==="git")A=await UI(Z,G,K);else if(Z.type==="official")A=await DI(Z,G,K,X);else if(Z.type==="remote")A=await LI(Z,G);else A=await TI(Z,G,J,K);let D=(Z.type==="local"||Z.type==="remote")&&A===G?PD(G).map((_)=>`./${wD(ND(G,_))}`):await FI(G,A,B);if(D.length===0)throw Error(`No plugin entry files found for ${W}`);zI(G,V,F);let U={source:W,installPath:V,entryPaths:D.map((_)=>a$(V,_)),mcpSyncFailures:[],mcpOAuthCandidates:[]},f=await f9({pluginPaths:U.entryPaths,cwd:J,workspacePath:J});return U.mcpSyncFailures=f.failures,U.mcpOAuthCandidates=Q7({pluginPaths:U.entryPaths}),U}catch(D){throw sQ(G,{recursive:!0,force:!0}),D}}var uD={};w(uD,{writeModelsFileSync:()=>w9,writeModelsFile:()=>C9,toProviderModel:()=>mX,syncStoredProviderRegistration:()=>vX,resolveModelsRegistryPath:()=>h1,registerProviderSettingsProvider:()=>cD,registerCustomProvider:()=>B8,registerConfiguredProvidersFromSettings:()=>P9,readModelsFileSync:()=>n6,readModelsFile:()=>V8,parseModelsFile:()=>gX,ensureCustomProvidersLoadedSync:()=>S9,ensureCustomProvidersLoaded:()=>b9,emptyModelsFile:()=>N9,StoredProviderMetadataSchema:()=>hD,StoredProviderEntrySchema:()=>IX,StoredModelsFileSchema:()=>xX,StoredModelEntrySchema:()=>yD});import{existsSync as EI,mkdirSync as NI,readFileSync as wI,renameSync as CI,rmSync as PI,writeFileSync as SI}from"node:fs";import{mkdir as bI,readFile as yI,rename as hI,rm as kI,writeFile as II}from"node:fs/promises";import{dirname as kX,join as xI}from"node:path";import*as A0 from"@cline/llms";import{ApiFormatSchema as gI,ModelCapabilitySchema as mI,ProviderCapabilitySchema as vI,ProviderClientSchema as cI,ProviderProtocolSchema as uI}from"@cline/shared";import{z as e}from"zod";var hX=e.number().finite().positive().optional().catch(void 0),E9=e.number().finite().nonnegative().optional().catch(void 0),yD=e.object({id:e.string().optional(),name:e.string().optional(),maxTokens:hX,contextWindow:hX,maxInputTokens:hX,capabilities:e.array(mI).optional(),supportsVision:e.boolean().optional(),supportsAttachments:e.boolean().optional(),supportsReasoning:e.boolean().optional(),inputPrice:E9,outputPrice:E9,cacheReadsPrice:E9,cacheWritesPrice:E9,temperature:E9,apiFormat:gI.optional(),isR1FormatRequired:e.boolean().optional()}).passthrough(),hD=e.object({name:e.string(),baseUrl:e.string(),defaultModelId:e.string().optional(),protocol:uI.optional(),client:cI.optional(),capabilities:e.array(vI).optional(),modelsSourceUrl:e.string().optional()}).passthrough(),IX=e.object({provider:hD.optional(),models:e.record(e.string(),yD).optional()}).passthrough(),xX=e.object({version:e.literal(1),providers:e.record(e.string(),IX)}),dI=e.object({version:e.literal(1),providers:e.record(e.string(),e.unknown())}),J7=new Set;function kD($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function h1($){return xI(kX($.getFilePath()),"models.json")}function N9(){return{version:1,providers:{}}}function gX($){let W=dI.safeParse($);if(!W.success)return s("models.json content is not a valid models file envelope; starting from an empty registry"),N9();let Z={};for(let[Q,J]of Object.entries(W.data.providers)){let j=IX.safeParse(J);if(j.success)Z[Q]=j.data;else s(`models.json: dropping invalid entry for provider=${Q}`)}return{version:1,providers:Z}}function n6($){if(!EI($))return N9();try{let W=wI($,"utf8");return gX(JSON.parse(W))}catch{s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return N9()}async function V8($){try{let W=await yI($,"utf8");return gX(JSON.parse(W))}catch(W){if(W?.code!=="ENOENT")s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return N9()}function w9($,W){NI(kX($),{recursive:!0});let Z=xX.parse(W),Q=`${$}.${process.pid}.tmp`;try{SI(Q,`${JSON.stringify(Z,null,2)}
736
+ `,"utf8"),CI(Q,$)}catch(J){throw PI(Q,{force:!0}),J}}async function C9($,W){await bI(kX($),{recursive:!0});let Z=xX.parse(W),Q=`${$}.${process.pid}.tmp`;try{await II(Q,`${JSON.stringify(Z,null,2)}
737
+ `,"utf8"),await hI(Q,$)}catch(J){throw await kI(Q,{force:!0}).catch(()=>{}),J}}function mX($,W){return{id:$,name:W.name??$,supportsAttachments:W.capabilities?.includes("files"),supportsVision:W.capabilities?.includes("images"),supportsReasoning:W.capabilities?.includes("reasoning")||W.thinkingConfig!=null}}function ID($){if(!$||$.length===0)return;let W=new Set;if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("tools"))W.add("tools");return W.size>0?[...W]:void 0}function xD($){let W=new Set;if(!$||$.length===0)return[...W];if($.includes("streaming"))W.add("streaming");if($.includes("tools"))W.add("tools");if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("vision"))W.add("images"),W.add("files");return[...W]}function lI($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function gD($,W){return $??W??"openai-chat"}function mD($,W,Z){return $??Z??(W==="openai-responses"?"openai":"openai-compatible")}function vD($,W,Z){let Q=new Set(W?.capabilities??Z??[]);if(W?.supportsVision!==void 0)if(W.supportsVision)Q.add("images");else Q.delete("images");if(W?.supportsAttachments!==void 0)if(W.supportsAttachments)Q.add("files");else Q.delete("files");if(W?.supportsReasoning!==void 0)if(W.supportsReasoning)Q.add("reasoning");else Q.delete("reasoning");let J=W?.isR1FormatRequired?"r1":W?.apiFormat,j=W?.inputPrice!==void 0||W?.outputPrice!==void 0||W?.cacheReadsPrice!==void 0||W?.cacheWritesPrice!==void 0;return{id:$,name:W?.name??$,...W?.maxTokens!==void 0?{maxTokens:W.maxTokens}:{},...W?.contextWindow!==void 0?{contextWindow:W.contextWindow}:{},...W?.maxInputTokens!==void 0?{maxInputTokens:W.maxInputTokens}:{},...Q.size>0?{capabilities:[...Q]}:{},...W?.temperature!==void 0?{temperature:W.temperature}:{},...J!==void 0?{apiFormat:J}:{},...j?{pricing:{...W?.inputPrice!==void 0?{input:W.inputPrice}:{},...W?.outputPrice!==void 0?{output:W.outputPrice}:{},...W?.cacheReadsPrice!==void 0?{cacheRead:W.cacheReadsPrice}:{},...W?.cacheWritesPrice!==void 0?{cacheWrite:W.cacheWritesPrice}:{}}}:{}}}function pI($,W){for(let[Z,Q]of Object.entries(W??{})){let J=Q.id?.trim()||Z.trim();if(!J)continue;A0.registerModel($,J,vD(J,Q))}}function rI($,W,Z){return{...W??{},id:$,name:W?.name??$,capabilities:W?.capabilities??Z}}function iI($){return Object.assign({},...A0.resolveProviderModelCatalogKeys($).map((Z)=>A0.getGeneratedModelsForProvider(Z)))}function cD($){let W=$.provider.trim();if(!W||A0.isBuiltInProviderId(W))return;let Z=$.baseUrl?.trim();if(!Z)return;let Q=A0.MODEL_COLLECTIONS_BY_PROVIDER_ID[W],J=iI(W),j=xD($.capabilities),X=j.length>0?j:void 0,Y=$.model?.trim(),V={...J,...Q?.models??{}};if(Y)V[Y]=rI(Y,V[Y],X);let B=Object.keys(V).filter(Boolean),H=Y||B[0];if(!H)return;let G=gD($.protocol,Q?.provider.protocol),K=mD($.client,G,Q?.provider.client);A0.registerProvider({provider:{id:W,name:Q?.provider.name??kD(W),description:Q?.provider.description,protocol:G,client:K,baseUrl:Z,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:H,capabilities:ID($.capabilities)??Q?.provider.capabilities,source:"file"},models:V})}function P9($){for(let W of Object.values($.providers))cD(W.settings)}function B8($,W){let Z=W.models??{};if(!lI(W.provider)){pI($,Z);return}let Q=xD(W.provider.capabilities),J=Object.entries(Z).map(([B,H])=>({id:H.id?.trim()||B.trim(),model:H})).filter(({id:B})=>B.length>0),j=W.provider.defaultModelId?.trim()||J[0]?.id||"default",X=gD(W.provider.protocol,void 0),Y=mD(W.provider.client,X,void 0),V=Object.fromEntries(J.map(({id:B,model:H})=>[B,{...vD(B,H,Q.length>0?Q:void 0),status:"active"}]));A0.registerProvider({provider:{id:$,name:W.provider.name.trim()||kD($),protocol:X,client:Y,baseUrl:W.provider.baseUrl,modelsSourceUrl:W.provider.modelsSourceUrl,defaultModelId:j,capabilities:ID(W.provider.capabilities),source:"file"},models:V})}function vX($,W,Z){let Q=Z?.models??{},J=new Set;for(let[Y,V]of Object.entries(W?.models??{})){if(Object.hasOwn(Q,Y))continue;let B=V.id?.trim()||Y.trim();if(B)J.add(B),A0.unregisterModel($,B)}if(!Z)return;let j=A0.getProviderCollectionSync($);B8($,Z);let X=A0.getProviderCollectionSync($);if(j&&X&&X!==j){let Y=Object.fromEntries(Object.entries(j.models).filter(([V])=>!J.has(V)));A0.registerProvider({...X,models:{...Y,...X.models}})}}function S9($){let W=h1($);if(J7.has(W))return;let Z=n6(W);for(let[Q,J]of Object.entries(Z.providers))B8(Q,J);J7.add(W)}async function b9($){let W=h1($);if(J7.has(W))return;let Z=await V8(W);for(let[Q,J]of Object.entries(Z.providers))B8(Q,J);J7.add(W)}var sD={};w(sD,{updateLocalProvider:()=>Y7,saveLocalProviderSettings:()=>iX,saveLocalProviderOAuthCredentials:()=>sX,resolveLocalClineAuthToken:()=>eX,refreshProviderModelsFromSource:()=>nX,normalizeOAuthProvider:()=>aX,markLocalProviderEnabled:()=>lX,loginLocalProvider:()=>oX,loginAndSaveLocalProviderOAuthCredentials:()=>tX,listLocalProviders:()=>pX,getLocalProviderModels:()=>rX,ensureCustomProvidersLoaded:()=>b9,deleteLocalProvider:()=>V7,addLocalProvider:()=>dX});import*as k0 from"@cline/llms";var lD="cline-pass";function nI($){return $.apiKey??$.auth?.apiKey}function aI($){return($.auth?.accessToken?.trim()??"").length>0}function pD($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function oI($){let W=$.split(/\s+/).filter(Boolean);if(W.length===0)return"?";if(W.length===1)return W[0].slice(0,2).toUpperCase();return`${W[0][0]}${W[1][0]}`.toUpperCase()}function sI($){let W=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Z=0;for(let Q of $)Z=Z*31+Q.charCodeAt(0)>>>0;return W[Z%W.length]}function rD($){return Object.entries($).sort(([W],[Z])=>W.localeCompare(Z)).map(([W,Z])=>mX(W,Z))}async function tI($,W){let Z=await k0.getModelsForProvider($),Q=$===lD;if(!W&&!Q)return Z;let J=await R5($,{loadLatestOnInit:Q,loadPrivateOnAuth:!0,failOnError:!1},W);if($==="litellm"&&J?.knownModels)return J.knownModels;if(Q&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Z,...J.knownModels}:Z}function cX($){return[...new Set(($??[]).map((W)=>W.trim()).filter(Boolean))]}function eI($){if(!$?.length)return;return[...new Set($)]}function $x($,W){return eI([...$??[],...W??[]])}function Wx($){let W=$?.popularRank;return typeof W==="number"&&Number.isFinite(W)?W:Number.MAX_SAFE_INTEGER}function Zx($){if(!$||typeof $!=="object")return!1;let W=$;return typeof W.path==="string"&&W.path.trim().length>0&&typeof W.label==="string"&&W.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(W.type))}function Qx($){let W=$?.configFields;if(!Array.isArray(W))return;return W.filter(Zx)}var j7={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},dD={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function Jx($){if(!$)return[j7];if($.source!=="system")return $.baseUrl?[j7,dD]:[j7];let W=[];if($.env?.length)W.push(j7);if($.baseUrl)W.push(dD);return W}function jx($,W){return W.split(".").reduce((Z,Q)=>{if(!Z||typeof Z!=="object")return;return Z[Q]},$)}function Xx($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function Yx($,W,Z){if(!$?.length)return;let Q={};for(let J of $){let X=Xx(J.path==="baseUrl"&&W?.baseUrl===void 0?Z?.baseUrl:jx(W,J.path))??J.defaultValue;if(X!==void 0)Q[J.path]=X}return Q}function iD($){let W=Object.entries($??{}).filter(([Z])=>Z.trim().length>0);return W.length>0?Object.fromEntries(W):void 0}function uX($,W){let Z=W?.includes("vision")??!1,Q=W?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Z,supportsAttachments:Z,supportsReasoning:Q}]))}async function nD($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let W=$.modelsSourceUrl?await NZ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...W])]}function aD($,W){let Z=$.read(),Q=!1;if(Z.providers[W])delete Z.providers[W],Q=!0;if(Z.lastUsedProvider===W)delete Z.lastUsedProvider,Q=!0;if(Q)$.write(Z);k0.unregisterProvider(W)}async function dX($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=W.baseUrl.trim(),J=W.apiKey?.trim()??"";if(!Q&&!J){let A=h1($);if((await V8(A)).providers[Z]){let U=await V7($,{providerId:Z});return{providerId:Z,settingsPath:U.settingsPath,modelsPath:U.modelsPath,modelsCount:0}}return aD($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(k0.hasProvider(Z))throw Error(`provider "${Z}" already exists`);let j=W.name.trim();if(!j)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let X=cX(W.models),Y=W.modelsSourceUrl?.trim(),V=await nD({providerId:Z,explicitModels:X,modelsSourceUrl:Y,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let B=W.defaultModelId?.trim()&&V.includes(W.defaultModelId.trim())?W.defaultModelId.trim():V[0],H=W.capabilities?.length?[...new Set(W.capabilities)]:void 0,G=iD(W.headers);$.saveProviderSettings({provider:Z,apiKey:J||void 0,baseUrl:Q,headers:G,timeout:W.timeoutMs,model:B,protocol:W.protocol,client:W.client},{setLastUsed:!1});let K=h1($),F=await V8(K);return F.providers[Z]={provider:{name:j,baseUrl:Q,defaultModelId:B,protocol:W.protocol,client:W.client,capabilities:H,modelsSourceUrl:Y},models:uX(V,H)},await C9(K,F),B8(Z,F.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function Y7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=h1($),J=await V8(Q),j=J.providers[Z];if(!j){let O=$.getProviderSettings(Z);if(!O)throw Error(`provider "${Z}" does not exist`);let T=W.modelsSourceUrl?.trim(),L=cX(W.models)[0]??O.model?.trim();if(!L&&!T)throw Error(`provider "${Z}" cannot be updated because no model is configured`);j={provider:{name:W.name?.trim()||pD(Z),baseUrl:W.baseUrl?.trim()??O.baseUrl?.trim()??"",defaultModelId:L,protocol:O.protocol,client:O.client,capabilities:O.capabilities},models:L?uX([L],O.capabilities):{}}}if(!j.provider)throw Error(`provider "${Z}" cannot be updated because it is a model overlay (no provider metadata)`);let X=W.name?.trim()??j.provider.name.trim();if(!X)throw Error("name is required");let Y=W.baseUrl?.trim()??j.provider.baseUrl.trim();if(!Y)throw Error("baseUrl is required");let V=W.capabilities===void 0?j.provider.capabilities:W.capabilities===null?void 0:[...new Set(W.capabilities)],B=W.protocol===void 0?j.provider.protocol:W.protocol??void 0,H=W.client===void 0?j.provider.client:W.client??void 0,G=cX(W.models),K=W.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:W.modelsSourceUrl?.trim()||void 0,F=W.models!==void 0||W.modelsSourceUrl!==void 0&&!!K,A=Object.keys(j.models??{}).map((O)=>O.trim()).filter(Boolean),D=await nD({providerId:Z,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(D.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let U=W.defaultModelId===void 0?j.provider.defaultModelId?.trim():W.defaultModelId?.trim(),f=U&&D.includes(U)?U:D[0],R={...$.getProviderSettings(Z)??{},provider:Z,baseUrl:Y,model:f};if(B)R.protocol=B;else delete R.protocol;if(H)R.client=H;else delete R.client;if(W.apiKey!==void 0){let O=W.apiKey?.trim()??"";if(O)R.apiKey=O;else delete R.apiKey}if(W.headers!==void 0){let O=iD(W.headers);if(O)R.headers=O;else delete R.headers}if(W.timeoutMs!==void 0)if(typeof W.timeoutMs==="number")R.timeout=W.timeoutMs;else delete R.timeout;return $.saveProviderSettings(R,{setLastUsed:!1}),J.providers[Z]={provider:{name:X,baseUrl:Y,defaultModelId:f,protocol:B,client:H,capabilities:V,modelsSourceUrl:K},models:uX(D,V)},await C9(Q,J),B8(Z,J.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:D.length}}async function V7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=h1($),J=await V8(Q);if(!J.providers[Z])throw Error(`provider "${Z}" does not exist`);return delete J.providers[Z],await C9(Q,J),k0.unregisterProvider(Z),aD($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q}}function lX($,W,Z={}){let Q=W.trim();if(!Q)throw Error("providerId is required");let J=$.read().providers[Q]?.settings;return $.saveProviderSettings({...J??{},provider:Q},{setLastUsed:!1,tokenSource:Z.tokenSource}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function pX($,W={}){let Z=$.read(),Q=k0.getProviderIds(),J=await Promise.all(Q.map(async(X)=>{let[Y,V]=await Promise.all([k0.getProvider(X),k0.getModelsForProvider(X)]),B=rD(V),H=Z.providers[X]?.settings,G=$.getProviderSettings(X),K=Y?.name??pD(X),F=$x(Y?.capabilities,G?.capabilities),A=Qx(Y?.metadata)??Jx(Y);return{provider:{id:X,name:K,models:B.length,color:sI(X),letter:oI(K),enabled:Boolean(H),apiKey:G?nI(G):void 0,oauthAccessTokenPresent:G?aI(G):void 0,baseUrl:G?.baseUrl??Y?.baseUrl,defaultModelId:Y?.defaultModelId,protocol:G?.protocol??Y?.protocol,client:G?.client??Y?.client,capabilities:F,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:A,configValues:Yx(A,G,Y),modelList:B},rank:Wx(Y?.metadata)}}));J.sort((X,Y)=>{if(X.rank!==Y.rank)return X.rank-Y.rank;return X.provider.name.localeCompare(Y.provider.name)||X.provider.id.localeCompare(Y.provider.id)});let j=J.map((X)=>X.provider);if(W.isClinePassEnabled!==!0)j=j.filter((X)=>X.id!==lD);return{providers:j,settingsPath:$.getFilePath()}}async function rX($,W){let Z=$.trim(),Q=await tI(Z,W),J=rD(Q);return{providerId:Z,models:J}}function X7($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function oD($,W){if(!X7(W))return X7($)?{...$}:void 0;let Z=X7($)?{...$}:{};for(let[Q,J]of Object.entries(W)){if(J==null||J===""){delete Z[Q];continue}if(X7(J)){let j=oD(Z[Q],J);if(j&&Object.keys(j).length>0)Z[Q]=j;else delete Z[Q];continue}Z[Q]=J}return Object.keys(Z).length>0?Z:void 0}function iX($,W){let Z=W.providerId.trim();if(W.enabled===!1){let j=$.read();if(delete j.providers[Z],j.lastUsedProvider===Z)delete j.lastUsedProvider;return $.write(j),{providerId:Z,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Z)??{},provider:Z};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(W,j)&&typeof W[j]==="string")if(W[j].trim().length===0)delete J[j];else J[j]=W[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(W,j))J[j]=W[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(W,j)&&W[j]!=null){let X=oD(J[j],W[j]);if(X)J[j]=X;else delete J[j]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Z,enabled:!0,settingsPath:$.getFilePath()}}async function nX($,W){let Z=W.trim(),Q=$.getProviderSettings(Z),j=k0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z]?.provider,X=Q?.baseUrl?.trim()||j?.baseUrl?.trim(),Y=wZ(X,j?.baseUrl,j?.modelsSourceUrl);if(!Q||!j||!X||!Y)return{providerId:Z,refreshed:!1};let V=await Y7($,{providerId:Z,name:j.name,baseUrl:X,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:Y,protocol:Q.protocol??j.protocol??null,client:Q.client??j.client??null,capabilities:Q.capabilities??null});return{providerId:Z,refreshed:!0,modelsCount:V.modelsCount}}function aX($){let W=$.trim().toLowerCase(),Z=H0(W);if(Z)return Z.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function oX($,W,Z,Q){let J=H0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let j=D6({onPrompt:async(X)=>X.defaultValue??"",openUrl:Z,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return J.login({settings:W,callbacks:j,telemetry:Q})}function sX($,W,Z,Q,J){return F2({manager:$,providerId:W,settings:Z,credentials:Q,setLastUsed:J?.setLastUsed})}async function tX($,W,Z,Q){let J=D6({onPrompt:async(j)=>j.defaultValue??"",openUrl:Z,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return C4($,W,{callbacks:J,telemetry:Q})}function eX($){let W=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return W&&W.length>0?W:void 0}var tD={};w(tD,{getProviderConfigFields:()=>$Y});import*as B7 from"@cline/llms";var Vx=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Bx={"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 Hx($,W){let Z={};for(let Q of Vx){let J=$[Q],j=W[Q];if(J||j)Z[Q]={...J,...j}}return Z}function Gx($){let W=Bx[$.providerId];if(!W)return $;return{...$,description:W.description??$.description,fields:W.mode==="replace"?W.fields:Hx($.fields,W.fields)}}var Kx=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Fx($,W){if(!W?.provider.baseUrl)return!1;if(W.provider.source!=="system")return!0;return Kx.has($)}function $Y($){let W=B7.normalizeProviderId($);if(K2(W))return{providerId:W,authMethod:"oauth",fields:{}};let Z=B7.MODEL_COLLECTIONS_BY_PROVIDER_ID[W];if(Z?.provider.capabilities?.includes("local-auth"))return{providerId:W,authMethod:"local",fields:{}};let Q=Z?.provider.baseUrl,J={apiKey:{}};if(Fx(W,Z))J.baseUrl={defaultValue:Q};return Gx({providerId:W,authMethod:"api-key",fields:J})}var Z_={};w(Z_,{resolveLegacyClineAuth:()=>QY,migrateLegacyProviderSettings:()=>y9});import{existsSync as Ax,readFileSync as Ux}from"node:fs";import{dirname as Dx,join as WY}from"node:path";import*as a6 from"@cline/llms";import{resolveClineDataDir as _x}from"@cline/shared/storage";var H7="openai",W_=a6.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,eD=128000;function QY($){let W=$?.trim();if(!W)return;try{let Z=JSON.parse(W);if(!Z)return;let Q=typeof Z.expiresAt==="number"&&Number.isFinite(Z.expiresAt)?Z.expiresAt<10000000000?Z.expiresAt*1000:Z.expiresAt:void 0;return{accessToken:Z.idToken,refreshToken:Z.refreshToken,expiresAt:Q,accountId:Z.userInfo?.id}}catch{return}}function b($){let W=$?.trim();return W?W:void 0}function fx($){return $==="credentials"?"iam":$}function $_($){if(!Ax($))return;try{let W=Ux($,"utf8"),Z=JSON.parse(W);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function Lx($){let W=$.dataDir??_x(),Z=$.globalStatePath??WY(W,"globalState.json"),Q=$.secretsPath??WY(W,"secrets.json"),J=$_(Z),j=$_(Q);if(!J&&!j)return;return{globalState:J??{},secrets:j??{}}}function ZY($){if($===H7)return W_;return $}function Tx($,W,Z,Q){let J=Z==="plan"?"planMode":"actMode",j=W===Q?b(Z==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,Y={openrouter:`${J}OpenRouterModelId`,cline:`${J}ClineModelId`,openai:`${J}OpenAiModelId`,ollama:`${J}OllamaModelId`,lmstudio:`${J}LmStudioModelId`,litellm:`${J}LiteLlmModelId`,requesty:`${J}RequestyModelId`,together:`${J}TogetherModelId`,fireworks:`${J}FireworksModelId`,sapaicore:`${J}SapAiCoreModelId`,groq:`${J}GroqModelId`,baseten:`${J}BasetenModelId`,huggingface:`${J}HuggingFaceModelId`,"huawei-cloud-maas":`${J}HuaweiCloudMaasModelId`,oca:`${J}OcaModelId`,aihubmix:`${J}AihubmixModelId`,hicap:`${J}HicapModelId`,nousResearch:`${J}NousResearchModelId`,"vercel-ai-gateway":`${J}VercelAiGatewayModelId`}[W];return(Y?b(typeof $[Y]==="string"?$[Y]:void 0):void 0)??j}function Ox($,W,Z){let Q=Z==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...W==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...W==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(b).find(Boolean),j=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&X===void 0)return;return{...j?{effort:j}:{},...X!==void 0?{budgetTokens:X}:{}}}function zx($){let W=$["openai-codex-oauth-credentials"];if(!W)return;try{let Z=JSON.parse(W),Q=b(Z.access_token),J=b(Z.refresh_token),j=b(Z.accountId);if(!Q&&!J&&!j)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...J?{refreshToken:J}:{},...j?{accountId:j}:{}}}}catch{return}}function qx($){let W=a6.getGeneratedModelsForProvider($),Q=a6.getProviderCollectionSync($)?.provider.defaultModelId;if(Q&&W[Q])return Q;return Object.keys(W)[0]??void 0}function Mx($,W,Z,Q){let J=ZY($),j=b(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),X=Tx(W,$,Q,j)??qx(J),Y=Ox(W,J,Q),V=typeof W.requestTimeoutMs==="number"&&Number.isInteger(W.requestTimeoutMs)&&W.requestTimeoutMs>0?W.requestTimeoutMs:void 0,B={anthropic:Z.apiKey,cline:Z.clineApiKey,openai:Z.openAiApiKey,"openai-native":Z.openAiNativeApiKey,openrouter:Z.openRouterApiKey,bedrock:Z.awsBedrockApiKey,gemini:Z.geminiApiKey,ollama:Z.ollamaApiKey,deepseek:Z.deepSeekApiKey,requesty:Z.requestyApiKey,together:Z.togetherApiKey,fireworks:Z.fireworksApiKey,qwen:Z.qwenApiKey,doubao:Z.doubaoApiKey,mistral:Z.mistralApiKey,litellm:Z.liteLlmApiKey,asksage:Z.asksageApiKey,xai:Z.xaiApiKey,moonshot:Z.moonshotApiKey,zai:Z.zaiApiKey,huggingface:Z.huggingFaceApiKey,nebius:Z.nebiusApiKey,sambanova:Z.sambanovaApiKey,cerebras:Z.cerebrasApiKey,groq:Z.groqApiKey,"huawei-cloud-maas":Z.huaweiCloudMaasApiKey,baseten:Z.basetenApiKey,"vercel-ai-gateway":Z.vercelAiGatewayApiKey,dify:Z.difyApiKey,minimax:Z.minimaxApiKey,hicap:Z.hicapApiKey,aihubmix:Z.aihubmixApiKey,nousResearch:Z.nousResearchApiKey,oca:Z.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,zx(Z));if($==="cline")try{let f=b(Z["cline:clineAccountId"]);if(f)H.auth={...H.auth??{},...QY(f)}}catch{}if($===H7&&W.openAiHeaders)H.headers=W.openAiHeaders;if($==="bedrock"){let f=fx(W.awsAuthentication),_=f==="profile"||W.awsUseProfile===!0;H.aws={accessKey:b(Z.awsAccessKey),secretKey:b(Z.awsSecretKey),sessionToken:b(Z.awsSessionToken),region:b(W.awsRegion),authentication:f,profile:_?b(W.awsProfile):void 0,usePromptCache:W.awsBedrockUsePromptCache,useCrossRegionInference:W.awsUseCrossRegionInference,useGlobalInference:W.awsUseGlobalInference,endpoint:b(W.awsBedrockEndpoint),customModelBaseId:b(Q==="plan"?W.planModeAwsBedrockCustomModelBaseId:W.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:b(W.vertexProjectId),region:b(W.vertexRegion)};if($===H7&&(W.azureApiVersion||W.azureIdentity!==void 0))H.azure={apiVersion:b(W.azureApiVersion),useIdentity:W.azureIdentity};if($==="sapaicore"){let f=W.sapAiCoreUseOrchestrationMode??!0;H.sap={clientId:b(Z.sapAiCoreClientId),clientSecret:b(Z.sapAiCoreClientSecret),tokenUrl:b(W.sapAiCoreTokenUrl),resourceGroup:b(W.sapAiResourceGroup),deploymentId:f?void 0:b(Q==="plan"?W.planModeSapAiCoreDeploymentId:W.actModeSapAiCoreDeploymentId),useOrchestrationMode:f}}if($==="oca"){H.oca={mode:W.ocaMode};let f=b(Z.ocaRefreshToken);if(f)H.auth={...H.auth??{},refreshToken:f}}if($==="qwen")H.apiLine=W.qwenApiLine;if($==="moonshot")H.apiLine=W.moonshotApiLine;if($==="zai")H.apiLine=W.zaiApiLine;if($==="minimax")H.apiLine=W.minimaxApiLine;let G={anthropic:W.anthropicBaseUrl,openai:W.openAiBaseUrl,ollama:W.ollamaBaseUrl,lmstudio:W.lmStudioBaseUrl,litellm:W.liteLlmBaseUrl,gemini:W.geminiBaseUrl,requesty:W.requestyBaseUrl,asksage:W.asksageApiUrl,dify:W.difyBaseUrl,oca:W.ocaBaseUrl,aihubmix:W.aihubmixBaseUrl,sapaicore:W.sapAiCoreBaseUrl},K=b(B[$]),F=b(G[$]),A={provider:J,...K?{apiKey:K}:{},...X?{model:X}:{},...F?{baseUrl:F}:{},...Y?{reasoning:Y}:{},...V?{timeout:V}:{},...H},D=F6.safeParse(A);if(!D.success)return;return Object.keys(A).filter((f)=>f!=="provider").length>0?D.data:void 0}function Rx($,W){if($!==W_)return;if(!W.baseUrl||!W.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:W.baseUrl,defaultModelId:W.model},models:{[W.model]:{id:W.model,name:W.model,contextWindow:eD,maxInputTokens:eD,capabilities:["streaming","tools","images"]}}}}function Ex($,W){let Z=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let j=b(J);if(j)Z.add(j)}if(b(W.apiKey))Z.add("anthropic");if(b(W.openRouterApiKey))Z.add("openrouter");if(b(W.openAiApiKey))Z.add(H7);if(b(W.openAiNativeApiKey))Z.add("openai-native");if(b(W["openai-codex-oauth-credentials"]))Z.add("openai-codex");if(b(W.geminiApiKey))Z.add("gemini");if(b(W.ollamaApiKey))Z.add("ollama");if(b(W.awsAccessKey)||b(W.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||b($.awsProfile))Z.add("bedrock");if(b($.vertexProjectId)||b($.vertexRegion))Z.add("vertex");if(b(W.clineApiKey))Z.add("cline");let Q=QY(b(W["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)Z.add("cline");if(b(W.ocaApiKey))Z.add("oca");if(b(W.sapAiCoreClientId)||b(W.sapAiCoreClientSecret)||b($.sapAiCoreTokenUrl)||b($.sapAiCoreBaseUrl)||b($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Z.add("sapaicore");return Z}function y9($){let W=$.providerSettingsManager.read(),Z=Lx($);if(!Z)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let{globalState:Q,secrets:J}=Z,j=Q.mode==="plan"?"plan":"act",X=Ex(Q,J),Y=v$();Y.providers={...W.providers},Y.lastUsedProvider=W.lastUsedProvider;let V=new Date().toISOString(),B=0,H=WY(Dx($.providerSettingsManager.getFilePath()),"models.json"),G=n6(H),K=0;for(let D of X){let U=ZY(D);if(Y.providers[U])continue;let f=Mx(D,Q,J,j);if(!f)continue;Y.providers[U]={settings:f,updatedAt:V,tokenSource:"migration"},B+=1;let _=Rx(U,f);if(_&&!G.providers[U])G.providers[U]=_,K+=1}if(B===0&&K===0)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let F=b(j==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),A=F?ZY(F):void 0;if(Y.lastUsedProvider=W.lastUsedProvider??(A&&Y.providers[A]?A:Object.keys(Y.providers)[0]),$.providerSettingsManager.write(Y),K>0)w9(H,G);return{migrated:B>0||K>0,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider}}bQ();R0();fW();var Q_={};w(Q_,{SessionVersioningService:()=>o$,SessionVersioningError:()=>c0});class c0 extends Error{code;constructor($,W){super(W);this.code=$;this.name="SessionVersioningError"}}function Nx($){let W=$.sessionId.trim();if(!W)throw new c0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new c0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new c0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new c0("invalid_restore","checkpointRunCount must be a positive integer");return W}class o${async restoreCheckpoint($){let W=$.restore?.messages!==!1,Z=$.restore?.workspace!==!1,Q=Nx({sessionId:$.sessionId,restoreMessages:W,restoreWorkspace:Z,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(Q);if(!J)throw new c0("session_not_found",`Session ${Q} not found`);let j=W?await $.readMessages(Q):void 0;if(W&&j?.length===0)throw new c0("session_messages_not_found",`No messages found for session ${Q}`);let X=$X({session:J,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:W});if(Z)await($.applyWorkspaceCheckpoint??WX)(X.cwd,X.checkpoint);let Y=N1({session:J,messages:j});if(!W)return{checkpoint:X.checkpoint,sourceSnapshot:Y};let V=tj(J,$.checkpointRunCount),B=$.restore?.omitCheckpointMessageFromSession?ej(j??[],$.checkpointRunCount):X.messages??[],H={sourceSession:J,sourceMessages:j,sourceSnapshot:Y,plan:X,restoredCheckpointMetadata:V,initialMessages:B,restoreMessages:W,restoreWorkspace:Z,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new c0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??uK)(X.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:X.messages,checkpoint:X.checkpoint,sourceSnapshot:Y,...A?{restoredSnapshot:N1({session:A,messages:B})}:{}}}}var J_={};w(J_,{FileTeamPersistenceStore:()=>G7});import{appendFileSync as wx,existsSync as JY,mkdirSync as Cx,readFileSync as Px,renameSync as Sx,unlinkSync as bx,writeFileSync as yx}from"node:fs";import{join as jY}from"node:path";import{resolveTeamDataDir as hx}from"@cline/shared/storage";function kx($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class G7{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let W=kx($.teamName),Z=$.baseDir?.trim()||hx();this.dirPath=jY(Z,W),this.statePath=jY(this.dirPath,"state.json"),this.taskHistoryPath=jY(this.dirPath,"task-history.jsonl")}loadState(){if(!JY(this.statePath))return;try{let $=Px(this.statePath,"utf8"),W=JSON.parse($);if(W.version!==1||!W.teamState)return;for(let Z of W.teammates??[])this.teammateSpecs.set(Z.agentId,Z);return EU(W.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 W={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Z=`${this.statePath}.tmp`;yx(Z,`${JSON.stringify(W,null,2)}
738
+ `,"utf8"),Sx(Z,this.statePath)}appendTaskHistory($){let W={};switch($.type){case"team_task_updated":W=$.task;break;case"team_message":W={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":W={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":W={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":W={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":W={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),wx(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:W})}
739
+ `,"utf8")}ensureDir(){if(!JY(this.dirPath))Cx(this.dirPath,{recursive:!0})}hasPersistableState($){let W=$.exportState();if(this.teammateSpecs.size>0)return!0;if(W.members.some((Z)=>Z.role==="teammate"))return!0;return W.tasks.length>0||W.mailbox.length>0||W.missionLog.length>0}clearPersistedState(){if(JY(this.statePath))bx(this.statePath)}}var j_={};w(j_,{ChatViewStateSchema:()=>XY,ChatSummarySchema:()=>D7,ChatSessionStatusSchema:()=>F7,ChatSessionConfigSchema:()=>K7,ChatMessageSchema:()=>U7,ChatMessageRoleSchema:()=>A7});import{z as I}from"zod";var K7=I.object({workspaceRoot:I.string().min(1),cwd:I.string().optional(),provider:I.string().min(1),model:I.string().min(1),mode:I.enum(["act","plan"]).default("act"),apiKey:I.string(),systemPrompt:I.string().optional(),rules:I.string().optional(),maxIterations:I.number().int().positive().optional(),enableTools:I.boolean(),enableSpawn:I.boolean().optional(),enableTeams:I.boolean().optional(),autoApproveTools:I.boolean().optional(),missionStepInterval:I.number().int().positive().optional(),missionTimeIntervalMs:I.number().int().positive().optional()}),F7=I.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),A7=I.enum(["user","assistant","tool","system","status","error"]),U7=I.object({id:I.string().min(1),sessionId:I.string().nullable(),role:A7,content:I.string(),createdAt:I.number().int().nonnegative(),meta:I.object({stream:I.enum(["stdout","stderr"]).optional(),toolName:I.string().optional(),iteration:I.number().int().nonnegative().optional(),agentId:I.string().optional(),conversationId:I.string().optional(),hookEventName:I.string().optional(),inputTokens:I.number().int().nonnegative().optional(),outputTokens:I.number().int().nonnegative().optional(),checkpoint:I.object({ref:I.string(),createdAt:I.number().int().nonnegative(),runCount:I.number().int().positive(),kind:I.enum(["stash","commit"]).optional()}).optional()}).optional()}),D7=I.object({toolCalls:I.number().int().nonnegative(),tokensIn:I.number().int().nonnegative(),tokensOut:I.number().int().nonnegative()}),XY=I.object({sessionId:I.string().nullable(),status:F7,config:K7,messages:I.array(U7),rawTranscript:I.string(),error:I.string().nullable(),summary:D7});var X_={};w(X_,{CORE_BUILD_VERSION:()=>YY});var YY=R8;import{Agent as bg,createAgentRuntime as yg}from"@cline/agents";var Y_={};w(Y_,{fetchClineRecommendedModels:()=>BY,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>_7});import{getClineEnvironmentConfig as Ix}from"@cline/shared";var xx=5000,_7={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"]}],clinePass:[]};function gx($){return{recommended:$.recommended.map((W)=>({...W,tags:[...W.tags]})),free:$.free.map((W)=>({...W,tags:[...W.tags]})),clinePass:$.clinePass.map((W)=>({...W,tags:[...W.tags]}))}}function VY($){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||W.id.length===0)return null;return{id:W.id,name:typeof W.name==="string"&&W.name.length>0?W.name:W.id,description:typeof W.description==="string"?W.description:"",tags:Array.isArray(W.tags)?W.tags.filter((Z)=>typeof Z==="string"):[]}}function mx($){if(!$||typeof $!=="object")return null;let W=$,Z=Array.isArray(W.recommended)?W.recommended:[],Q=Array.isArray(W.free)?W.free:[],J=Array.isArray(W.clinePass)?W.clinePass:[],j=Z.map(VY).filter((V)=>V!==null),X=Q.map(VY).filter((V)=>V!==null),Y=J.map(VY).filter((V)=>V!==null);if(j.length===0&&X.length===0&&Y.length===0)return null;return{recommended:j,free:X,clinePass:Y}}function vx($){let W=$.baseUrl?.trim();if(W)return W;let Z=Ix().apiBaseUrl;try{return($.providerSettingsManager??new k1).getProviderSettings("cline")?.baseUrl?.trim()||Z}catch{return Z}}async function cx($,W,Z){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await $(W,{signal:Q.signal})}finally{clearTimeout(J)}}async function BY($={}){try{let W=vx($),Z=$.fetchImpl??fetch,Q=await cx(Z,`${W}/api/v1/ai/cline/recommended-models`,$.timeoutMs??xx);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let J=await Q.json(),j=mx(J);if(j)return j}catch{}return gx(_7)}var V_={};w(V_,{loadLlmsConfigFromFile:()=>GY,defineLlmsConfig:()=>HY});import{readFile as ux}from"node:fs/promises";import dx from"node:path";function HY($){return $}async function GY($){let W=dx.resolve($),Z=await ux(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(J){let j=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${W}": ${j}`)}return lx(Q,W)}function lx($,W){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${W}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${W}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${W}": "providers" cannot be empty.`);return $}var A_={};w(A_,{createLlmsSdk:()=>FY,DefaultLlmsSdk:()=>h9});import{BUILT_IN_PROVIDER_IDS as G_,createHandler as ix,createHandlerAsync as nx,getProviderCollection as ax,hasProvider as K_,registerAsyncHandler as ox,registerHandler as sx,registerModel as tx,registerProvider as F_}from"@cline/llms";function B_($){return $?{...$}:{}}function px($,W){if($)return $;if(!W)return;let Z=globalThis.process;if(!Z?.env)return;return Z.env[W]}function rx($,W){if(!W.length)throw Error(`Provider "${$}" must include at least one model.`)}function H_($){let W=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:W,defaultModel:$.collection.provider.defaultModelId,modelCount:W.length}}class KY{providers=new Map;register($){rx($.id,$.models);let W=$.defaultModel??$.models[0];if(!W)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(W))throw Error(`Default model "${W}" is not included in configured models for "${$.id}".`);let Z=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Z?.models??[],...$.models]),defaultModel:W,defaults:{...Z?.defaults??{},...B_($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:px($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...B_($.settings)}})}registerModel($,W){let Z=this.providers.get($);if(!Z){this.providers.set($,{id:$,models:new Set([W]),defaultModel:W,defaults:{}});return}Z.models.add(W)}createHandlerConfig($){let W=this.require($.providerId),Z=$.modelId??W.defaultModel;if(!W.models.has(Z))throw Error(`Model "${Z}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Z,...W.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($,W){return this.providers.get($)?.models.has(W)??!1}require($){let W=this.providers.get($);if(!W)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return W}}class h9{configuredProviders=new KY;constructor($){this.applyConfig($)}createHandler($){return ix(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return nx(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(F_($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)sx($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)ox($.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 W=$.exposeModels??Object.keys($.models),Z=$.defaultModel??W[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);F_({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Z,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:W,defaultModel:Z,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){tx($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...G_]}async getBuiltInProviders(){return(await Promise.all(G_.map((W)=>ax(W)))).filter((W)=>W!==void 0).map((W)=>H_({collection:W}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,W){return this.configuredProviders.hasModel($,W)}applyConfig($){for(let W of $.providers)this.configuredProviders.registerSelectionConfig(W);for(let W of $.models??[])this.registerModel(W);for(let W of $.customProviders??[])this.registerProvider(W);for(let W of this.configuredProviders.list()){let Z=K_(W.id),Q=this.configuredProviders.createHandlerConfig({providerId:W.id,modelId:W.defaultModel}).routingProviderId,J=typeof Q==="string"&&K_(Q);if(!Z&&!J)throw Error(`Provider "${W.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function FY($){return new h9($)}p7();async function ex(){return Promise.resolve().then(() => (bQ(),nU))}function vg(){return new Date().toISOString()}var cg="cline",ug="cline-pass";function dg($){if(z_($)!=="providers.json")return;let W=DY($);if(z_(W)!=="settings")return;return DY(W)}class k1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??mg(),this.dataDir=$.dataDir??dg(this.filePath),this.dataDir||!$.filePath)y9({providerSettingsManager:this,dataDir:this.dataDir});if(S9(this),P9(this.read()),UY(this.filePath))try{O_(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!UY(this.filePath))return v$();try{let $=kg(this.filePath,"utf8"),W=JSON.parse($),Z=A6.safeParse(W);if(Z.success){P9(Z.data);let Q=Z.data.providers.cline?.settings?.auth;return s(`providers.read providers=[${Object.keys(Z.data.providers).join(",")}] lastUsed=${Z.data.lastUsedProvider??"none"} clineAuthPresent=${!!Q?.accessToken} clineAccessTokenHash=${N0(Q?.accessToken)} clineRefreshTokenHash=${N0(Q?.refreshToken)}`),Z.data}}catch{}return v$()}write($){let W=A6.parse($),Z=DY(this.filePath);if(!UY(Z))hg(Z,{recursive:!0,mode:448});let Q=`${this.filePath}.${process.pid}.tmp`;try{gg(Q,`${JSON.stringify(W,null,2)}
740
+ `,{encoding:"utf8",mode:384}),Ig(Q,this.filePath)}catch(J){throw xg(Q,{force:!0}),J}try{O_(this.filePath,384)}catch{}P9(W)}saveProviderSettings($,W={}){let Z=F6.parse($),Q=this.read(),J=Z.provider,j=W.setLastUsed!==!1,X=Q.providers[J],Y=W.tokenSource??X?.tokenSource??"manual",V={...Q,providers:{...Q.providers,[J]:{settings:Z,updatedAt:vg(),tokenSource:Y}},lastUsedProvider:j?J:Q.lastUsedProvider};this.write(V);let B=Q.providers.cline?.settings?.auth,H=Z.provider==="cline"?Z.auth:V.providers.cline?.settings?.auth,G=!!B?.accessToken&&!H?.accessToken;return s(`providers.save providerId=${J} tokenSource=${Y} clineAuthWasPresent=${!!B?.accessToken} clineAuthIsPresent=${!!H?.accessToken} authDropped=${G}`),V}resolveProviderSettings($,W){let Z=$.providers[W]?.settings,J=H0(W)?.storageProviderId;if(!J||J===W)return Z;let j=$.providers[J]?.settings;if(!j)return Z;return F6.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Z??{},provider:W})}getProviderSettings($){let W=this.read();return this.resolveProviderSettings(W,$)}resolveLastUsedProviderId($,W){let Z=$.lastUsedProvider;if(Z===ug&&W.isClinePassEnabled===!1)return cg;return Z}getLastUsedProviderSettings($={}){let W=this.read(),Z=this.resolveLastUsedProviderId(W,$);if(!Z)return;return this.resolveProviderSettings(W,Z)}getProviderConfig($,W){let Z=this.getProviderSettings($);if(!Z)return;return s0(Z,W)}getLastUsedProviderConfig($={}){let W=this.getLastUsedProviderSettings($);if(!W)return;return s0(W,$)}async refreshCatalog(){try{await G6({})}catch{}}}R0();O8();function lg($,W){let Z=$?.expiresAt,Q=W?.expiresAt;return $?.accessToken===W?.accessToken&&$?.refreshToken===W?.refreshToken&&$?.accountId===W?.accountId&&Z===Q}class O7 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 _Y{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new k1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let W=H0($.providerId);if(!W)return null;return this.resolveWithSingleFlight(W.providerId,W.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,W,Z=!1){let Q=this.refreshInFlight.get(W);if(Q)return Q;let J=this.resolveProviderApiKeyInternal($,W,Z).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(W)});return this.refreshInFlight.set(W,J),J}async resolveProviderApiKeyInternal($,W,Z){let Q=H0($);if(!Q)return null;let J=this.providerSettingsManager.getProviderSettings(W);if(!J)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_settings`),null;let j=P4($,J);if(!j)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_credentials`),null;s(`oauth.resolve.start providerId=${$} storageProviderId=${W} forceRefresh=${Z} accessTokenHash=${N0(j.access)} refreshTokenHash=${N0(j.refresh)}`);let X=await Q.refresh({settings:J,credentials:j,forceRefresh:Z,telemetry:this.telemetry});if(!X)throw s(`oauth.resolve providerId=${$} outcome=refresh_returned_null`),new O7($);let Y=F2({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:X,setLastUsed:!1,save:!1}),V=!lg(J.auth,Y.auth);if(V)s(`oauth.resolve.refreshed providerId=${$} newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} savingToDisk=true`),this.providerSettingsManager.saveProviderSettings(Y,{setLastUsed:!1,tokenSource:"oauth"});else s(`oauth.resolve providerId=${$} outcome=not_refreshed`);return{apiKey:Q.getApiKey(Y)??X.access,accountId:X.accountId,refreshed:V}}}import{normalizeUserInput as pg}from"@cline/shared";import{nanoid as rg}from"nanoid";class q_{list($){return $?Q1($):[]}update($,W){if(!$)return{sessionId:W.sessionId,prompts:[],updated:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((V)=>V.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let J=$.pendingPrompts[Q];if(!J)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let j=W.prompt===void 0?J.prompt:pg(W.prompt).trim();if(!j)throw Error("prompt cannot be empty");let X=W.delivery??J.delivery,Y={...J,prompt:j,mode:W.mode??J.mode,delivery:X};return $.pendingPrompts.splice(Q,1),ig($,Y,Q,J.delivery),{sessionId:W.sessionId,prompts:Q1($),prompt:z7(Y),updated:!0}}delete($,W){if(!$)return{sessionId:W.sessionId,prompts:[],removed:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((j)=>j.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),removed:!1};let[J]=$.pendingPrompts.splice(Q,1);return{sessionId:W.sessionId,prompts:Q1($),prompt:J?z7(J):void 0,removed:!0}}enqueue($,W){let{prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X}=W,Y=$.pendingPrompts.findIndex((V)=>V.prompt===Z);if(Y>=0){let[V]=$.pendingPrompts.splice(Y,1),B={...V,prompt:Z,mode:Q??V.mode,userImages:j??V.userImages,userFiles:X??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...B,delivery:"steer"});else $.pendingPrompts.push(B)}else{let V={id:`pending_${Date.now()}_${rg(5)}`,prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return Q1($)}consumeSteer($){let W=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(W<0)return{prompts:Q1($)};let[Z]=$.pendingPrompts.splice(W,1);return{entry:Z,prompts:Q1($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:Q1($)}}requeueFront($,W){return $.pendingPrompts.unshift(W),Q1($)}clear($){return $.pendingPrompts.length=0,[]}}class fY{deps;service=new q_;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Z=this.service.update(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}delete($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Z=this.service.delete(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}enqueue($,W){let Z=this.deps.getSession($);if(!Z||Z.aborting)return;this.service.enqueue(Z,W),this.emitPrompts(Z),this.scheduleDrain($,Z)}consumeSteer($){let W=this.deps.getSession($);if(!W)return;let{entry:Z}=this.service.consumeSteer(W);if(!Z)return;return this.emitPrompts(W),this.emitSubmitted(W,Z),Z}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:Q1($)}})}scheduleDrain($,W){if(W.pendingPrompts.length===0||W.aborting||W.drainingPendingPrompts||!W.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let W=this.deps.getSession($);if(!W)return;if(W.aborting||W.drainingPendingPrompts)return;if(!W.agent.canStartRun())return;let{entry:Z}=this.service.shiftNext(W);if(!Z)return;this.emitPrompts(W),this.emitSubmitted(W,Z),W.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:Z.prompt,...Z.mode?{mode:Z.mode}:{},userImages:Z.userImages,userFiles:Z.userFiles})}catch{Q=!1,this.service.requeueFront(W,Z),this.emitPrompts(W)}finally{if(W.drainingPendingPrompts=!1,Q&&W.pendingPrompts.length>0&&W.status!=="failed"&&W.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,W){let Z=z7(W);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}})}}function z7($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function Q1($){return $.pendingPrompts.map(z7)}function ig($,W,Z,Q){if(W.delivery==="steer")$.pendingPrompts.unshift(W);else if(Q==="steer")$.pendingPrompts.push(W);else $.pendingPrompts.splice(Z,0,W)}R0();class TY{deps;constructor($){this.deps=$}dispatchAgentEvent($,W,Z){let Q=this.deps.getSession($),J={sessionId:$,config:W,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=TJ(Z),X=!!Q&&(!j.agentId||j.agentId===LY(Q.agent));OJ(J,Z,X?{isPrimaryAgentEvent:!0,agentId:LY(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,W){let Z=this.deps.getSession($);if(Z){if(xj(Z,W),W.type==="agent_event"){let Q={sessionId:$,config:Z.config,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};OJ(Q,W.event,{agentId:W.agentId,teamRole:"teammate",teamAgentId:W.agentId,isPrimaryAgentEvent:!1})}if(W.type==="teammate_spawned"){let Q=W$({agentId:W.teammate.runtimeAgentId??W.agentId,conversationId:W.teammate.conversationId,parentAgentId:W.teammate.parentAgentId,createdByAgentId:LY(Z.agent),teamId:Z.runtime.teamRuntime?.getTeamId(),teamName:Z.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:W.agentId});if(Q)T$(Z.config.telemetry,{ulid:$,modelId:W.teammate.modelId??Z.config.modelId,provider:Z.config.providerId,...Q})}}if(await gj($,W,this.deps.invokeBackendOptional),Z)mj(Z,$,W,this.deps.emit)}async handlePluginEvent($,W,Z){if(W.name==="plugin_log"){this.handlePluginLog($,W.payload);return}if(W.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Z;if(!V)return;let B=W.payload&&typeof W.payload==="object"?W.payload:void 0;if(!B)return;await V.ingestEvent(B);return}if(W.name!=="steer_message"&&W.name!=="queue_message"&&W.name!=="pending_prompt")return;let Q=W.payload&&typeof W.payload==="object"?W.payload:void 0,J=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,j=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!j)return;let X=W.name==="steer_message"?"steer":W.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:j,delivery:X})}handlePluginLog($,W,Z){let Q=this.deps.getSession($),J=Z??Q?.config.extensionContext?.logger??Q?.config.logger;if(!J||!W||typeof W!=="object")return;let j=W,X=typeof j.message==="string"?j.message:"";if(!X)return;let Y=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(Y.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)Y.pluginName=j.pluginName;if(j.level==="debug"){J.debug(X,Y);return}if(j.level==="error"){if(J.error)J.error(X,Y);else J.log(X,{...Y,severity:"error"});return}J.log(X,Y)}}function LY($){return $.getAgentId()}function OY($){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:Z$($.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 zY($,W){let Z=$[W];return typeof Z==="function"?Z:null}async function M_($,W,...Z){let Q=zY($,W);if(!Q)throw Error(`session service method not available: ${W}`);return Promise.resolve(Q.apply($,Z))}async function R_($,W,...Z){let Q=zY($,W);if(!Q)return;await Promise.resolve(Q.apply($,Z))}async function E_($,W,...Z){let Q=zY($,W);if(!Q)return;return await Promise.resolve(Q.apply($,Z))}X1();R0();function qY($,W,Z){return{onSubAgentEvent:(Q)=>$.onAgentEvent(Z,W,Q),onSubAgentStart:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:Z});let j=W$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)T$(W.telemetry,{ulid:Z,modelId:W.modelId,provider:W.providerId,...j});B4(W.telemetry,{event:"started",ulid:Z,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Z,Q)},onSubAgentEnd:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime,j=$.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
741
+ `).length:0;B4(W.telemetry,{event:"ended",ulid:Z,durationMs:X,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...W$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Z,Q)}}}function MY($,W,Z,Q){let J=qY($,W,Z);return y$({configProvider:{getRuntimeConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,maxIterations:W.maxIterations,hooks:W.hooks,extensions:W.extensions,logger:W.logger,telemetry:W.telemetry},getConnectionConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let X=W.enableTools?y2({cwd:W.cwd,...a0[e1({mode:W.mode})],executors:Q}):[];if(W.enableSpawnAgent)X.push(MY($,W,Z,Q));return u1(X)},...J})}import{readFile as ng,stat as ag}from"node:fs/promises";var og=20480000;async function N_($){let W=await ag($);if(!W.isFile())throw Error("Path is not a file");if(W.size>og)throw Error("File is too large to read into context.");let Z=await ng($,"utf8");if(Z.includes("\x00"))throw Error("Cannot read binary file into context.");return Z}var w_=5000;function m9($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Jm($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=m9(W.inputTokens),Q=m9(W.outputTokens),J=m9(W.cacheReadTokens),j=m9(W.cacheWriteTokens),X=m9(W.totalCost);if(Z===void 0||Q===void 0||J===void 0||j===void 0||X===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:J,cacheWriteTokens:j,totalCost:X}}function jm($,W){return{inputTokens:Math.max($.inputTokens,W.inputTokens),outputTokens:Math.max($.outputTokens,W.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,W.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,W.cacheWriteTokens),totalCost:Math.max($.totalCost,W.totalCost)}}function C_($,W){if(!W)return!1;if($.source_message_count!==W.source_message_count)return $.source_message_count<W.source_message_count;return Date.parse($.updated_at)<Date.parse(W.updated_at)}class b1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new Z9;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new o$;constructor($){let W=tg();if(W)Qm(W);let Z=x0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new d6,this.createAgentInstance=$.createAgent??((Q)=>new P$(Q)),this.defaultCapabilities=P0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new k1,this.oauthTokenManager=$.oauthTokenManager??new _Y({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Z),this.defaultFetch=$.fetch,this.pendingPromptsController=new fY({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new TY({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,J,j)=>{this.invoke("persistSessionMessages",Q,J,j)},enqueuePendingPrompt:(Q,J)=>this.pendingPromptsController.enqueue(Q,J),invokeBackendOptional:(Q,...J)=>this.invokeOptional(Q,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let W=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!W?.apiKey)return $;return{...$,config:{...$.config,apiKey:W.apiKey}}}async startSession($){let W=$.source??F0.CLI,Z=X0(),Q=$.config.sessionId?.trim()??"",J=Q||$m(),j=await this.applyInitialOAuthCredentials($),X=j.initialMessages??[],Y=X.length>0?$6(X):z0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let B=RY(V,J),H=RY(B,`${J}.messages.json`),G=RY(B,`${J}.json`),K=Z$($.config),F=m0.parse({version:1,session_id:J,source:W,pid:process.pid,started_at:Z,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:K,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}),A,D;if(Q.length>0&&X.length>0&&!j.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",J);if(k)F=k,A={manifestPath:G,messagesPath:k.messages_path||H,compactionPath:k.compaction_path,manifest:k},D=await this.invokeOptionalValue("readSessionCompactionState",J)}let f=await this.seedAggregateUsageFromArtifacts({initialUsage:Y,sessionDir:B,rootMessagesPath:A?.messagesPath??H,manifest:F});this.usageBySession.set(J,Y),this.aggregateUsageBySession.set(J,f);let _=P0(this.defaultCapabilities,$.capabilities),R=_?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,C,E={getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,W0,T0)=>this.eventBridge.dispatchAgentEvent(k,W0,T0),invokeBackendOptional:(k,...W0)=>this.invokeOptional(k,...W0)};C=await FF({input:j,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:_,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(J,k.payload,T);return}this.eventBridge.handlePluginEvent(J,k,L)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(J,k),C.config.onTeamEvent?.(k)},createSpawnTool:()=>MY(E,C.config,J,R),createSubAgentLifecycleCallbacks:(k)=>qY(E,k,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(J,()=>k)}});let p=r9(j.sessionMetadata??A?.manifest.metadata,C.gitState);if(!A)F.metadata=p;let x=await this.runtimeBuilder.build(C.runtimeBuilderInput),P=C.config,r=C.providerConfig;if(x.teamRuntime&&!P.teamName?.trim())P.teamName=x.teamRuntime.getTeamName();let d=[...x.tools,...P.extraTools??[]],I1=x.extensions??C.extensions,$2=j.initialCompactionState,A$,I0=m4(P),U0=$2??D,D1=I0&&U0?{...U0,conversation_id:U0.conversation_id?.trim()||J}:void 0,K8=I0?v4({compact:I0,getState:()=>A$?.compactionState,saveState:async(k)=>{let W0=A$;if(!W0)return;let T0={...k,conversation_id:W0.sessionId};try{if(!(await this.persistActiveSessionCompactionState(W0,T0)).updated)P.logger?.debug?.("Skipped stale session compaction state",{sessionId:W0.sessionId,sourceMessageCount:T0.source_message_count})}catch(q0){P.logger?.error?.("Failed to persist session compaction state",{sessionId:W0.sessionId,error:q0}),s$(P.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:q0,context:{sessionId:W0.sessionId,providerId:P.providerId,modelId:P.modelId}})}}}):void 0,V0={sessionId:J,providerId:r.providerId,modelId:r.modelId,apiKey:r.apiKey,baseUrl:r.baseUrl,headers:r.headers,knownModels:r.knownModels,providerConfig:r,thinking:P.thinking,reasoningEffort:P.reasoningEffort??r.reasoningEffort,thinkingBudgetTokens:P.thinkingBudgetTokens,maxTokensPerTurn:P.maxTokensPerTurn,temperature:P.temperature,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:K8,tools:d,hooks:C.hooks,extensions:I1,hookErrorMode:P.hookErrorMode,initialMessages:C.effectiveInput.initialMessages,userFileContentLoader:N_,toolPolicies:C.toolPolicies,requestToolApproval:C.requestToolApproval?async(k)=>{let W0=C.requestToolApproval,T0=this.sessions.get(J);if(T0)await this.markTurnPending(T0);try{if(!W0)return{approved:!1,reason:"Tool approval callback is not configured."};return await W0(k)}finally{let q0=this.sessions.get(J);if(q0?.status==="pending")await this.markTurnRunning(q0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:x.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(J);return k?G9(k.prompt,k.mode??P.mode):void 0},logger:x.logger??P.logger,extensionContext:P.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(J,P,k)};V0.hooks={...V0.hooks,onEvent:async(k)=>{if(await C.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let W0=this.sessions.get(J);if(!W0)return;let T0=W0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,T0,P.systemPrompt)}catch(q0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:q0}),s$(P.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:q0,severity:"warn",handled:!0,context:{sessionId:J,providerId:P.providerId,modelId:P.modelId}})}}};let d0=this.createAgentInstance(V0);if(V0.onEvent)d0.subscribeEvents(V0.onEvent);x.registerLeadAgent?.(d0);let J1=W$({agentId:d0.getAgentId(),conversationId:d0.getConversationId(),teamId:x.teamRuntime?.getTeamId(),teamName:x.teamRuntime?.getTeamName(),teamRole:x.teamRuntime?"lead":void 0});if(UF(P,J,Q.length>0,K,J1),J1)T$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...J1});if(x.teamRuntime)VW(P.telemetry,{ulid:J,teamId:x.teamRuntime.getTeamId(),teamName:x.teamRuntime.getTeamName(),leadAgentId:d0.getAgentId(),restoredFromPersistence:x.teamRestoredFromPersistence===!0});let y={sessionId:J,config:P,sessionMetadata:p,...A?{artifacts:A}:{},source:W,startedAt:A?.manifest.started_at??Z,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Z,pendingPrompt:F.prompt,runtime:x,agent:d0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:X,compactionState:D1,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:C.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(A$=y,y.compactionState&&!this.isCompactionStateForSession(y.sessionId,y.compactionState,y))y.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:y.sessionId,conversationId:y.compactionState.conversation_id}),y.compactionState=void 0;if(this.sessions.set(J,y),A)await this.refreshActiveSessionGitMetadata(y,C.gitState);if(this.emitStatus(J,"running"),X.length>0&&!A){if(await this.ensureSessionPersisted(y),await this.invoke("persistSessionMessages",y.sessionId,X,y.config.systemPrompt),y.compactionState){if(!(await this.persistActiveSessionCompactionState(y,y.compactionState)).updated)y.compactionState=void 0}if(!j.prompt?.trim())await this.updateStatus(y,"completed",0)}let j1;try{if(j.prompt?.trim())if(j1=await this.executeTurn(y,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!y.interactive)await this.finalizeSingleRun(y,j1.finishReason);else await this.completeInteractiveTurn(y,j1.finishReason)}catch(k){if(y.interactive&&y.aborting)j1=await this.completeAbortedInteractiveTurn(y);else{s$(y.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:y.sessionId,providerId:y.config.providerId,modelId:y.config.modelId}});try{await this.failSession(y)}catch(W0){y.config.logger?.error?.("Session failure cleanup threw",{sessionId:y.sessionId,error:W0})}throw k}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:H,result:j1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(W)=>this.getSession(W),readMessages:(W)=>this.readSessionMessages(W),buildStartInput:(W,Z)=>{let Q=W.restoredCheckpointMetadata?{...Z.sessionMetadata??{},checkpoint:W.restoredCheckpointMetadata}:Z.sessionMetadata;return{...Z,...Q?{sessionMetadata:Q}:{},initialMessages:W.initialMessages}},startSession:(W)=>this.startSession(W),getStartedSessionId:(W)=>W.sessionId,readRestoredSession:(W)=>this.getSession(W)})}async runTurn($){let W=this.getSessionOrThrow($.sessionId),Z=W.agent.canStartRun(),Q=$.delivery??(W.interactive&&!Z?"queue":void 0);if(W.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(W,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!W.interactive)await this.finalizeSingleRun(W,J.finishReason);else await this.completeInteractiveTurn(W,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(W.interactive&&W.aborting)return await this.completeAbortedInteractiveTurn(W);throw s$(W.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:W.sessionId,providerId:W.config.providerId,modelId:W.config.modelId}}),await this.failSession(W),J}}async getAccumulatedUsage($){let W=Ej(this.usageBySession.get($)),Z=Ej(this.aggregateUsageBySession.get($));return W||Z?{usage:W,aggregateUsage:Z}:void 0}async abort($,W){let Z=this.sessions.get($);if(!Z)return;Z.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Z.aborting=!0,this.pendingPromptsController.clearAborted(Z),Z.agent.abort(W)}async stopSession($){let W=this.sessions.get($);if(!W)return;if(W.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),W.interactive&&!K0(W.status)){await this.releaseSessionRuntime(W,"session_stop");return}if(W.interactive&&W.agent.canStartRun()){await this.shutdownSession(W,{status:this.resolveInteractiveStopStatus(W),exitCode:this.resolveInteractiveStopExitCode(W),shutdownReason:"session_stop",endReason:"stopped"});return}W.aborting=!0,W.agent.abort(Error("session_stop")),await this.shutdownSession(W,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let W=[...this.sessions.values()];if(W.length===0)return;await Promise.allSettled(W.map((Z)=>Z.interactive&&!K0(Z.status)?this.releaseSessionRuntime(Z,$):Z.interactive&&Z.agent.canStartRun()?this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let W=this.sessions.get($);if(W)return OY(W);let Z=$.trim();if(!Z)return;let Q=await this.getRow(Z);if(Q)return H5(Q);let J=await this.readManifest(Z);return J?LQ(J):void 0}async listSessions($=200){let Z=(await this.listRows($)).map(H5),Q=new Set(Z.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(Q.has(J.sessionId))continue;Z.unshift(OY(J))}return Z.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let W=await this.invoke("deleteSession",$);if(W.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return W.deleted}async updateSession($,W){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:W.prompt,metadata:W.metadata,title:W.title}))?.updated===!0}}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=this.sessions.get(Z),J=Q?void 0:await this.getSession(Z);if(!(Q??J))return{updated:!1};if(Q){let Y=await this.readSessionMessages(Z),V=W.source_message_count>0&&Y.length>=W.source_message_count,B=V?Y:void 0;if(V){if(!await this.canPersistCompactionState(Z,W,Q,void 0,Y))return{updated:!1};Q.agent.restore(Y)}return await this.persistActiveSessionCompactionState(Q,W,B)}if(!await this.canPersistCompactionState(Z,W,void 0,J))return{updated:!1};let X=await this.invokeOptionalValue("readSessionCompactionState",Z);if(C_(W,X))return{updated:!1};return await this.invoke("persistSessionCompactionState",Z,W),{updated:!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=this.sessions.get(W);if(Z)for(;;){let Q=Z.compactionStateWriteQueue;if(!Q)return Z.compactionState;await Q.catch(()=>{return})}return await this.invokeOptionalValue("readSessionCompactionState",W)}isCompactionStateForSession($,W,Z,Q){let J=W.conversation_id?.trim();if(!J)return!0;if(J===$)return!0;let j=Z?.agent.getConversationId()?.trim()||Q?.conversationId?.trim();return j?J===j:!1}async canPersistCompactionState($,W,Z,Q,J){if(!W.conversation_id?.trim())return!1;if(!this.isCompactionStateForSession($,W,Z,Q))return!1;let j=J??Z?.agent.getMessages()??await this.readSessionMessages($);return A2(W,j)!==void 0}async persistActiveSessionCompactionState($,W,Z){if(!await this.canPersistCompactionState($.sessionId,W,$,void 0,Z))return{updated:!1};return await this.enqueueCompactionStateWrite($,async()=>{if(C_(W,$.compactionState))return{updated:!1};return await this.invoke("persistSessionCompactionState",$.sessionId,W),$.compactionState=W,{updated:!0}})}async enqueueCompactionStateWrite($,W){let Q=($.compactionStateWriteQueue??Promise.resolve()).catch(()=>{return}).then(W),J=Q.then(()=>{return},()=>{return});$.compactionStateWriteQueue=J;try{return await Q}finally{if($.compactionStateWriteQueue===J)$.compactionStateWriteQueue=void 0}}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.getRow(W);if(Z?.messagesPath)return p$(Z.messagesPath);let Q=await this.readManifest(W);return p$(Q?.messages_path)}async dispatchHookEvent($){await kA($,{queueSpawnRequest:(W)=>this.invokeOptional("queueSpawnRequest",W),upsertSubagentSessionFromHook:(W)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",W),appendSubagentHookAudit:(W,Z)=>this.invokeOptional("appendSubagentHookAudit",W,Z),applySubagentStatus:(W,Z)=>this.invokeOptional("applySubagentStatus",W,Z)})}subscribe($,W){return this.events.subscribe($,W)}async updateSessionModel($,W){await this.updateSessionConnection($,{modelId:W})}async updateSessionConnection($,W){let Z=w2(W),Q=this.getSessionOrThrow($);if(Z.providerId!==void 0)Q.config.providerId=Z.providerId;if(Z.modelId!==void 0)Q.config.modelId=Z.modelId;if(Z.apiKey!==void 0)Q.config.apiKey=Z.apiKey;if(Z.baseUrl!==void 0)Q.config.baseUrl=Z.baseUrl;if(Z.headers!==void 0)Q.config.headers=Z.headers;if(Z.providerConfig!==void 0)Q.config.providerConfig=Z.providerConfig;if(Object.hasOwn(Z,"reasoningEffort"))Q.config.reasoningEffort=Z.reasoningEffort??void 0;if(Object.hasOwn(Z,"thinkingBudgetTokens"))Q.config.thinkingBudgetTokens=Z.thinkingBudgetTokens??void 0;if(Object.hasOwn(Z,"thinking")){if(Q.config.thinking=Z.thinking??void 0,Z.thinking===!1||Z.thinking===null)Q.config.reasoningEffort=void 0,Q.config.thinkingBudgetTokens=void 0}let J={...Z.providerId!==void 0?{providerId:Z.providerId}:{},...Z.modelId!==void 0?{modelId:Z.modelId}:{},...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{},...Z.providerConfig!==void 0?{providerConfig:Z.providerConfig}:{},...Object.hasOwn(Z,"reasoningEffort")?{reasoningEffort:Z.reasoningEffort??void 0}:{},...Object.hasOwn(Z,"thinking")?{thinking:Z.thinking??void 0}:{},...Object.hasOwn(Z,"thinkingBudgetTokens")?{thinkingBudgetTokens:Z.thinkingBudgetTokens??void 0}:{}};if(Z.thinking===!1||Z.thinking===null)J.reasoningEffort=void 0,J.thinkingBudgetTokens=void 0;let j={...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{}};if(Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults(J),Q.agent.updateConnection(Z),Q.runtime.teamRuntime?.updateTeammateConnections(j),Z.providerId||Z.modelId)await this.mutateSessionManifest(Q,(X)=>{if(Z.providerId)X.provider=Z.providerId;if(Z.modelId)X.model=Z.modelId})}async mutateSessionManifest($,W){let Z=$.artifacts;if(!Z)return;let Q=$.sessionId,j=(this.manifestMutationQueues.get(Q)??Promise.resolve()).then(async()=>{let Y=await this.invokeOptionalValue("readSessionManifest",Q)??Z.manifest;return W(Y),Z.manifest=Y,await this.invoke("writeSessionManifest",Z.manifestPath,Y),Y}),X=j.then(()=>{return},()=>{return});this.manifestMutationQueues.set(Q,X);try{return await j}finally{if(this.manifestMutationQueues.get(Q)===X)this.manifestMutationQueues.delete(Q)}}handlePluginEvent($,W,Z){return this.eventBridge.handlePluginEvent($,W,Z)}async executeTurn($,W){let Z=await this.prepareTurnInput($,W),Q=Z.prompt.trim(),J=Z?.userImages?.length,j=Z?.userFiles?.length;if(!Q&&!J&&!j)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.refreshActiveSessionGitMetadata($),await this.syncOAuthCredentials($),await this.markTurnRunning($);try{let X=await this.executeAgentTurn($,Q,Z.userImages,Z.userFiles);while(vj($,X.finishReason)){let Y=await cj($);if(Y.length===0)break;let V=uj($,Y);X=await this.executeAgentTurn($,V)}return X}finally{await this.refreshActiveSessionGitMetadata($)}}async completeInteractiveTurn($,W){if(H9($))return;$.lastInteractiveTurnFinishReason=W,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let W=$.lastInteractiveTurnFinishReason;if(!W)return"cancelled";switch(W){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return W}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let W=new Date,Z=$.agent.getMessages(),Q=z0();return $.persistedMessages=Z,$.started=$.started||Z.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:Z,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:W,endedAt:W,durationMs:0}}async executeAgentTurn($,W,Z,Q){let J=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),X=this.usageBySession.get($.sessionId)??z0(),Y=this.aggregateUsageBySession.get($.sessionId)??X;$.turnUsageBaseline=X,$.turnAggregateUsageBaseline=Y,$.turnPrimaryUsage=z0(),$.turnUsageByAgent=new Map,ZW($.config.telemetry,$.sessionId,$.config.mode),L8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(W,Z,Q):()=>$.agent.run(W,Z,Q),B=await this.runWithAuthRetry($,V,j);$.started=!0;let H=DZ(B.messages,B,j);$.persistedMessages=H;let G=K5($.turnUsageByAgent?.values()??[]),K=L0(X,B.usage),F=L0(L0(z0(),B.usage),G),A=L0(Y,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(D)=>({...D??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,B),B}catch(V){throw s$($.config.telemetry,{component:"core",operation:"session.turn",error:V,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),V}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,W){if($.submitAndExitObserved)return;if(!W.toolCalls.some((Q)=>Q.name===O0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,Y4($.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($,W){let Z=Z$($.config),Q=Zm(W.prompt).trim();if(!Q)return{prompt:"",userImages:W.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles)};let J=await d8(Q,Z);DF($.config.telemetry,J);let j=G9(J.prompt,W.mode??$.config.mode),X=this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles),Y=this.resolveAbsoluteFilePaths(Z,J.matchedFiles),V=Array.from(new Set([...X,...Y]));return{prompt:j,userImages:W.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let W=Z$($.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:W,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 refreshActiveSessionGitMetadata($,W){try{let Z=W??await S7(Z$($.config));if(!Z||!$.artifacts)return;if(P7($.artifacts.manifest.metadata,Z))return;await this.persistSessionMetadata($.sessionId,(Q)=>r9({...Q??{},...$.sessionMetadata??{}},Z))}catch(Z){$.config.logger?.debug?.("Failed to refresh session git metadata",{sessionId:$.sessionId,error:Z})}}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,W){let Z=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??Z?.artifacts?.manifest,J=W(Q?.metadata);if(!Z?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Z.sessionMetadata=J,Z.artifacts.manifest.metadata=J}async finalizeSingleRun($,W){if(H9($))return;let Z=W==="aborted"||$.aborting,Q=W==="error";await this.shutdownSession($,{status:Z?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:W})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,W){if(W.status==="completed"&&!$.submitAndExitObserved)Y4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});RQ($);let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),s$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:W.status,shutdownReason:W.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){await this.refreshActiveSessionGitMetadata($);try{await this.updateStatus($,W.status,W.exitCode)}catch(J){Q("update_status",J)}try{await $.agent.shutdown(W.shutdownReason)}catch(J){Q("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(W.shutdownReason))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:W.endReason,ts:Date.now()}}),Z.length>0&&W.status==="failed")throw Z[0]}async releaseSessionRuntime($,W){let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),s$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:W,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(W)}catch(J){Q("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(W))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Z.length>0)throw Z[0]}async updateStatus($,W,Z){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,W,Z);if(!Q.updated)return;let J=await this.mutateSessionManifest($,(j)=>{if(j.status=W,K0(W))delete j.ended_at,j.exit_code=null;else j.ended_at=Q.endedAt??X0(),j.exit_code=typeof Z==="number"?Z:null});if(!J)return;$.status=W,$.updatedAt=Q.endedAt??X0(),$.endedAt=K0(W)?null:J.ended_at,$.exitCode=J.exit_code,this.emitStatus($.sessionId,W)}async runWithAuthRetry($,W,Z){try{return await W()}catch(Q){if(!K2($.config.providerId)||!Wm(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Z),W()}}async syncOAuthCredentials($,W){let Z=null;try{Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:W?.forceRefresh})}catch(Q){if(Q instanceof O7)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!Z?.apiKey||$.config.apiKey===Z.apiKey)return;$.config.apiKey=Z.apiKey,$.agent.updateConnection({apiKey:Z.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Z.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Z.apiKey})}getSessionOrThrow($){let W=this.sessions.get($);if(!W){let Z=new l1($);throw s$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Z,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Z}return W}resolveAbsoluteFilePaths($,W){if(!W||W.length===0)return[];let Z=W.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>eg(Q)?Q:EY($,Q));return Array.from(new Set(Z))}getSessionAgentTelemetryIdentity($){return W$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let W=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Z=L0($.initialUsage,W);return this.withPersistedAggregateUsageFloor(Z,$.manifest)}async summarizePersistedTeammateUsage($,W,Z){let Q=EY(W),J=`${Z}.messages.json`,j;try{j=sg($)}catch{return z0()}let X=z0();for(let Y of j){if(!Y.endsWith(".messages.json"))continue;if(Y===J)continue;let V=EY($,Y);if(V===Q)continue;let B=await p$(V);if(B.length===0)continue;X=L0(X,$6(B))}return X}withPersistedAggregateUsageFloor($,W){let Z=Jm(W.metadata?.aggregateUsage);if(Z)return jm($,Z);let Q=W.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,W){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:W}})}async emitSessionSnapshot($){let W=await this.getSession($);if(!W)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:N1({session:W,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($)),w_))}async getRow($){let W=$.trim();if(!W)return;return(await this.listRows(w_)).find((Q)=>Q.sessionId===W)}async readManifest($){let W=$.trim();if(!W)return;return await this.invokeOptionalValue("readSessionManifest",W)}invoke($,...W){return M_(this.sessionService,$,...W)}invokeOptional($,...W){return R_(this.sessionService,$,...W)}invokeOptionalValue($,...W){return E_(this.sessionService,$,...W)}}function Ym($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function Vm($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function __($={}){let W=new b1({sessionService:new S1(new C1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:Xm(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Vm(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:Ym(J)}},async abortSession(Z){return await W.abort(Z,Error("hub schedule abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}import{resolveClineBuildEnv as Sf}from"@cline/shared";function Bm($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Z)=>{if(Z&&typeof Z==="object"&&"type"in Z&&Z.type==="text"&&"text"in Z&&typeof Z.text==="string")return Z.text.trim();return""}).filter(Boolean).join(`
742
+ `).trim()||void 0}var P_=120,NY="...";function k9($){let W=$.trim();if(!W)return"";if(Buffer.byteLength(W,"utf8")<=P_)return W;let Z=P_-Buffer.byteLength(NY,"utf8");if(Z<=0)return NY;let Q="";for(let J of W){if(Buffer.byteLength(Q+J,"utf8")>Z)break;Q+=J}return`${Q}${NY}`}async function S_($){let W=$?.sessionId?.trim()||"unknown",Z=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await p$(Z)].reverse().find((V)=>V.role==="assistant"),j=J?Bm(J.content):void 0,X=$?.workspaceRoot?.trim()||"workspace",Y=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():X;return{title:`Task completed (${W})`,body:k9(j&&j.length>0?j:Y.length>0?Y:X),severity:"info"}}import{captureSdkError as E7,createSessionId as Hv}from"@cline/shared";import{createSessionId as Fm}from"@cline/shared";import{createSessionId as Km}from"@cline/shared";function Hm($){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 Gm($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())W.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())W.parentAgentId=$.parentAgentId;if($.agentId?.trim())W.agentId=$.agentId;if($.conversationId?.trim())W.conversationId=$.conversationId;if($.messagesPath?.trim())W.messagesPath=$.messagesPath;if($.prompt?.trim())W.prompt=$.prompt;if($.provider?.trim())W.provider=$.provider;if($.model?.trim())W.model=$.model;if($.source?.trim())W.source=$.source;if(typeof $.pid==="number")W.pid=$.pid;return Object.keys(W).length>0?W:void 0}function q7($,W,Z,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:W?.createdByClientId??"hub",status:Hm($.status),participants:W?[...W.participants.values()]:[],metadata:Gm($),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,...Z?{usage:{...Z}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function u($,W){return{version:$.version,requestId:$.requestId,ok:!0,...W!==void 0?{payload:W}:{}}}function h($,W,Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:W,message:Z}}}function s6($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function S0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function H8($,W,Z){return{version:"v1",event:$,eventId:Km("hevt_"),sessionId:Z,timestamp:Date.now(),payload:W}}async function b0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let Q=await $.sessionHost.getAccumulatedUsage?.(W);return q7(Z,$.sessionState.get(W),Q?.usage,Q?.aggregateUsage)}async function u0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let[Q,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(W):[],$.sessionHost.getAccumulatedUsage?.(W)]);return N1({session:Z,messages:Q,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function wY($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(Q==="creator"&&!j.createdByClientId)j.createdByClientId=Z;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={createdByClientId:Z,interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}function b_($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}async function CY($,W){let Z=Fm("approval_"),Q=W.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Z,{sessionId:Q,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Z,sessionId:W.sessionId,agentId:W.agentId,conversationId:W.conversationId,iteration:W.iteration,toolCallId:W.toolCallId,toolName:W.toolName,inputJson:JSON.stringify(W.input??null),policy:W.policy},Q))})}function PY($,W,Z){let Q=$.pendingApprovals.get(W);if(!Q)return;return $.pendingApprovals.delete(W),Q.resolve(Z),{sessionId:Q.sessionId}}function SY($,W,Z){let Q=0;for(let[J,j]of[...$.pendingApprovals.entries()]){if(!W({approvalId:J,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(J),j.resolve({approved:!1,reason:Z}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Z},j.sessionId)),Q+=1}return Q}async function y_($,W){let Z=typeof W.payload?.approvalId==="string"?W.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Z))return h(W,"approval_not_found",`Unknown approval: ${Z}`);let J=typeof W.payload?.reason==="string"?W.payload.reason:W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)&&typeof W.payload.payload.reason==="string"?W.payload.payload.reason:void 0,j=W.payload?.approved===!0,X=PY($,Z,{approved:j,reason:J});if(!X)return h(W,"approval_not_found",`Unknown approval: ${Z}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:j,reason:J},X.sessionId)),u(W,{approvalId:Z,approved:j})}import{createSessionId as Dm}from"@cline/shared";function Am($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var h_={debug:10,info:20,warn:30,error:40,silent:50};function Um(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function i($,W,Z={}){if(h_[$]<h_[Um()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:W,...Object.fromEntries(Object.entries(Z).map(([J,j])=>[J,Am(j)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function bY($,W){let Z=W instanceof Error?W.stack||W.message:String(W);i("error",$,{error:Z})}async function k_($,W,Z,Q,J,j){let X=Dm("capreq_"),Y=performance.now();return i("info","capability.request.start",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J}),await new Promise((V,B)=>{$.pendingCapabilityRequests.set(X,{sessionId:W,targetClientId:J,capabilityName:Z,onProgress:j,resolve:(H)=>{if(i(H.ok?"info":"warn","capability.request.end",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-Y)}),!H.ok){B(Error(H.error||`Capability ${Z} was rejected by ${J}.`));return}V(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:X,targetClientId:J,capabilityName:Z,payload:Q},W)),i("info","capability.request.published",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J})})}function I_($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);if((W.clientId?.trim()||"")!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{};return Q.onProgress?.(j),u(W,{requestId:Z})}function t$($,W,Z){let Q=0;for(let[J,j]of[...$.pendingCapabilityRequests.entries()]){if(!W({requestId:J,...j}))continue;$.pendingCapabilityRequests.delete(J),i("warn","capability.request.cancelled",{requestId:J,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Z}),j.resolve({ok:!1,error:Z}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Z},j.sessionId)),Q+=1}return Q}async function x_($,W){let Z=typeof W.payload?.sessionId==="string"?W.payload.sessionId.trim():W.sessionId?.trim()||"",Q=typeof W.payload?.capabilityName==="string"?W.payload.capabilityName.trim():"",J=typeof W.payload?.targetClientId==="string"?W.payload.targetClientId.trim():"";if(!Z||!Q||!J)return h(W,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{},X=await $.requestCapability(Z,Q,j,J);return u(W,X)}catch(j){return h(W,"capability_request_failed",j instanceof Error?j.message:String(j))}}function g_($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);let J=W.clientId?.trim()||"";if(J!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(Z);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:void 0,X=typeof W.payload?.error==="string"?W.payload.error:void 0,Y=W.payload?.ok===!0;return i(Y?"info":"warn","capability.respond",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,error:X}),Q.resolve({ok:Y,payload:j,error:X}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,payload:j,error:X},Q.sessionId)),u(W,{requestId:Z,ok:Y})}import{createSessionId as _m}from"@cline/shared";function m_($,W){let Z=W.payload,Q=Z?.clientId?.trim()||W.clientId?.trim()||_m("client_");return $.clients.set(Q,{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,actorKind:Z?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Z?.transport??"native",capabilities:Z?.capabilities??[],metadata:Z?.metadata,workspaceContext:Z?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,connectedAt:Date.now()})),u(W,{clientId:Q})}function v_($,W){let Z=W.clientId?.trim(),Q=Z?$.clients.get(Z):void 0;if(!Z||!Q)return h(W,"client_not_found","Client is not registered with this hub.");let J=s6(W.payload?.metadata);if(Q.lastSeenAt=Date.now(),J)Q.metadata=JSON.parse(JSON.stringify(J));return u(W)}function c_($,W,Z){let Q=W.clientId?.trim();if(Q)$.clients.delete(Q),Z(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return u(W)}function u_($,W){return u(W,{clients:[...$.clients.values()]})}R0();import{existsSync as p_,mkdirSync as fm,readdirSync as Lm,readFileSync as Tm,rmSync as Om,writeFileSync as zm}from"node:fs";import{dirname as qm,join as d_}from"node:path";import{CONNECTOR_PLATFORMS as Mm,connectorChannelsFromPlatforms as Rm,listConnectorCatalog as r_,shouldIncludeConnectorField as Em}from"@cline/shared";import{resolveConnectorDataDir as Nm,resolveConnectorSettingsPath as hY}from"@cline/shared/storage";var wm=1,l_={startedAt:($)=>typeof $.startedAt==="string"?$.startedAt:void 0,port:($)=>typeof $.port==="number"?$.port:void 0,baseUrl:($)=>typeof $.baseUrl==="string"?$.baseUrl:void 0,connectionMode:($)=>typeof $.connectionMode==="string"?$.connectionMode:void 0,userName:($)=>typeof $.userName==="string"?$.userName:void 0,botUsername:($)=>typeof $.botUsername==="string"?$.botUsername:void 0,applicationId:($)=>typeof $.applicationId==="string"?$.applicationId:void 0,phoneNumberId:($)=>typeof $.phoneNumberId==="string"?$.phoneNumberId:void 0},Cm={discord:{required:["userName","applicationId"],optional:["startedAt","port","baseUrl"]},telegram:{required:["botUsername"],optional:["startedAt"]},gchat:{required:["userName"],optional:["startedAt","port","baseUrl"]},linear:{required:["userName"],optional:["startedAt","port","baseUrl"]},slack:{required:["userName"],optional:["startedAt","connectionMode","port","baseUrl"]},whatsapp:{required:["userName"],optional:["startedAt","phoneNumberId","port","baseUrl"]}};function e$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function v9($){return typeof $==="string"?$.trim():void 0}function i_($){if(!p_($))return;try{let W=JSON.parse(Tm($,"utf8"));return e$(W)?W:void 0}catch{return}}function kY(){let $=i_(hY()),W=e$($?.connectors)?$.connectors:{},Z={};for(let[Q,J]of Object.entries(W)){if(!e$(J))continue;let j=v9(J.type),X=v9(J.configuredAt),Y=v9(J.updatedAt);if(!j||!X||!Y)continue;let V=M7(J.values),B=e$(J.security)?{enabled:J.security.enabled===!0,values:M7(J.security.values)}:void 0;Z[Q]={type:j,values:V,security:B,configuredAt:X,updatedAt:Y}}return{version:wm,connectors:Z}}function n_($){let W=hY();fm(qm(W),{recursive:!0}),zm(W,`${JSON.stringify($,null,2)}
743
+ `,"utf8")}function M7($){if(!e$($))return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q.trim();return W}function Pm($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function Sm($){let W=d_(Nm(),$);if(!p_(W))return[];return Lm(W).filter((Z)=>Z.endsWith(".json")&&!Z.endsWith(".threads.json")).map((Z)=>d_(W,Z))}function bm($,W,Z){let Q=W.botUsername??W.userName??W.applicationId??W.phoneNumberId??String(Z);return`${$}:${Q}`}function ym($,W){let Z=i_(W);if(!Z)return;let Q=typeof Z.pid==="number"?Z.pid:void 0,J=typeof Z.hubUrl==="string"?Z.hubUrl:typeof Z.rpcAddress==="string"?Z.rpcAddress:void 0;if(!Q||!J||!Pm(Q))return;let j=Cm[$];if(!j)return;let X={};for(let Y of j.required){let V=l_[Y](Z);if(!V||typeof V==="string"&&!V.trim())return;X[Y]=V}for(let Y of j.optional){let V=l_[Y](Z);if(V!==void 0)X[Y]=V}return{id:bm($,X,Q),type:$,pid:Q,hubUrl:J,...X}}function hm(){let $=[];for(let{name:W}of r_())for(let Z of Sm(W)){let Q=ym(W,Z);if(Q)$.push(Q)}return $.sort((W,Z)=>{if(W.type!==Z.type)return W.type.localeCompare(Z.type);let Q=W.botUsername??W.userName??"",J=Z.botUsername??Z.userName??"";return Q.localeCompare(J)})}function km(){let $=kY();return Object.entries($.connectors).map(([W,Z])=>({id:W,type:Z.type,configuredAt:Z.configuredAt,updatedAt:Z.updatedAt})).sort((W,Z)=>W.type.localeCompare(Z.type))}function IY(){return{available:Rm(),active:hm(),configured:km()}}function Im($,W){if($.required&&!W[$.flag]?.trim())throw Error(`${$.label} is required`)}function xm($,W){let Z={};for(let J of $.fields)Z[J.flag]=W[J.flag]??J.initialValue??"";let Q={};for(let J of $.fields){if(!Em(J,Z))continue;Im(J,Z),Q[J.flag]=Z[J.flag]}return Q}function gm($){if(!e$($))throw Error("connector.configure payload must be an object.");let W=v9($.channel);if(!W)throw Error("channel is required");let Z=Mm.find((K)=>K.id===W);if(!Z)throw Error(`unknown connector channel: ${W}`);if(!new Set(r_().map((K)=>K.name)).has(Z.id))throw Error(`connector channel is not available: ${W}`);let J=M7($.values),j=xm(Z,J),X=e$($.security)?$.security:{},Y=X.enabled===!0,V=M7(X.values);if(Y&&Z.security)for(let K of Z.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let B=kY(),H=new Date().toISOString(),G=B.connectors[W];return B.connectors[W]={type:W,values:j,security:Y?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??H,updatedAt:H},n_(B),IY()}function mm($){if(!e$($))throw Error("connector.delete_config payload must be an object.");let W=v9($.channel);if(!W)throw Error("channel is required");let Z=kY();if(delete Z.connectors[W],Object.keys(Z.connectors).length>0)n_(Z);else Om(hY(),{force:!0});return IY()}function vm($){return $==="connector.configure"||$==="connector.delete_config"}function yY($,W,Z){if(!vm(W.command))return;T8($.telemetry,{ulid:W.sessionId??W.requestId??"hub",tool:W.command,success:Z})}async function a_($,W){try{if(W.command==="connector.channels")return u(W,IY());if(W.command==="connector.configure"){let Z=gm(W.payload);return yY($,W,!0),u(W,Z)}if(W.command==="connector.delete_config"){let Z=mm(W.payload);return yY($,W,!0),u(W,Z)}return h(W,"unsupported_connector_command",`unsupported connector command: ${W.command}`)}catch(Z){return yY($,W,!1),h(W,"connector_command_failed",Z instanceof Error?Z.message:String(Z))}}var cm=30000;function um($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function dm($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function lm($,W,Z){let Q=Z instanceof Error&&Z.message.trim()?Z.message:`Unknown session: ${W}`;return h($,X2,Q)}function pm($){return $?$:void 0}function rm($){let W=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(W&&Number.isFinite(W)&&W>0)return Math.floor(W);let Z=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z*1000);return}async function im($,W,Z,Q){let J=performance.now(),j=!1,X={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z.sessionId,timeoutMs:Q},Y=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-J);i("warn","run.heartbeat",{...X,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:W.requestId,elapsedMs:H,...Q?{timeoutMs:Q}:{}},Z.sessionId))},cm),V=$.sessionHost.runTurn(Z);V.then((H)=>{if(!j)return;i("warn","run.late_end",{...X,elapsedMs:Math.round(performance.now()-J),finishReason:H?.finishReason})},(H)=>{if(!j)return;i("error","run.late_error",{...X,elapsedMs:Math.round(performance.now()-J),error:H})});let B;try{if(!Q)return await V;return await Promise.race([V,new Promise((H,G)=>{B=setTimeout(()=>{let K=`Hub run ${W.command} timed out after ${Q}ms.`;j=!0,clearInterval(Y),G(Error(K)),i("error","run.timeout",{...X,elapsedMs:Math.round(performance.now()-J)}),SY($,(F)=>F.sessionId===Z.sessionId,K),t$($,(F)=>F.sessionId===Z.sessionId,K),$.sessionHost.abort(Z.sessionId,K).catch((F)=>{i("error","run.timeout_abort_failed",{...X,error:F})})},Q)})])}finally{if(j=!0,clearInterval(Y),B)clearTimeout(B)}}async function o_($,W){let Z=S0(W),Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!J.trim())return h(W,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Z));let j=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,X=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,Y=rm(Q);$.suppressNextTerminalEventBySession.set(Z,"run.start.reply");let V;try{V=await im($,W,{sessionId:Z,prompt:J,mode:pm(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:X,timeoutMs:Y},Y)}catch(H){if($.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z);if(p1(H))return lm(W,Z,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Z)),H}if(V){let H=await u0($,Z),G=dm(V);if($.publish($.buildEvent(um(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...H?{snapshot:H}:{}},Z)),$.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z)}else $.suppressNextTerminalEventBySession.delete(Z);let B=await u0($,Z);return u(W,V||B?{...V?{result:V}:{},...B?{snapshot:B}:{}}:void 0)}async function s_($,W){let Z=S0(W),Q=typeof W.payload?.reason==="string"?W.payload.reason:"Run was aborted before pending approval or capability request was resolved.";SY($,(J)=>J.sessionId===Z,Q);try{await $.sessionHost.abort(Z,W.payload?.reason)}catch(J){i("warn","run.abort_failed",{command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z,error:J})}finally{t$($,(J)=>J.sessionId===Z,Q)}return u(W,{applied:!0})}async function t_($,W){let Z=m6(W.payload?.payload);if(!Z)return h(W,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Z),u(W,{applied:!0})}async function e_($,W){switch(W.type){case"chunk":return;case"agent_event":await nm($,W);return;case"hook":if(W.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:W.payload.toolName},W.payload.sessionId));else if(W.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:W.payload.toolName},W.payload.sessionId));return;case"team_progress":{let Z={type:"team_progress_projection",version:1,sessionId:W.payload.sessionId,summary:W.payload.summary,lastEvent:W.payload.lifecycle};$.publish($.buildEvent("team.progress",Z,W.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:W.payload.sessionId,prompts:W.payload.prompts},W.payload.sessionId));return;case"pending_prompt_submitted":{let Z={id:W.payload.id,prompt:W.payload.prompt,delivery:W.payload.delivery,attachmentCount:W.payload.attachmentCount,userImages:W.payload.userImages,userFiles:W.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:W.payload.sessionId,prompt:Z},W.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:W.payload.sessionId,snapshot:W.payload.snapshot},W.payload.sessionId));return;case"status":{let[Z,Q]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(Z)$.publish($.buildEvent("session.updated",{session:Z,...Q?{snapshot:Q}:{}},W.payload.sessionId));return}case"ended":await am($,W);return;default:return}}async function nm($,W){let{sessionId:Z,event:Q}=W.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},Z));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},Z));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},Z));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Z));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},Z));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},Z));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},Z));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},Z));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},Z));break}return}if(Q.type==="notice"){$.publish($.buildEvent("session.notice",{sessionId:Z,message:Q.message,noticeType:Q.noticeType,...Q.displayRole?{displayRole:Q.displayRole}:{},...Q.reason?{reason:Q.reason}:{},...Q.metadata?{metadata:Q.metadata}:{},agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Z)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Z,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},Z))}async function am($,W){let Z=$.suppressNextTerminalEventBySession.get(W.payload.sessionId),Q=Z===W.payload.reason||Z==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(W.payload.sessionId);let[J,j]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(W.payload.reason==="completed"){let X=await S_(J);$.publish($.buildEvent("ui.notify",X,W.payload.sessionId))}if(Q)return;$.publish($.buildEvent(W.payload.reason==="aborted"?"run.aborted":W.payload.reason==="error"||W.payload.reason==="failed"?"run.failed":"run.completed",{reason:W.payload.reason,...j?{snapshot:j}:{}},W.payload.sessionId))}import{createSessionId as Qf,parseRuntimeConfigExtensions as Jf}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as d20,HUB_COMPACTION_CAPABILITY as l20,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as p20,HUB_HOOK_CAPABILITY_PREFIX as r20,HUB_MISTAKE_LIMIT_CAPABILITY as i20,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as n20,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as a20,isHubToolExecutorName as om}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as W80,HUB_COMPACTION_CAPABILITY as Z80,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Q80,HUB_HOOK_CAPABILITY_PREFIX as J80,HUB_MISTAKE_LIMIT_CAPABILITY as j80,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as X80,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Y80}from"@cline/shared";var sm=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function G8($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function tm($,W){let Z=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=G8($.inputSchema);if(!Z||!Q||!j||!J||W.has(J))return;return W.add(J),{kind:"tool",capabilityName:J,name:Z,description:Q,inputSchema:j,...G8($.lifecycle)?{lifecycle:G8($.lifecycle)}:{}}}function gY($){if(!Array.isArray($))return[];let W=[],Z=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let J=Q,j=J.kind,X=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!X||Z.has(X))continue;if(j==="tool"){let Y=tm(J,Z);if(Y)W.push(Y);continue}if(j==="toolExecutor"){let Y=J.executor;if(!om(Y))continue;Z.add(X),W.push({kind:"toolExecutor",capabilityName:X,executor:Y});continue}if(j==="hook"){let Y=typeof J.name==="string"?J.name.trim():"";if(!Y)continue;Z.add(X),W.push({kind:"hook",capabilityName:X,name:Y});continue}if(j==="compaction"){Z.add(X),W.push({kind:"compaction",capabilityName:X,...G8(J.config)?{config:G8(J.config)}:{}});continue}if(j==="checkpoint"){Z.add(X),W.push({kind:"checkpoint",capabilityName:X,...G8(J.config)?{config:G8(J.config)}:{}});continue}if(j==="mistakeLimit"){Z.add(X),W.push({kind:"mistakeLimit",capabilityName:X});continue}if(j==="userInstructionService")Z.add(X),W.push({kind:"userInstructionService",capabilityName:X})}return W}function Wf($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W[iW];return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:W&&Object.keys(W).length>0?W:void 0}}function em($){return Object.hasOwn($,"update")?$.update:$}function c9($){return $.trim().replace(/^\/+/,"").toLowerCase()}function $v($){let W=($??[]).map(c9).filter(Boolean);return W.length>0?new Set(W):void 0}function Wv($,W,Z){if(!Z)return!0;let Q=c9($),J=c9(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function xY($,W){let Z=$v(W);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>Wv(Q.id,Q.name,Z))}function $f($,W){let Z=async(Q,J)=>{let j=c9(Q),Y=xY($,W).filter((K)=>K.id===j||c9(K.name)===j||K.id.endsWith(`:${j}`)).filter((K)=>!K.disabled);if(Y.length!==1)return Y.length>1?`Skill "${Q}" is ambiguous. Use one of: ${Y.map((K)=>K.id).join(", ")}`:`Skill "${Q}" not found.`;let V=Y[0].skill,B=J?.trim(),H=B?`
744
744
  <command-args>${B}</command-args>`:"",G=V.description?.trim()?`Description: ${V.description.trim()}
745
745
 
746
746
  `:"";return`<command-name>${V.name}</command-name>${H}
747
747
  <command-instructions>
748
748
  ${G}${V.instructions}
749
- </command-instructions>`};return Object.defineProperty(Z,"configuredSkills",{get:()=>EY($,W).map(({skill:Q,...J})=>J),enumerable:!0}),Z}function rm($,W,Z,Q){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let X=await Q($,Z.capabilityName,{},W);if(X?.snapshot)J=X.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(X)=>[...J.records[X]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(X)=>{if(!X.startsWith("/")||X.length<2)return X;let V=X.match(/^\/(\S+)/)?.[1];if(!V)return X;let B=J.runtimeCommands.find((H)=>H.name===V);return B?`${B.instructions}${X.slice(V.length+1)}`:X},hasConfiguredSkills:(X)=>EY(J,X).some((Y)=>!Y.disabled),createSkillsExecutor:(X)=>nD(J,X),createExtension:(X)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[X.includeRules?"rules":void 0,X.registerSkillsTool?"tools":void 0,X.includeSkills||X.includeWorkflows?"commands":void 0].filter((Y)=>Boolean(Y))},setup(Y){if(X.includeRules)Y.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>F8(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(X.registerSkillsTool)Y.registerTool(T2(nD(J,X.allowedSkillNames)));for(let V of J.runtimeCommands.filter((B)=>B.kind==="skill"&&X.includeSkills||B.kind==="workflow"&&X.includeWorkflows))Y.registerCommand({name:V.name,description:V.description,handler:(B)=>{let H=B.trim();return H?`${V.instructions}
749
+ </command-instructions>`};return Object.defineProperty(Z,"configuredSkills",{get:()=>xY($,W).map(({skill:Q,...J})=>J),enumerable:!0}),Z}function Zv($,W,Z,Q){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let X=await Q($,Z.capabilityName,{},W);if(X?.snapshot)J=X.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(X)=>[...J.records[X]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(X)=>{if(!X.startsWith("/")||X.length<2)return X;let V=X.match(/^\/(\S+)/)?.[1];if(!V)return X;let B=J.runtimeCommands.find((H)=>H.name===V);return B?`${B.instructions}${X.slice(V.length+1)}`:X},hasConfiguredSkills:(X)=>xY(J,X).some((Y)=>!Y.disabled),createSkillsExecutor:(X)=>$f(J,X),createExtension:(X)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[X.includeRules?"rules":void 0,X.registerSkillsTool?"tools":void 0,X.includeSkills||X.includeWorkflows?"commands":void 0].filter((Y)=>Boolean(Y))},setup(Y){if(X.includeRules)Y.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>U8(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(X.registerSkillsTool)Y.registerTool(O2($f(J,X.allowedSkillNames)));for(let V of J.runtimeCommands.filter((B)=>B.kind==="skill"&&X.includeSkills||B.kind==="workflow"&&X.includeWorkflows))Y.registerCommand({name:V.name,description:V.description,handler:(B)=>{let H=B.trim();return H?`${V.instructions}
750
750
 
751
- ${H}`:V.instructions}})}})}}function im($,W,Z,Q){let J=Z.map((j)=>[j.executor,async(...X)=>{let Y=X.at(-1),V=X.slice(0,-1);return(await Q($,j.capabilityName,{executor:j.executor,args:V,context:aD(Y)},W))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function nm($,W,Z,Q){if(Z.length===0)return;return Z.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(j,X){return(await Q($,J.capabilityName,{toolName:J.name,input:j,context:aD(X)},W,X.emitUpdate?(V)=>{X.emitUpdate?.(dm(V))}:void 0))?.result}}))}function am($,W,Z,Q){let J=new Map(Z.map((X)=>[X.name,X])),j={};for(let X of cm){let Y=J.get(X);if(!Y)continue;j[X]=async(V)=>{return(await Q($,Y.capabilityName,{context:V},W))?.control}}return Object.keys(j).length>0?j:void 0}function CY($){let W=$.contributions.filter((V)=>V.kind==="toolExecutor"),Z=$.contributions.filter((V)=>V.kind==="tool"),Q=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),j=$.contributions.find((V)=>V.kind==="checkpoint"),X=$.contributions.find((V)=>V.kind==="mistakeLimit"),Y=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:im($.sessionId,$.targetClientId,W,$.requestCapability),localRuntime:{...Q.length>0?{hooks:am($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...Z.length>0?{extraTools:nm($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}:{},...Y?{userInstructionService:rm($.sessionId,$.targetClientId,Y,$.requestCapability)}:{}}}}var oD="hubCapabilityOwnerClientId";function T7($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function om($){if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$===null)return $;return}function sm($){let W=a6($)??{},Z={},Q=T7(W.providerId);if(Q)Z.providerId=Q;let J=T7(W.modelId);if(J)Z.modelId=J;let j=T7(W.apiKey);if(j!==void 0)Z.apiKey=j;let X=T7(W.baseUrl);if(X!==void 0)Z.baseUrl=X;if(W.headers&&typeof W.headers==="object")Z.headers=W.headers;if(W.providerConfig&&typeof W.providerConfig==="object")Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"thinking")){if(typeof W.thinking==="boolean"||W.thinking===null)Z.thinking=W.thinking}if(Object.hasOwn(W,"reasoningEffort")){let Y=om(W.reasoningEffort);if(Y!==void 0)Z.reasoningEffort=Y}if(Object.hasOwn(W,"thinkingBudgetTokens")){if(typeof W.thinkingBudgetTokens==="number"&&Number.isFinite(W.thinkingBudgetTokens)&&W.thinkingBudgetTokens>0)Z.thinkingBudgetTokens=Math.trunc(W.thinkingBudgetTokens);else if(W.thinkingBudgetTokens===null)Z.thinkingBudgetTokens=null}return E2(Z)}function tm($,W){return $.sessionState.get(W)?.createdByClientId}function em($){if(!$||!(oD in $))return $;let W={...$};return delete W[oD],W}function eD($){let W=tm($.ctx,$.sessionId);if(!W)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} has no owner`);if(W!==$.clientId)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} is owned by ${W}`);return}async function $_($,W,Z){let Q=performance.now(),J={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:W.sessionId};i("info","session.create.begin",J);let j=W.payload&&typeof W.payload==="object"?W.payload:{},X=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},Y=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,V=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{},B=G1(j.initialCompactionState);if(typeof Y?.mode==="string")X.mode=Y.mode;else if(typeof V.mode==="string")X.mode=V.mode;if(typeof Y?.systemPrompt==="string")X.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")X.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)X.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)X.checkpointEnabled=!0;let H=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},G=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!G)return i("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(W,"invalid_session_create","session.create requires workspaceRoot or cwd");let K=W.clientId?.trim()||"hub-client",F=wY(V.clientContributions);i("info","session.create.contributions_parsed",{...J,clientId:K,workspaceRoot:G,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:F.length});let f=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||sD(),U=tD(V.configExtensions);i("info","session.create.runtime_build.begin",{...J,sessionId:f,configExtensionCount:U?.length??0});let _=CY({sessionId:f,targetClientId:K,contributions:F,sessionConfig:Y,requestCapability:$.requestCapability});i("info","session.create.start_session.begin",{...J,sessionId:f,provider:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),model:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub")});let D=await $.sessionHost.startSession({source:typeof X.source==="string"?X.source:void 0,interactive:X.interactive!==!1,sessionMetadata:Object.keys(X).length>0?X:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,initialCompactionState:B,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,..._.localRuntime},capabilities:{toolExecutors:_.toolExecutors,requestToolApproval:Z},config:{...Y??{},sessionId:f,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),modelId:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub"),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:Y?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():G),workspaceRoot:Y?.workspaceRoot??G,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 X.teamName==="string"?X.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});i("info","session.create.start_session.end",{...J,sessionId:D.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!D.result}),_Y($,D.sessionId,K,"creator",{interactive:X.interactive!==!1}),i("info","session.create.read_records.begin",{...J,sessionId:D.sessionId});let[M,O]=await Promise.all([S0($,D.sessionId),u0($,D.sessionId)]);if(i("info","session.create.read_records.end",{...J,sessionId:D.sessionId,hasSession:!!M,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Q)}),M)$.publish($.buildEvent("session.created",{session:M,...O?{snapshot:O}:{}},D.sessionId));return i("info","session.create.reply",{...J,sessionId:D.sessionId,elapsedMs:Math.round(performance.now()-Q)}),u(W,{session:M,...O?{snapshot:O}:{}})}async function W_($,W,Z){let Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.sessionId==="string"?Q.sessionId.trim():W.sessionId?.trim()||"",j=Q.checkpointRunCount;if(!J)return h(W,"invalid_restore","session.restore requires a session id");let X=Q.restore&&typeof Q.restore==="object"?Q.restore:{},Y=X.messages!==!1;if(typeof j!=="number")return h(W,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(Y&&!V)return h(W,"invalid_restore","sessionConfig is required when restore.messages is true");let B=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},H=G1(Q.initialCompactionState),G=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof V?.mode==="string")G.mode=V.mode;else if(typeof B.mode==="string")G.mode=B.mode;if(typeof V?.systemPrompt==="string")G.systemPrompt=V.systemPrompt;else if(typeof B.systemPrompt==="string")G.systemPrompt=B.systemPrompt;if(V?.checkpoint?.enabled===!0)G.checkpointEnabled=!0;else if(B.checkpointEnabled===!0)G.checkpointEnabled=!0;let K=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},F=W.clientId?.trim()||"hub-client",A=wY(B.clientContributions),U=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||sD(),_=tD(B.configExtensions),D=CY({sessionId:U,targetClientId:F,contributions:A,sessionConfig:V,requestCapability:$.requestCapability}),O=await new a$().restoreCheckpoint({sessionId:J,checkpointRunCount:j,restore:{messages:X.messages,workspace:X.workspace,omitCheckpointMessageFromSession:X.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)G.checkpoint=N.restoredCheckpointMetadata;let p=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof G.source==="string"?G.source:void 0,interactive:G.interactive!==!1,sessionMetadata:{...G,restoredFromSessionId:J,restoredCheckpointRunCount:j},initialMessages:N.initialMessages,initialCompactionState:H,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:_,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Z},config:{...V??{},sessionId:U,providerId:V?.providerId??(typeof K.provider==="string"?K.provider:N.sourceSession.provider),modelId:V?.modelId??(typeof K.model==="string"?K.model:N.sourceSession.model),apiKey:V?.apiKey??(typeof K.apiKey==="string"?K.apiKey:""),cwd:V?.cwd??N.plan.cwd,workspaceRoot:V?.workspaceRoot??p,systemPrompt:V?.systemPrompt??(typeof B.systemPrompt==="string"?B.systemPrompt:""),mode:V?.mode??(B.mode==="plan"||B.mode==="yolo"?B.mode:"act"),maxIterations:V?.maxIterations??(typeof B.maxIterations==="number"?B.maxIterations:void 0),enableTools:V?.enableTools??B.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??B.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??B.enableTeams!==!1,checkpoint:V?.checkpoint??(B.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof G.teamName==="string"?G.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):B.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!Y)return u(W,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return h(W,"restore_failed","Checkpoint restore did not start a session");_Y($,T.sessionId,F,"creator",{interactive:G.interactive!==!1});let[L,C]=await Promise.all([S0($,T.sessionId),u0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...C?{snapshot:C}:{}},T.sessionId));return u(W,{session:L,...C?{snapshot:C}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(V){if(V instanceof c0)return h(W,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(W,"restore_failed",V instanceof Error?V.message:String(V))}}async function Z_($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_attach","session.attach requires a session id");let Q=await S0($,Z);if(!Q)return h(W,"session_not_found",`Unknown session: ${Z}`);ND($,Z,W.clientId?.trim()||"hub-client","participant");let J=await S0($,Z);return $.publish($.buildEvent("session.attached",{session:J??Q},Z)),u(W,{session:J??Q})}async function Q_($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_detach","session.detach requires a session id");let Q=W.clientId?.trim()||"hub-client",J=$.sessionState.get(Z);if(J){if(J.participants.delete(Q),J.createdByClientId===Q)J.createdByClientId=void 0;if(J.participants.size===0)$.sessionState.delete(Z)}s$($,(Y)=>Y.sessionId===Z&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[j,X]=await Promise.all([S0($,Z),u0($,Z)]);return $.publish($.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},Z)),u(W)}async function J_($,W){let Z=P0(W),Q=W.payload?.includeSnapshot===!0,[J,j]=await Promise.all([S0($,Z),Q?u0($,Z):Promise.resolve(void 0)]);return J?u(W,{session:J,...j?{snapshot:j}:{}}):h(W,"session_not_found",`Unknown session: ${Z}`)}async function j_($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_id","session.messages requires a session id");if(!await S0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=await $.sessionHost.readSessionMessages(Z);return u(W,{sessionId:Z,messages:J})}async function X_($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.get requires a session id");if(!await S0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=W.clientId?.trim()||"hub-client",j=eD({sessionId:Z,ctx:$,clientId:J,envelope:W});if(j)return j;let X=await $.sessionHost.readSessionCompactionState(Z);return u(W,{sessionId:Z,state:X})}async function Y_($,W){let Z=typeof W.payload?.limit==="number"?W.payload.limit:200,J=(await $.sessionHost.listSessions(Z)).map((j)=>_7(j,$.sessionState.get(j.sessionId)));return u(W,{sessions:J})}async function V_($,W){let Z=P0(W),Q=em(a6(W.payload?.metadata)),J=await $.sessionHost.updateSession(Z,{metadata:Q}),[j,X]=await Promise.all([S0($,Z),u0($,Z)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...X?{snapshot:X}:{}},Z));return{version:W.version,requestId:W.requestId,ok:J.updated,payload:{updated:J.updated,session:j,...X?{snapshot:X}:{}}}}async function B_($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_update_connection","session.update_connection requires a session id");let Q=$.sessionHost.updateSessionConnection;if(!Q)return h(W,"unsupported_session_update_connection","runtime host does not support session connection updates");let J=a6(W.payload),j=sm(J?.updates);return await Q.call($.sessionHost,Z,j),u(W,{sessionId:Z,updated:!0})}async function H_($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.update requires a session id");let Q=W.clientId?.trim()||"hub-client",J=await S0($,Z);if(!J)return h(W,"session_not_found",`Unknown session: ${Z}`);let j=eD({sessionId:Z,ctx:$,clientId:Q,envelope:W});if(j)return j;let X=W.payload&&typeof W.payload==="object"?W.payload:{},Y=G1(X.state);if(!Y)return h(W,"invalid_compaction_state","session.compaction.update requires a valid compaction state");let V=await $.sessionHost.updateSessionCompactionState(Z,Y),[B,H]=V.updated?await Promise.all([S0($,Z),u0($,Z)]):[J,void 0];if(V.updated)$.publish($.buildEvent("session.updated",{session:B??J,...H?{snapshot:H}:{}},Z));return{version:W.version,requestId:W.requestId,ok:!0,payload:{updated:V.updated,session:B??J,...H?{snapshot:H}:{}}}}async function G_($,W){let Z=P0(W),Q=await $.sessionHost.deleteSession(Z);return $.sessionState.delete(Z),u(W,{deleted:Q})}async function K_($,W){let Z=P0(W),Q=$.sessionHost.pendingPrompts;if(!Q)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await Q.list({sessionId:Z});return u(W,{sessionId:Z,prompts:J})}async function F_($,W){let Z=P0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=typeof W.payload?.prompt==="string"?W.payload.prompt:void 0,j=W.payload?.delivery==="queue"||W.payload?.delivery==="steer"?W.payload.delivery:void 0,X=$.sessionHost.pendingPrompts;if(!X)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let Y=await X.update({sessionId:Z,promptId:Q,prompt:J,delivery:j});return u(W,Y)}async function A_($,W){let Z=P0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await J.delete({sessionId:Z,promptId:Q});return u(W,j)}function U_($){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 Wv=new Set(["skills","workflows","rules","tools","mcp"]);function PY($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function hW($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="string")throw Error(`settings payload '${W}' must be a string.`);return Z}function Zv($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="boolean")throw Error(`settings payload '${W}' must be a boolean.`);return Z}function f_($){if($===void 0)return{};if(!PY($))throw Error("settings.list payload must be an object.");return{cwd:hW($,"cwd"),workspaceRoot:hW($,"workspaceRoot"),availabilityContext:PY($.availabilityContext)?$.availabilityContext:void 0}}function Qv($){if(!PY($))throw Error("settings.toggle payload must be an object.");let{type:W}=$;if(typeof W!=="string"||!Wv.has(W))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...f_($),type:W,id:hW($,"id"),path:hW($,"path"),name:hW($,"name"),enabled:Zv($,"enabled")}}class n6{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=$v("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new b1({sessionService:new S1(new C1),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:(W)=>this.publish(W),buildEvent:V8,requestCapability:(W,Z,Q,J,j)=>CD(this.ctx,W,Z,Q,J,j)},this.schedules=new f8({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(W,Z)=>{let Q=W==="schedule.execution.completed"?"schedule.execution_completed":W==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(V8(Q,Z&&typeof Z==="object"?Z:void 0))}}),this.scheduleCommands=new K8(this.schedules),this.settings=$.settingsService??new d$,$.cronOptions)this.cronService=new e5({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((W)=>{iD(this.ctx,W).catch((Z)=>{zY("session event handling failed",Z),O7(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Z,severity:"error",handled:!0,context:{eventType:W.type,sessionId:W.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())TY(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(s$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let W=await this.dispatchCommand($);return this.captureFailedReply($,W),W}catch(W){throw O7(this.options.telemetry,{component:"core",operation:"hub.command",error:W,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),W}}async dispatchCommand($){switch($.command){case"client.register":return yD(this.ctx,$);case"client.update":return hD(this.ctx,$);case"client.unregister":return kD(this.ctx,$,(W)=>{this.listeners.delete(W),this.detachClientFromSessions(W)});case"client.list":return ID(this.ctx,$);case"session.create":return await $_(this.ctx,$,(W)=>LY(this.ctx,W));case"session.restore":return await W_(this.ctx,$,(W)=>LY(this.ctx,W));case"session.attach":return await Z_(this.ctx,$);case"session.detach":return await Q_(this.ctx,$);case"session.get":return await J_(this.ctx,$);case"session.messages":return await j_(this.ctx,$);case"session.compaction.get":return await X_(this.ctx,$);case"session.list":return await Y_(this.ctx,$);case"session.update":return await V_(this.ctx,$);case"session.update_connection":return await B_(this.ctx,$);case"session.compaction.update":return await H_(this.ctx,$);case"session.pending_prompts":return await K_(this.ctx,$);case"session.update_pending_prompt":return await F_(this.ctx,$);case"session.remove_pending_prompt":return await A_(this.ctx,$);case"session.delete":return await G_(this.ctx,$);case"session.hook":return await rD(this.ctx,$);case"run.start":case"session.send_input":return await lD(this.ctx,$);case"run.abort":return await pD(this.ctx,$);case"capability.request":return await SD(this.ctx,$);case"approval.respond":return await ED(this.ctx,$);case"capability.respond":return bD(this.ctx,$);case"capability.progress":return PD(this.ctx,$);case"ui.notify":return this.publish(V8("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(V8("ui.show_window",$.payload??{})),u($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"connector.channels":case"connector.configure":case"connector.delete_config":return await dD(this.ctx,$);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 W=await this.scheduleCommands.handleCommand($);if(W.ok){let Z=U_($.command);if(Z)this.publish(V8(Z,W.payload))}return W}}}captureFailedReply($,W){if(W.ok||!W.error||!Jv(W.error.code))return;O7(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(W.error.message),severity:W.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:W.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let W=await this.settings.list(f_($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:W instanceof Error?W.message:String(W)}}}}async handleSettingsToggle($){try{let W=await this.settings.toggle(Qv($.payload));return this.publish(V8("settings.changed",{types:W.changedTypes,snapshot:W.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W.snapshot,changedTypes:W.changedTypes}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:W instanceof Error?W.message:String(W)}}}}subscribe($,W,Z){let Q=this.listeners.get($)??new Set,J={sessionId:Z?.sessionId,listener:W};return Q.add(J),this.listeners.set($,Q),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(J),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[W,Z]of this.sessionState.entries()){if(Z.participants.delete($),Z.createdByClientId===$)Z.createdByClientId=void 0;if(Z.participants.size===0)this.sessionState.delete(W)}s$(this.ctx,(W)=>W.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let W of this.listeners.values())for(let Z of W){if(Z.sessionId&&Z.sessionId!==$.sessionId)continue;try{Z.listener($)}catch(Q){zY(`listener threw while publishing ${$.event}`,Q),O7(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Jv($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as Vv}from"node:crypto";import Bv from"node:http";import Hv from"node:net";import{URL as hY}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as L_,HUB_CAPABILITIES as Gv,isHubProtocolCompatible as Kv,MAX_CLIENT_HUB_PROTOCOL_VERSION as T_,MIN_CLIENT_HUB_PROTOCOL_VERSION as O_}from"@cline/shared";import{WebSocketServer as Fv}from"ws";import{captureSdkError as D_,HUB_COMMAND_SLOW_LOG_MS as jv,resolveHubCommandTimeoutMs as Xv,safeJsonParse as Yv}from"@cline/shared";function SY($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function __($,W,Z){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:W,message:Z}}}class wW{transport;telemetry;constructor($,W){this.transport=$;this.telemetry=W}attach($){let W=new Map,Z=new Set,Q=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(B){console.error(`[hub] failed to send websocket frame: ${B instanceof Error?B.stack||B.message:String(B)}`)}},j=(V)=>{J({kind:"event",envelope:V})},X=async(V)=>{try{let B=JSON.parse(V.data);switch(B.kind){case"command":{let H=performance.now(),G=!1,K=SY(B);i("info","command.start",K);let F=setTimeout(()=>{if(G)return;i("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-H)})},jv),A=this.transport.command(B.envelope);A.then((O)=>{if(!G)return;i(O.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-H),ok:O.ok,errorCode:O.error?.code,errorMessage:O.error?.message})},(O)=>{if(!G)return;i("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-H),error:O})});let f=!1,U,_,D=Xv(B.envelope.command,B.envelope.timeoutMs);try{_=D===null?await A:await Promise.race([A,new Promise((O)=>{U=setTimeout(()=>{f=!0,D_(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${B.envelope.command} did not complete within ${D}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:D}}),O(__(B,"hub_command_timeout",`Hub command ${B.envelope.command} did not complete within ${D}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${B.envelope.requestId}.`))},D)})])}catch(O){if(clearTimeout(F),U)clearTimeout(U);throw O}if(G=f,clearTimeout(F),U)clearTimeout(U);let M=Math.round(performance.now()-H);if(f)i("error","command.timeout",{...K,durationMs:M,timeoutMs:D});else i(_.ok?"info":"warn","command.end",{...K,durationMs:M,ok:_.ok,errorCode:_.error?.code,errorMessage:_.error?.message});if(B.envelope.command==="client.register"&&_.ok){let T=(B.envelope.payload??{}).clientId?.trim()||B.envelope.clientId?.trim();if(T)Z.add(T)}else if(B.envelope.command==="client.unregister"&&_.ok){let O=B.envelope.clientId?.trim();if(O)Z.delete(O)}J({kind:"reply",envelope:_});break}case"stream.subscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;if(W.has(H))break;let G=await this.transport.subscribe(B.clientId,j,{sessionId:B.sessionId});W.set(H,G);break}case"stream.unsubscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;W.get(H)?.(),W.delete(H);break}case"reply":case"event":break}}catch(B){let H=typeof V.data==="string"?Yv(V.data):void 0;if(!H||H.kind!=="command"){i("error","rejected malformed websocket frame",{error:B});return}i("error","command.error",{...SY(H),error:B}),D_(this.telemetry,{component:"core",operation:"hub.websocket_command",error:B,severity:"error",handled:!0,context:SY(H)}),J({kind:"reply",envelope:__(H,"command_failed",B instanceof Error?B.message:"Unknown hub error")})}},Y=()=>{if(Q)return;Q=!0;for(let V of W.values())V();W.clear();for(let V of Z)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Z.clear(),$.removeEventListener("message",X),$.removeEventListener("close",Y)};return $.addEventListener("message",X),$.addEventListener("close",Y),Y}}class CW{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,W,Z){return this.transport.subscribe($,W,Z)}}function Av($){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((W)=>Buffer.from(W))).toString();return String($)}function Uv($){return{send(W){$.send(W)},addEventListener(W,Z){if(W==="message"){$.on("message",(Q)=>{Z({data:Av(Q)})});return}$.on("close",Z)},removeEventListener(){}}}function fv($){try{$.write(`HTTP/1.1 400 Bad Request\r
751
+ ${H}`:V.instructions}})}})}}function Qv($,W,Z,Q){let J=Z.map((j)=>[j.executor,async(...X)=>{let Y=X.at(-1),V=X.slice(0,-1);return(await Q($,j.capabilityName,{executor:j.executor,args:V,context:Wf(Y)},W))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function Jv($,W,Z,Q){if(Z.length===0)return;return Z.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(j,X){return(await Q($,J.capabilityName,{toolName:J.name,input:j,context:Wf(X)},W,X.emitUpdate?(V)=>{X.emitUpdate?.(em(V))}:void 0))?.result}}))}function jv($,W,Z,Q){let J=new Map(Z.map((X)=>[X.name,X])),j={};for(let X of sm){let Y=J.get(X);if(!Y)continue;j[X]=async(V)=>{return(await Q($,Y.capabilityName,{context:V},W))?.control}}return Object.keys(j).length>0?j:void 0}function mY($){let W=$.contributions.filter((V)=>V.kind==="toolExecutor"),Z=$.contributions.filter((V)=>V.kind==="tool"),Q=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),j=$.contributions.find((V)=>V.kind==="checkpoint"),X=$.contributions.find((V)=>V.kind==="mistakeLimit"),Y=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:Qv($.sessionId,$.targetClientId,W,$.requestCapability),localRuntime:{...Q.length>0?{hooks:jv($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...Z.length>0?{extraTools:Jv($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}:{},...Y?{userInstructionService:Zv($.sessionId,$.targetClientId,Y,$.requestCapability)}:{}}}}var Zf="hubCapabilityOwnerClientId";function R7($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function Xv($){if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$===null)return $;return}function Yv($){let W=s6($)??{},Z={},Q=R7(W.providerId);if(Q)Z.providerId=Q;let J=R7(W.modelId);if(J)Z.modelId=J;let j=R7(W.apiKey);if(j!==void 0)Z.apiKey=j;let X=R7(W.baseUrl);if(X!==void 0)Z.baseUrl=X;if(W.headers&&typeof W.headers==="object")Z.headers=W.headers;if(W.providerConfig&&typeof W.providerConfig==="object")Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"thinking")){if(typeof W.thinking==="boolean"||W.thinking===null)Z.thinking=W.thinking}if(Object.hasOwn(W,"reasoningEffort")){let Y=Xv(W.reasoningEffort);if(Y!==void 0)Z.reasoningEffort=Y}if(Object.hasOwn(W,"thinkingBudgetTokens")){if(typeof W.thinkingBudgetTokens==="number"&&Number.isFinite(W.thinkingBudgetTokens)&&W.thinkingBudgetTokens>0)Z.thinkingBudgetTokens=Math.trunc(W.thinkingBudgetTokens);else if(W.thinkingBudgetTokens===null)Z.thinkingBudgetTokens=null}return w2(Z)}function Vv($,W){return $.sessionState.get(W)?.createdByClientId}function Bv($){if(!$||!(Zf in $))return $;let W={...$};return delete W[Zf],W}function jf($){let W=Vv($.ctx,$.sessionId);if(!W)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} has no owner`);if(W!==$.clientId)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} is owned by ${W}`);return}async function Xf($,W,Z){let Q=performance.now(),J={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:W.sessionId};i("info","session.create.begin",J);let j=W.payload&&typeof W.payload==="object"?W.payload:{},X=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},Y=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,V=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{},B=G1(j.initialCompactionState);if(typeof Y?.mode==="string")X.mode=Y.mode;else if(typeof V.mode==="string")X.mode=V.mode;if(typeof Y?.systemPrompt==="string")X.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")X.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)X.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)X.checkpointEnabled=!0;let H=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},G=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!G)return i("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(W,"invalid_session_create","session.create requires workspaceRoot or cwd");let K=W.clientId?.trim()||"hub-client",F=gY(V.clientContributions);i("info","session.create.contributions_parsed",{...J,clientId:K,workspaceRoot:G,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:F.length});let D=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||Qf(),U=Jf(V.configExtensions);i("info","session.create.runtime_build.begin",{...J,sessionId:D,configExtensionCount:U?.length??0});let f=mY({sessionId:D,targetClientId:K,contributions:F,sessionConfig:Y,requestCapability:$.requestCapability});i("info","session.create.start_session.begin",{...J,sessionId:D,provider:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),model:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub")});let _=await $.sessionHost.startSession({source:typeof X.source==="string"?X.source:void 0,interactive:X.interactive!==!1,sessionMetadata:Object.keys(X).length>0?X:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,initialCompactionState:B,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...f.localRuntime},capabilities:{toolExecutors:f.toolExecutors,requestToolApproval:Z},config:{...Y??{},sessionId:D,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),modelId:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub"),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:Y?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():G),workspaceRoot:Y?.workspaceRoot??G,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 X.teamName==="string"?X.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});i("info","session.create.start_session.end",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!_.result}),wY($,_.sessionId,K,"creator",{interactive:X.interactive!==!1}),i("info","session.create.read_records.begin",{...J,sessionId:_.sessionId});let[R,O]=await Promise.all([b0($,_.sessionId),u0($,_.sessionId)]);if(i("info","session.create.read_records.end",{...J,sessionId:_.sessionId,hasSession:!!R,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Q)}),R)$.publish($.buildEvent("session.created",{session:R,...O?{snapshot:O}:{}},_.sessionId));return i("info","session.create.reply",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q)}),u(W,{session:R,...O?{snapshot:O}:{}})}async function Yf($,W,Z){let Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.sessionId==="string"?Q.sessionId.trim():W.sessionId?.trim()||"",j=Q.checkpointRunCount;if(!J)return h(W,"invalid_restore","session.restore requires a session id");let X=Q.restore&&typeof Q.restore==="object"?Q.restore:{},Y=X.messages!==!1;if(typeof j!=="number")return h(W,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(Y&&!V)return h(W,"invalid_restore","sessionConfig is required when restore.messages is true");let B=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},H=G1(Q.initialCompactionState),G=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof V?.mode==="string")G.mode=V.mode;else if(typeof B.mode==="string")G.mode=B.mode;if(typeof V?.systemPrompt==="string")G.systemPrompt=V.systemPrompt;else if(typeof B.systemPrompt==="string")G.systemPrompt=B.systemPrompt;if(V?.checkpoint?.enabled===!0)G.checkpointEnabled=!0;else if(B.checkpointEnabled===!0)G.checkpointEnabled=!0;let K=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},F=W.clientId?.trim()||"hub-client",A=gY(B.clientContributions),U=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||Qf(),f=Jf(B.configExtensions),_=mY({sessionId:U,targetClientId:F,contributions:A,sessionConfig:V,requestCapability:$.requestCapability}),O=await new o$().restoreCheckpoint({sessionId:J,checkpointRunCount:j,restore:{messages:X.messages,workspace:X.workspace,omitCheckpointMessageFromSession:X.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(E)=>$.sessionHost.getSession(E),readMessages:(E)=>$.sessionHost.readSessionMessages(E),buildStartInput:(E)=>{if(E.restoredCheckpointMetadata)G.checkpoint=E.restoredCheckpointMetadata;let p=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():E.sourceSession.workspaceRoot||E.sourceSession.cwd;return{source:typeof G.source==="string"?G.source:void 0,interactive:G.interactive!==!1,sessionMetadata:{...G,restoredFromSessionId:J,restoredCheckpointRunCount:j},initialMessages:E.initialMessages,initialCompactionState:H,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:f,..._.localRuntime},capabilities:{toolExecutors:_.toolExecutors,requestToolApproval:Z},config:{...V??{},sessionId:U,providerId:V?.providerId??(typeof K.provider==="string"?K.provider:E.sourceSession.provider),modelId:V?.modelId??(typeof K.model==="string"?K.model:E.sourceSession.model),apiKey:V?.apiKey??(typeof K.apiKey==="string"?K.apiKey:""),cwd:V?.cwd??E.plan.cwd,workspaceRoot:V?.workspaceRoot??p,systemPrompt:V?.systemPrompt??(typeof B.systemPrompt==="string"?B.systemPrompt:""),mode:V?.mode??(B.mode==="plan"||B.mode==="yolo"?B.mode:"act"),maxIterations:V?.maxIterations??(typeof B.maxIterations==="number"?B.maxIterations:void 0),enableTools:V?.enableTools??B.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??B.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??B.enableTeams!==!1,checkpoint:V?.checkpoint??(B.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof G.teamName==="string"?G.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):B.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(E)=>$.sessionHost.startSession(E),getStartedSessionId:(E)=>E.sessionId,readRestoredSession:(E)=>$.sessionHost.getSession(E)});if(!Y)return u(W,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return h(W,"restore_failed","Checkpoint restore did not start a session");wY($,T.sessionId,F,"creator",{interactive:G.interactive!==!1});let[L,C]=await Promise.all([b0($,T.sessionId),u0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...C?{snapshot:C}:{}},T.sessionId));return u(W,{session:L,...C?{snapshot:C}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(V){if(V instanceof c0)return h(W,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(W,"restore_failed",V instanceof Error?V.message:String(V))}}async function Vf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_attach","session.attach requires a session id");let Q=await b0($,Z);if(!Q)return h(W,"session_not_found",`Unknown session: ${Z}`);b_($,Z,W.clientId?.trim()||"hub-client","participant");let J=await b0($,Z);return $.publish($.buildEvent("session.attached",{session:J??Q},Z)),u(W,{session:J??Q})}async function Bf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_detach","session.detach requires a session id");let Q=W.clientId?.trim()||"hub-client",J=$.sessionState.get(Z);if(J){if(J.participants.delete(Q),J.createdByClientId===Q)J.createdByClientId=void 0;if(J.participants.size===0)$.sessionState.delete(Z)}t$($,(Y)=>Y.sessionId===Z&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[j,X]=await Promise.all([b0($,Z),u0($,Z)]);return $.publish($.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},Z)),u(W)}async function Hf($,W){let Z=S0(W),Q=W.payload?.includeSnapshot===!0,[J,j]=await Promise.all([b0($,Z),Q?u0($,Z):Promise.resolve(void 0)]);return J?u(W,{session:J,...j?{snapshot:j}:{}}):h(W,"session_not_found",`Unknown session: ${Z}`)}async function Gf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.messages requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=await $.sessionHost.readSessionMessages(Z);return u(W,{sessionId:Z,messages:J})}async function Kf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.get requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=W.clientId?.trim()||"hub-client",j=jf({sessionId:Z,ctx:$,clientId:J,envelope:W});if(j)return j;let X=await $.sessionHost.readSessionCompactionState(Z);return u(W,{sessionId:Z,state:X})}async function Ff($,W){let Z=typeof W.payload?.limit==="number"?W.payload.limit:200,J=(await $.sessionHost.listSessions(Z)).map((j)=>q7(j,$.sessionState.get(j.sessionId)));return u(W,{sessions:J})}async function Af($,W){let Z=S0(W),Q=Bv(s6(W.payload?.metadata)),J=await $.sessionHost.updateSession(Z,{metadata:Q}),[j,X]=await Promise.all([b0($,Z),u0($,Z)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...X?{snapshot:X}:{}},Z));return{version:W.version,requestId:W.requestId,ok:J.updated,payload:{updated:J.updated,session:j,...X?{snapshot:X}:{}}}}async function Uf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_update_connection","session.update_connection requires a session id");let Q=$.sessionHost.updateSessionConnection;if(!Q)return h(W,"unsupported_session_update_connection","runtime host does not support session connection updates");let J=s6(W.payload),j=Yv(J?.updates);return await Q.call($.sessionHost,Z,j),u(W,{sessionId:Z,updated:!0})}async function Df($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.update requires a session id");let Q=W.clientId?.trim()||"hub-client",J=await b0($,Z);if(!J)return h(W,"session_not_found",`Unknown session: ${Z}`);let j=jf({sessionId:Z,ctx:$,clientId:Q,envelope:W});if(j)return j;let X=W.payload&&typeof W.payload==="object"?W.payload:{},Y=G1(X.state);if(!Y)return h(W,"invalid_compaction_state","session.compaction.update requires a valid compaction state");let V=await $.sessionHost.updateSessionCompactionState(Z,Y),[B,H]=V.updated?await Promise.all([b0($,Z),u0($,Z)]):[J,void 0];if(V.updated)$.publish($.buildEvent("session.updated",{session:B??J,...H?{snapshot:H}:{}},Z));return{version:W.version,requestId:W.requestId,ok:!0,payload:{updated:V.updated,session:B??J,...H?{snapshot:H}:{}}}}async function _f($,W){let Z=S0(W),Q=await $.sessionHost.deleteSession(Z);return $.sessionState.delete(Z),u(W,{deleted:Q})}async function ff($,W){let Z=S0(W),Q=$.sessionHost.pendingPrompts;if(!Q)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await Q.list({sessionId:Z});return u(W,{sessionId:Z,prompts:J})}async function Lf($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=typeof W.payload?.prompt==="string"?W.payload.prompt:void 0,j=W.payload?.delivery==="queue"||W.payload?.delivery==="steer"?W.payload.delivery:void 0,X=$.sessionHost.pendingPrompts;if(!X)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let Y=await X.update({sessionId:Z,promptId:Q,prompt:J,delivery:j});return u(W,Y)}async function Tf($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await J.delete({sessionId:Z,promptId:Q});return u(W,j)}function Of($){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 Gv=new Set(["skills","workflows","rules","tools","mcp"]);function vY($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function u9($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="string")throw Error(`settings payload '${W}' must be a string.`);return Z}function Kv($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="boolean")throw Error(`settings payload '${W}' must be a boolean.`);return Z}function zf($){if($===void 0)return{};if(!vY($))throw Error("settings.list payload must be an object.");return{cwd:u9($,"cwd"),workspaceRoot:u9($,"workspaceRoot"),availabilityContext:vY($.availabilityContext)?$.availabilityContext:void 0}}function Fv($){if(!vY($))throw Error("settings.toggle payload must be an object.");let{type:W}=$;if(typeof W!=="string"||!Gv.has(W))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...zf($),type:W,id:u9($,"id"),path:u9($,"path"),name:u9($,"name"),enabled:Kv($,"enabled")}}class o6{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=Hv("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new b1({sessionService:new S1(new C1),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:(W)=>this.publish(W),buildEvent:H8,requestCapability:(W,Z,Q,J,j)=>k_(this.ctx,W,Z,Q,J,j)},this.schedules=new f8({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(W,Z)=>{let Q=W==="schedule.execution.completed"?"schedule.execution_completed":W==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(H8(Q,Z&&typeof Z==="object"?Z:void 0))}}),this.scheduleCommands=new A8(this.schedules),this.settings=$.settingsService??new l$,$.cronOptions)this.cronService=new W9({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((W)=>{e_(this.ctx,W).catch((Z)=>{bY("session event handling failed",Z),E7(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Z,severity:"error",handled:!0,context:{eventType:W.type,sessionId:W.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())PY(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(t$(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 W=await this.dispatchCommand($);return this.captureFailedReply($,W),W}catch(W){throw E7(this.options.telemetry,{component:"core",operation:"hub.command",error:W,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),W}}async dispatchCommand($){switch($.command){case"client.register":return m_(this.ctx,$);case"client.update":return v_(this.ctx,$);case"client.unregister":return c_(this.ctx,$,(W)=>{this.listeners.delete(W),this.detachClientFromSessions(W)});case"client.list":return u_(this.ctx,$);case"session.create":return await Xf(this.ctx,$,(W)=>CY(this.ctx,W));case"session.restore":return await Yf(this.ctx,$,(W)=>CY(this.ctx,W));case"session.attach":return await Vf(this.ctx,$);case"session.detach":return await Bf(this.ctx,$);case"session.get":return await Hf(this.ctx,$);case"session.messages":return await Gf(this.ctx,$);case"session.compaction.get":return await Kf(this.ctx,$);case"session.list":return await Ff(this.ctx,$);case"session.update":return await Af(this.ctx,$);case"session.update_connection":return await Uf(this.ctx,$);case"session.compaction.update":return await Df(this.ctx,$);case"session.pending_prompts":return await ff(this.ctx,$);case"session.update_pending_prompt":return await Lf(this.ctx,$);case"session.remove_pending_prompt":return await Tf(this.ctx,$);case"session.delete":return await _f(this.ctx,$);case"session.hook":return await t_(this.ctx,$);case"run.start":case"session.send_input":return await o_(this.ctx,$);case"run.abort":return await s_(this.ctx,$);case"capability.request":return await x_(this.ctx,$);case"approval.respond":return await y_(this.ctx,$);case"capability.respond":return g_(this.ctx,$);case"capability.progress":return I_(this.ctx,$);case"ui.notify":return this.publish(H8("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(H8("ui.show_window",$.payload??{})),u($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"connector.channels":case"connector.configure":case"connector.delete_config":return await a_(this.ctx,$);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 W=await this.scheduleCommands.handleCommand($);if(W.ok){let Z=Of($.command);if(Z)this.publish(H8(Z,W.payload))}return W}}}captureFailedReply($,W){if(W.ok||!W.error||!Av(W.error.code))return;E7(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(W.error.message),severity:W.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:W.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let W=await this.settings.list(zf($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:W instanceof Error?W.message:String(W)}}}}async handleSettingsToggle($){try{let W=await this.settings.toggle(Fv($.payload));return this.publish(H8("settings.changed",{types:W.changedTypes,snapshot:W.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W.snapshot,changedTypes:W.changedTypes}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:W instanceof Error?W.message:String(W)}}}}subscribe($,W,Z){let Q=this.listeners.get($)??new Set,J={sessionId:Z?.sessionId,listener:W};return Q.add(J),this.listeners.set($,Q),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(J),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[W,Z]of this.sessionState.entries()){if(Z.participants.delete($),Z.createdByClientId===$)Z.createdByClientId=void 0;if(Z.participants.size===0)this.sessionState.delete(W)}t$(this.ctx,(W)=>W.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let W of this.listeners.values())for(let Z of W){if(Z.sessionId&&Z.sessionId!==$.sessionId)continue;try{Z.listener($)}catch(Q){bY(`listener threw while publishing ${$.event}`,Q),E7(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Av($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as fv}from"node:crypto";import Lv from"node:http";import Tv from"node:net";import{URL as lY}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as Rf,HUB_CAPABILITIES as Ov,isHubProtocolCompatible as zv,MAX_CLIENT_HUB_PROTOCOL_VERSION as Ef,MIN_CLIENT_HUB_PROTOCOL_VERSION as Nf}from"@cline/shared";import{WebSocketServer as qv}from"ws";import{captureSdkError as qf,HUB_COMMAND_SLOW_LOG_MS as Uv,resolveHubCommandTimeoutMs as Dv,safeJsonParse as _v}from"@cline/shared";function cY($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function Mf($,W,Z){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:W,message:Z}}}class I9{transport;telemetry;constructor($,W){this.transport=$;this.telemetry=W}attach($){let W=new Map,Z=new Set,Q=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(B){console.error(`[hub] failed to send websocket frame: ${B instanceof Error?B.stack||B.message:String(B)}`)}},j=(V)=>{J({kind:"event",envelope:V})},X=async(V)=>{try{let B=JSON.parse(V.data);switch(B.kind){case"command":{let H=performance.now(),G=!1,K=cY(B);i("info","command.start",K);let F=setTimeout(()=>{if(G)return;i("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-H)})},Uv),A=this.transport.command(B.envelope);A.then((O)=>{if(!G)return;i(O.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-H),ok:O.ok,errorCode:O.error?.code,errorMessage:O.error?.message})},(O)=>{if(!G)return;i("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-H),error:O})});let D=!1,U,f,_=Dv(B.envelope.command,B.envelope.timeoutMs);try{f=_===null?await A:await Promise.race([A,new Promise((O)=>{U=setTimeout(()=>{D=!0,qf(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${B.envelope.command} did not complete within ${_}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:_}}),O(Mf(B,"hub_command_timeout",`Hub command ${B.envelope.command} did not complete within ${_}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${B.envelope.requestId}.`))},_)})])}catch(O){if(clearTimeout(F),U)clearTimeout(U);throw O}if(G=D,clearTimeout(F),U)clearTimeout(U);let R=Math.round(performance.now()-H);if(D)i("error","command.timeout",{...K,durationMs:R,timeoutMs:_});else i(f.ok?"info":"warn","command.end",{...K,durationMs:R,ok:f.ok,errorCode:f.error?.code,errorMessage:f.error?.message});if(B.envelope.command==="client.register"&&f.ok){let T=(B.envelope.payload??{}).clientId?.trim()||B.envelope.clientId?.trim();if(T)Z.add(T)}else if(B.envelope.command==="client.unregister"&&f.ok){let O=B.envelope.clientId?.trim();if(O)Z.delete(O)}J({kind:"reply",envelope:f});break}case"stream.subscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;if(W.has(H))break;let G=await this.transport.subscribe(B.clientId,j,{sessionId:B.sessionId});W.set(H,G);break}case"stream.unsubscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;W.get(H)?.(),W.delete(H);break}case"reply":case"event":break}}catch(B){let H=typeof V.data==="string"?_v(V.data):void 0;if(!H||H.kind!=="command"){i("error","rejected malformed websocket frame",{error:B});return}i("error","command.error",{...cY(H),error:B}),qf(this.telemetry,{component:"core",operation:"hub.websocket_command",error:B,severity:"error",handled:!0,context:cY(H)}),J({kind:"reply",envelope:Mf(H,"command_failed",B instanceof Error?B.message:"Unknown hub error")})}},Y=()=>{if(Q)return;Q=!0;for(let V of W.values())V();W.clear();for(let V of Z)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Z.clear(),$.removeEventListener("message",X),$.removeEventListener("close",Y)};return $.addEventListener("message",X),$.addEventListener("close",Y),Y}}class x9{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,W,Z){return this.transport.subscribe($,W,Z)}}function Mv($){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((W)=>Buffer.from(W))).toString();return String($)}function Rv($){return{send(W){$.send(W)},addEventListener(W,Z){if(W==="message"){$.on("message",(Q)=>{Z({data:Mv(Q)})});return}$.on("close",Z)},removeEventListener(){}}}function Ev($){try{$.write(`HTTP/1.1 400 Bad Request\r
752
752
  Connection: close\r
753
753
  Content-Length: 0\r
754
754
  \r
755
- `),$.end()}catch{$.destroy()}}function Dv($){try{$.write(`HTTP/1.1 401 Unauthorized\r
755
+ `),$.end()}catch{$.destroy()}}function Nv($){try{$.write(`HTTP/1.1 401 Unauthorized\r
756
756
  Connection: close\r
757
757
  Content-Length: 0\r
758
758
  \r
759
- `),$.end()}catch{$.destroy()}}function bY($,W){if(!$||!W)return!1;let Z=Buffer.from($,"utf8"),Q=Buffer.from(W,"utf8");return Z.length===Q.length&&Vv(Z,Q)}function z_($,W){let Z=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${W.host}:${W.port}${W.pathname}: ${Q}`,j=Error(Z?`${J} (${Z})`:J);if(Z)$.code=Z,j.code=Z;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
760
- Caused by: ${$.stack}`;return j}async function _v($){return await new Promise((W,Z)=>{let Q=Hv.createServer();Q.once("error",Z),Q.listen(0,$,()=>{let J=Q.address();if(!J||typeof J==="string"){Q.close(()=>Z(Error("Failed to resolve free port")));return}let j=J.port;Q.close((X)=>{if(X){Z(X);return}W(j)})})})}function Lv($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var yY=new Map,q_="cline-hub-auth.",Tv=30000;function kY($){return Array.isArray($)?$.join(","):$??""}function M_($){return $===32||$===9}function F7($){let W=kY($).trim(),Z="bearer";if(W.length<=6||W.slice(0,6).toLowerCase()!=="bearer"||!M_(W.charCodeAt(6)))return null;let Q=7;while(Q<W.length&&M_(W.charCodeAt(Q)))Q+=1;return W.slice(Q).trim()||null}function Ov($){for(let W of kY($).split(",")){let Z=W.trim();if(Z.startsWith(q_))return Z.slice(q_.length).trim()||null}return null}function A7($){let W=$.trim().toLowerCase();return W==="localhost"||W==="127.0.0.1"||W==="::1"||W==="[::1]"}function JY($){let W=kY($).trim();if(!W)return!1;try{return A7(new hY(W).hostname)}catch{return!1}}async function PW($){let W=$.owner??p1(),Z=$.host??"127.0.0.1",Q=$.pathname??"/hub",J=$.port??M8(),j=J===0?await _v(Z):J,X=j,Y=Y1(Z,j,Q),V=K9(),B=G9(),H=new n6($);await H.start();let G=new wW(new CW(H),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:L_,minClientProtocolVersion:O_,maxClientProtocolVersion:T_,capabilities:Gv,coreVersion:U4.version,buildId:V,pid:process.pid,startedAt:F},f=new Set,U,_,D=async()=>{if(_)return _;return _=(async()=>{if(U)clearInterval(U),U=void 0;for(let L of f)L.terminate?.();f.clear();for(let L of K)L();if(K.clear(),await new Promise((L,C)=>{O.close((N)=>{if(N){C(N);return}L()})}),await new Promise((L,C)=>{M.close((N)=>{if(N){C(N);return}L()})}),await H.stop(),(await U0(W.discoveryPath))?.url===Y)await x0(W.discoveryPath)})(),_},M=Bv.createServer((T,L)=>{if((T.url??"/")==="/health"){let N=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Z,port:X,url:Y});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(N);return}if((T.url??"/")==="/status"){if(!bY(F7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}let N=JSON.stringify({hubId:H.getHubId(),...A,authToken:B,host:Z,port:X,url:Y,updatedAt:new Date().toISOString()});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(N);return}if((T.url??"/")==="/version"){L.statusCode=200,L.setHeader("content-type","application/json"),L.end(JSON.stringify(A));return}if(new hY(T.url??"/",`http://${Z}:${X}`).pathname==="/shutdown"&&T.method==="POST"){if(!bY(F7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}L.statusCode=202,L.setHeader("content-type","application/json"),L.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{D()});return}L.statusCode=404,L.end("Not found")}),O=new Fv({noServer:!0});U=setInterval(()=>{for(let T of f){if(T.isAlive===!1){try{T.terminate?.()}catch{}f.delete(T);continue}T.isAlive=!1;try{T.ping?.()}catch{try{T.terminate?.()}catch{}f.delete(T)}}},Tv),M.on("upgrade",(T,L,C)=>{if(new hY(T.url??"/",`http://${Z}:${X}`).pathname!==Q){L.destroy();return}if(!(bY(Ov(T.headers["sec-websocket-protocol"]),B)||A7(Z)&&JY(T.headers.origin))){Dv(L);return}try{O.handleUpgrade(T,L,C,(x)=>{let P=x;P.isAlive=!0,P.on("pong",()=>{P.isAlive=!0}),f.add(P);let r=G.attach(Uv(x));K.add(r),x.once("close",()=>{f.delete(P),r(),K.delete(r)})})}catch{fv(L)}});try{await new Promise((T,L)=>{M.once("error",(C)=>{L(z_(C,{host:Z,port:j,pathname:Q}))}),M.listen(j,Z,()=>{let C=M.address();if(!C||typeof C==="string"){L(z_(Error("Failed to resolve hub port"),{host:Z,port:j,pathname:Q}));return}X=C.port,Y=Y1(Z,X,Q),T()})})}catch(T){if(U)clearInterval(U),U=void 0;throw await H.stop().catch(()=>{return}),T}return await F9(W.discoveryPath,{hubId:H.getHubId(),protocolVersion:L_,minClientProtocolVersion:O_,maxClientProtocolVersion:T_,capabilities:[...A.capabilities],coreVersion:U4.version,buildId:V,authToken:B,host:Z,port:X,url:Y,pid:process.pid,startedAt:F,updatedAt:F}),{host:Z,port:X,url:Y,authToken:B,close:D}}async function U7($){let W=$.owner??p1(),Z=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",J=$.port??M8(),j=$.pathname??"/hub",X=Y1(Q,J,j),Y=W.discoveryPath,V=(H)=>{if(!Z)T$(H.url,H.authToken);return H},B=yY.get(Y);if(B){let H=await B;if(H.url===X)return V({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await A9(W.discoveryPath,async()=>{let H=await U0(W.discoveryPath);if(H?.url&&(H.url===X||$.allowPortFallback===!0)){let F=await r1(H.url,{authToken:H.authToken});if(F?.url&&Kv(F).compatible&&await z1(F.url,{authToken:H.authToken}))return V({url:F.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await x0(W.discoveryPath);let K=async(F)=>{let A=PW({...F,owner:W});yY.set(Y,A);try{let f=await A;return V({server:f,url:f.url,authToken:f.authToken,action:"started"})}catch(f){throw yY.delete(Y),f}};try{return await K($)}catch(F){if(!$.allowPortFallback||!Lv(F))throw F;return await K({...$,port:0})}})}function N_(){return R_()==="production"?O1():V1()}function zv($){return R_()!=="production"&&!$}async function KD($){let W=T1({host:$.host,port:$.port,pathname:$.pathname});return await PW({...$,...W,owner:N_()})}async function FD($){let W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=T1({host:$.host,port:$.port,pathname:$.pathname});return await U7({...$,...Z,allowPortFallback:$.allowPortFallback??zv(W),owner:N_()})}export{F9 as writeHubDiscovery,A9 as withHubStartupLock,z1 as verifyHubConnection,EW as truncateNotificationBody,r7 as toHubStatusUrl,U9 as toHubHealthUrl,J3 as stopLocalHubServerGracefully,PW as startHubWebSocketServer,KD as startHubServer,R8 as spawnDetachedHubServerWithRetry,t7 as spawnDetachedHubServer,JB as sendHubCommand,T9 as restartLocalHubIfIdleAfterStartupTimeout,cV as resolveWorkspaceHubOwnerContext,V1 as resolveSharedHubOwnerContext,O1 as resolveProductionHubOwnerContext,j3 as resolveHubUrl,p1 as resolveHubOwnerContext,T1 as resolveHubEndpointOptions,K9 as resolveHubBuildId,M8 as resolveDefaultHubPort,s7 as resolveDefaultHubPathname,o7 as resolveDefaultHubHost,_4 as resolveCompatibleLocalHubUrl,xV as resolveClineDir,X2 as resolveClineDataDir,D4 as requestHubShutdown,T$ as rememberRecoverableLocalHubUrl,U0 as readHubDiscovery,F7 as readBearerToken,r1 as probeHubServer,QB as probeHubConnection,D9 as prewarmDetachedHubServer,O$ as normalizeHubWebSocketUrl,JY as isLocalHubOrigin,A7 as isLocalHubHostName,Z3 as isHubReconnectableTransportError,L9 as isHubCommandTimeoutError,mV as isDiscoveryFilePresent,U7 as ensureHubWebSocketServer,FD as ensureHubServer,iV as ensureDetachedHubServer,B2 as ensureCompatibleLocalHubUrl,GD as createLocalHubScheduleRuntimeHandlers,gV as createInMemoryHubOwnerContext,Y1 as createHubServerUrl,G9 as createHubAuthToken,u1 as createConfiguredTelemetryService,z8 as createConfiguredTelemetryHandle,O9 as connectToHub,x0 as clearHubDiscovery,B1 as NodeHubClient,CW as NativeHubTransportAdapter,V3 as HubUIClient,b0 as HubTransportError,Y3 as HubSessionClient,n6 as HubServerTransport,f8 as HubScheduleService,K8 as HubScheduleCommandService,N8 as HubCommandError,n7 as DEFAULT_HUB_PORT,a7 as DEFAULT_HUB_PATHNAME,i7 as DEFAULT_HUB_HOST,wW as BrowserWebSocketHubAdapter};
759
+ `),$.end()}catch{$.destroy()}}function uY($,W){if(!$||!W)return!1;let Z=Buffer.from($,"utf8"),Q=Buffer.from(W,"utf8");return Z.length===Q.length&&fv(Z,Q)}function wf($,W){let Z=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${W.host}:${W.port}${W.pathname}: ${Q}`,j=Error(Z?`${J} (${Z})`:J);if(Z)$.code=Z,j.code=Z;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
760
+ Caused by: ${$.stack}`;return j}async function wv($){return await new Promise((W,Z)=>{let Q=Tv.createServer();Q.once("error",Z),Q.listen(0,$,()=>{let J=Q.address();if(!J||typeof J==="string"){Q.close(()=>Z(Error("Failed to resolve free port")));return}let j=J.port;Q.close((X)=>{if(X){Z(X);return}W(j)})})})}function Cv($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var dY=new Map,Cf="cline-hub-auth.",Pv=30000;function pY($){return Array.isArray($)?$.join(","):$??""}function Pf($){return $===32||$===9}function f7($){let W=pY($).trim(),Z="bearer";if(W.length<=6||W.slice(0,6).toLowerCase()!=="bearer"||!Pf(W.charCodeAt(6)))return null;let Q=7;while(Q<W.length&&Pf(W.charCodeAt(Q)))Q+=1;return W.slice(Q).trim()||null}function Sv($){for(let W of pY($).split(",")){let Z=W.trim();if(Z.startsWith(Cf))return Z.slice(Cf.length).trim()||null}return null}function L7($){let W=$.trim().toLowerCase();return W==="localhost"||W==="127.0.0.1"||W==="::1"||W==="[::1]"}function AY($){let W=pY($).trim();if(!W)return!1;try{return L7(new lY(W).hostname)}catch{return!1}}async function g9($){let W=$.owner??r1(),Z=$.host??"127.0.0.1",Q=$.pathname??"/hub",J=$.port??E8(),j=J===0?await wv(Z):J,X=j,Y=Y1(Z,j,Q),V=TW(),B=LW(),H=new o6($);await H.start();let G=new I9(new x9(H),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:Rf,minClientProtocolVersion:Nf,maxClientProtocolVersion:Ef,capabilities:Ov,coreVersion:_4.version,buildId:V,pid:process.pid,startedAt:F},D=new Set,U,f,_=async()=>{if(f)return f;return f=(async()=>{if(U)clearInterval(U),U=void 0;for(let L of D)L.terminate?.();D.clear();for(let L of K)L();if(K.clear(),await new Promise((L,C)=>{O.close((E)=>{if(E){C(E);return}L()})}),await new Promise((L,C)=>{R.close((E)=>{if(E){C(E);return}L()})}),await H.stop(),(await D0(W.discoveryPath))?.url===Y)await g0(W.discoveryPath)})(),f},R=Lv.createServer((T,L)=>{if((T.url??"/")==="/health"){let E=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Z,port:X,url:Y});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(E);return}if((T.url??"/")==="/status"){if(!uY(f7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}let E=JSON.stringify({hubId:H.getHubId(),...A,authToken:B,host:Z,port:X,url:Y,updatedAt:new Date().toISOString()});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(E);return}if((T.url??"/")==="/version"){L.statusCode=200,L.setHeader("content-type","application/json"),L.end(JSON.stringify(A));return}if(new lY(T.url??"/",`http://${Z}:${X}`).pathname==="/shutdown"&&T.method==="POST"){if(!uY(f7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}L.statusCode=202,L.setHeader("content-type","application/json"),L.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{_()});return}L.statusCode=404,L.end("Not found")}),O=new qv({noServer:!0});U=setInterval(()=>{for(let T of D){if(T.isAlive===!1){try{T.terminate?.()}catch{}D.delete(T);continue}T.isAlive=!1;try{T.ping?.()}catch{try{T.terminate?.()}catch{}D.delete(T)}}},Pv),R.on("upgrade",(T,L,C)=>{if(new lY(T.url??"/",`http://${Z}:${X}`).pathname!==Q){L.destroy();return}if(!(uY(Sv(T.headers["sec-websocket-protocol"]),B)||L7(Z)&&AY(T.headers.origin))){Nv(L);return}try{O.handleUpgrade(T,L,C,(x)=>{let P=x;P.isAlive=!0,P.on("pong",()=>{P.isAlive=!0}),D.add(P);let r=G.attach(Rv(x));K.add(r),x.once("close",()=>{D.delete(P),r(),K.delete(r)})})}catch{Ev(L)}});try{await new Promise((T,L)=>{R.once("error",(C)=>{L(wf(C,{host:Z,port:j,pathname:Q}))}),R.listen(j,Z,()=>{let C=R.address();if(!C||typeof C==="string"){L(wf(Error("Failed to resolve hub port"),{host:Z,port:j,pathname:Q}));return}X=C.port,Y=Y1(Z,X,Q),T()})})}catch(T){if(U)clearInterval(U),U=void 0;throw await H.stop().catch(()=>{return}),T}return await OW(W.discoveryPath,{hubId:H.getHubId(),protocolVersion:Rf,minClientProtocolVersion:Nf,maxClientProtocolVersion:Ef,capabilities:[...A.capabilities],coreVersion:_4.version,buildId:V,authToken:B,host:Z,port:X,url:Y,pid:process.pid,startedAt:F,updatedAt:F}),{host:Z,port:X,url:Y,authToken:B,close:_}}async function T7($){let W=$.owner??r1(),Z=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",J=$.port??E8(),j=$.pathname??"/hub",X=Y1(Q,J,j),Y=W.discoveryPath,V=(H)=>{if(!Z)O$(H.url,H.authToken);return H},B=dY.get(Y);if(B){let H=await B;if(H.url===X)return V({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await zW(W.discoveryPath,async()=>{let H=await D0(W.discoveryPath);if(H?.url&&(H.url===X||$.allowPortFallback===!0)){let F=await i1(H.url,{authToken:H.authToken});if(F?.url&&zv(F).compatible&&await z1(F.url,{authToken:H.authToken}))return V({url:F.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await g0(W.discoveryPath);let K=async(F)=>{let A=g9({...F,owner:W});dY.set(Y,A);try{let D=await A;return V({server:D,url:D.url,authToken:D.authToken,action:"started"})}catch(D){throw dY.delete(Y),D}};try{return await K($)}catch(F){if(!$.allowPortFallback||!Cv(F))throw F;return await K({...$,port:0})}})}function bf(){return Sf()==="production"?O1():V1()}function bv($){return Sf()!=="production"&&!$}async function f_($){let W=T1({host:$.host,port:$.port,pathname:$.pathname});return await g9({...$,...W,owner:bf()})}async function L_($){let W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=T1({host:$.host,port:$.port,pathname:$.pathname});return await T7({...$,...Z,allowPortFallback:$.allowPortFallback??bv(W),owner:bf()})}export{OW as writeHubDiscovery,zW as withHubStartupLock,z1 as verifyHubConnection,k9 as truncateNotificationBody,s7 as toHubStatusUrl,qW as toHubHealthUrl,B3 as stopLocalHubServerGracefully,g9 as startHubWebSocketServer,f_ as startHubServer,N8 as spawnDetachedHubServerWithRetry,Q3 as spawnDetachedHubServer,AB as sendHubCommand,wW as restartLocalHubIfIdleAfterStartupTimeout,sV as resolveWorkspaceHubOwnerContext,V1 as resolveSharedHubOwnerContext,O1 as resolveProductionHubOwnerContext,H3 as resolveHubUrl,r1 as resolveHubOwnerContext,T1 as resolveHubEndpointOptions,TW as resolveHubBuildId,E8 as resolveDefaultHubPort,Z3 as resolveDefaultHubPathname,W3 as resolveDefaultHubHost,T4 as resolveCompatibleLocalHubUrl,iV as resolveClineDir,Y2 as resolveClineDataDir,L4 as requestHubShutdown,O$ as rememberRecoverableLocalHubUrl,D0 as readHubDiscovery,f7 as readBearerToken,i1 as probeHubServer,FB as probeHubConnection,RW as prewarmDetachedHubServer,z$ as normalizeHubWebSocketUrl,AY as isLocalHubOrigin,L7 as isLocalHubHostName,Y3 as isHubReconnectableTransportError,NW as isHubCommandTimeoutError,aV as isDiscoveryFilePresent,T7 as ensureHubWebSocketServer,L_ as ensureHubServer,QB as ensureDetachedHubServer,H2 as ensureCompatibleLocalHubUrl,__ as createLocalHubScheduleRuntimeHandlers,nV as createInMemoryHubOwnerContext,Y1 as createHubServerUrl,LW as createHubAuthToken,d1 as createConfiguredTelemetryService,M8 as createConfiguredTelemetryHandle,CW as connectToHub,g0 as clearHubDiscovery,B1 as NodeHubClient,x9 as NativeHubTransportAdapter,F3 as HubUIClient,y0 as HubTransportError,K3 as HubSessionClient,o6 as HubServerTransport,f8 as HubScheduleService,A8 as HubScheduleCommandService,w8 as HubCommandError,e7 as DEFAULT_HUB_PORT,$3 as DEFAULT_HUB_PATHNAME,t7 as DEFAULT_HUB_HOST,I9 as BrowserWebSocketHubAdapter};