@cline/core 0.0.47 → 0.0.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hub/index.js CHANGED
@@ -1,44 +1,44 @@
1
- import{createRequire as qG}from"node:module";var{defineProperty:g9,getOwnPropertyNames:MG}=Object;var L3=Object.prototype.hasOwnProperty;function _3($){return this[$]}var M=($,f,J)=>{var Q=MG(f);for(let Z of Q)if(!L3.call($,Z)&&Z!=="default")g9($,Z,{get:_3.bind(f,Z),enumerable:!0});if(J){for(let Z of Q)if(!L3.call(J,Z)&&Z!=="default")g9(J,Z,{get:_3.bind(f,Z),enumerable:!0});return J}};var TG=($)=>$;function NG($,f){this[$]=TG.bind(null,f)}var q=($,f)=>{for(var J in f)g9($,J,{get:f[J],enumerable:!0,configurable:!0,set:NG.bind(f,J)})};var h$=($,f)=>()=>($&&(f=$($=0)),f);var z3=qG(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as VF}from"@cline/shared";function p($,f,J){$?.capture({event:f,properties:J})}function CJ($){if(!$)return;return $.substring(0,HF)}function BF($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function KF($){return typeof $==="string"?$:$.message}function c3($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function u3($){p($,g.CLIENT.EXTENSION_ACTIVATED)}function yJ($,f){let J=[...f.vcs_types],Q={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:c3(J,new Set(["git"])),has_mercurial:c3(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)Q.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)Q.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)Q.is_remote_workspace=f.is_remote_workspace;p($,g.WORKSPACE.INITIALIZED,Q)}function SJ($,f,J){p($,g.WORKSPACE.INIT_ERROR,{error_type:BF(f),error_message:CJ(KF(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function d3($,f){p($,g.WORKSPACE.PATH_RESOLVED,{...f})}function N1($,f){p($,g.USER.AUTH_STARTED,{provider:f})}function q1($,f){p($,g.USER.AUTH_SUCCEEDED,{provider:f})}function w1($,f,J){p($,g.USER.AUTH_FAILED,{provider:f,errorMessage:CJ(J)})}function f$($,f,J){p($,g.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function l3($,f){p($,g.USER.PROVIDER_CONFIGURED,{provider:f})}function p3($,f){$?.captureRequired(g.USER.TELEMETRY_OPT_OUT,f)}function C1($,f){let J=f.id?.trim();if(J)$?.setDistinctId(J);$?.updateCommonProperties({account_id:f.id,account_email:f.email,provider:f.provider,organization_id:f.organizationId,organization_name:f.organizationName,member_id:f.memberId})}function EJ($,f){p($,g.TASK.CREATED,f)}function hJ($,f){p($,g.TASK.RESTARTED,f)}function A8($,f){p($,g.TASK.COMPLETED,f)}function cf($,f){p($,g.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function bJ($,f){p($,g.TASK.TOKEN_USAGE,f)}function kJ($,f,J){p($,g.TASK.MODE_SWITCH,{ulid:f,mode:J})}function IJ($,f){p($,g.TASK.TOOL_USED,f)}function xJ($,f){p($,g.TASK.SKILL_USED,f)}function gJ($,f){p($,g.TASK.DIFF_EDIT_FAILED,f)}function V8($,f){p($,g.TASK.PROVIDER_API_ERROR,{...f,errorMessage:CJ(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function r3($,f){p($,g.SDK.TOOL_TIMEOUT,GF(f))}function GF($){let f={};for(let[J,Q]of Object.entries($))if(Q!==void 0)f[J]=Q;return f}function mJ($,f,J){p($,g.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function vJ($,f,J,Q){p($,g.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:CJ(Q),timestamp:new Date().toISOString()})}function cJ($,f,J,Q,Z){p($,g.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:Q,isEmpty:Z,timestamp:new Date().toISOString()})}function J$($,f){p($,g.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function uJ($,f){p($,g.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function H8($,f){p($,f.event==="ended"?g.TASK.SUBAGENT_COMPLETED:g.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function dJ($,f,J,Q){p($,g.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:Q,totalCount:J+Q,timestamp:new Date().toISOString()})}function lJ($,f){p($,g.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function pJ($,f){p($,g.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var HF=500,g;var _0=h$(()=>{g={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:VF,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as FF,readFileSync as PF,statSync as RF,writeFileSync as DF}from"node:fs";import{dirname as UF}from"node:path";import{resolveGlobalSettingsPath as n3}from"@cline/shared/storage";import{z as uf}from"zod";function rJ(){return B8.parse({})}function LF(){iJ=void 0}function _F($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function zF($){let f;try{f=PF($,"utf8")}catch{return rJ()}try{let J=B8.safeParse(JSON.parse(f));return J.success?J.data:rJ()}catch{return rJ()}}function OF(){let $=n3(),f=RF($,{throwIfNoEntry:!1}),J=f?.mtimeMs??0,Q=f?.size??0,Z=iJ;if(Z&&Z.path===$&&Z.mtimeMs===J&&Z.size===Q)return Z;let W=_F(f?zF($):rJ());return iJ={path:$,mtimeMs:J,size:Q,value:W},iJ}function z0(){return OF().value}function y1($,f={}){let J=n3(),Q=z0();FF(UF(J),{recursive:!0});let Z=B8.parse($);if(!Q.telemetryOptOut&&Z.telemetryOptOut)p3(f.telemetry);DF(J,`${JSON.stringify(Z,null,2)}
2
- `,"utf8"),LF()}function nJ(){return z0().telemetryOptOut}function a3($,f={}){y1({...z0(),telemetryOptOut:$},f)}function t3(){return z0().autoUpdateEnabled}function s3($,f={}){y1({...z0(),autoUpdateEnabled:$},f)}function W1($){return new Set($??z0().disabledTools??[])}function K8($){return new Set($??z0().disabledPlugins??[])}function o3($){return W1().has($)}function aJ($){let f=z0(),J=new Set(f.disabledTools??[]),Q=J.has($);if(Q)J.delete($);else J.add($);return y1({...f,disabledTools:[...J]}),!Q}function s9($,f){let J=[...new Set($.map((W)=>W.trim()).filter(Boolean))];if(J.length===0)return;let Q=z0(),Z=W1(Q.disabledTools);for(let W of J)if(f)Z.add(W);else Z.delete(W);y1({...Q,disabledTools:[...Z]})}function e3($,f){return s9([$],f),f}function $j($){return K8().has($)}function fj($,f){let J=$.trim();if(!J)return;let Q=z0(),Z=K8(Q.disabledPlugins);if(f)Z.add(J);else Z.delete(J);y1({...Q,disabledPlugins:[...Z]})}function tJ($,f){let J=K8(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q))}function x$($,f){let J=W1(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q.name))}function sJ($,f){if(!$||$.length===0)return $;let J=W1(f);if(J.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(Z,W)=>Q.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},W)}})}var i3,B8,iJ;var j1=h$(()=>{_0();i3=uf.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,uf.array(uf.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,Q)=>J.localeCompare(Q));return f.length>0?f:void 0}),B8=uf.object({telemetryOptOut:uf.boolean().default(!1).catch(!1),autoUpdateEnabled:uf.boolean().default(!0).catch(!0),disabledTools:i3.optional(),disabledPlugins:i3.optional()}).strip().transform(($)=>{let f={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});import{existsSync as MF,mkdirSync as TF,readFileSync as NF,writeFileSync as qF}from"node:fs";import{resolve as wF}from"node:path";import{resolveSessionDataDir as CF}from"@cline/shared/storage";import{nanoid as yF}from"nanoid";import*as SF from"node-machine-id";function S1($){let f=$?.trim();if(f)return f;let J=bF();if(J)return J;return kF()}function hF(){let $=SF;return $.machineIdSync??$.default?.machineIdSync}function bF(){try{let $=hF();if(!$)return;return $().trim()||void 0}catch{return}}function kF(){let $=CF(),f=wF($,EF);try{if(MF(f)){let Q=NF(f,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${yF()}`;try{TF($,{recursive:!0}),qF(f,J,"utf8")}catch{}return J}var EF="machine-id";var G8=()=>{};class P8{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.counters.get($);if(!W)W=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,W);W.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get($);if(!W)W=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,W);W.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.buildAttributes(J),j=JSON.stringify(W),X=this.gaugeValues.get($);if(f===null){if(X){if(X.delete(j),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let Y=X;if(!Y)Y=new Map,this.gaugeValues.set($,Y);if(!this.gauges.has($)){let A=this.meter.createObservableGauge($,Q?{description:Q}:void 0);A.addCallback((V)=>{for(let H of this.snapshotGaugeSeries($))V.observe(H.value,this.flattenProperties(H.attributes))}),this.gauges.set($,A)}Y.set(j,{value:f,attributes:W})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,Q=0){if(!$)return{};let Z={},W=100,j=10;for(let[X,Y]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let A=f?`${f}.${X}`:X;if(Y===null||Y===void 0){Z[A]=String(Y);continue}if(Array.isArray(Y)){let V=Y.length>W?Y.slice(0,W):Y;try{Z[A]=JSON.stringify(V)}catch{Z[A]="[UnserializableArray]"}if(Y.length>W)Z[`${A}_truncated`]=!0,Z[`${A}_original_length`]=Y.length;continue}if(typeof Y==="object"){if(Y instanceof Date){Z[A]=Y.toISOString();continue}if(Y instanceof Error){Z[A]=Y.message;continue}if(J.has(Y)){Z[A]="[Circular]";continue}if(Q>=j){Z[A]="[MaxDepthExceeded]";continue}J.add(Y),Object.assign(Z,this.flattenProperties(Y,A,J,Q+1));continue}if(IF(Y)){Z[A]=Y;continue}try{Z[A]=JSON.stringify(Y)}catch{Z[A]=String(Y)}}return Z}}function IF($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class R8{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordHistogram($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordGauge($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class df{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new R8({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let Q of this.adapters)Q.emitRequired($,J)}recordCounter($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,W,Q,Z)}recordHistogram($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,W,Q,Z)}recordGauge($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,W,Q,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var o9=()=>{};import{metrics as xF,trace as gF}from"@opentelemetry/api";import{logs as mF}from"@opentelemetry/api-logs";import{OTLPLogExporter as vF}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as cF}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as uF}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as dF}from"@opentelemetry/resources";import{BatchLogRecordProcessor as lF,ConsoleLogRecordExporter as pF,LoggerProvider as rF}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as iF,MeterProvider as nF,PeriodicExportingMetricReader as Jj}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as aF,ConsoleSpanExporter as tF,SimpleSpanProcessor as sF}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as oF}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as eF,ATTR_SERVICE_VERSION as $P}from"@opentelemetry/semantic-conventions";class Qj{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class lf{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=dF({[eF]:$.serviceName??"cline",...$.serviceVersion?{[$P]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)xF.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)mF.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return gF.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new P8({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new df({...$,adapters:[f],distinctId:S1($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let f=e9(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(J*0.8)),Z=f.map((W)=>QP(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:Q})).filter((W)=>W!==null);if(Z.length===0)return null;return new nF({resource:$,readers:Z})}createTracerProvider($){let f=e9(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of f){let j=JP(W,{endpoint:J,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new oF({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=e9(this.options.logsExporter);if(f.length===0)return null;let J=f.map((Q)=>{let Z=fP(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new lF(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(J.length===0)return null;return new rF({resource:$,processors:J})}}function D8($){let f=new lf($),J=f.createTelemetryService($);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:f,telemetry:J}}function E1($){if(nJ())return{telemetry:new Qj($)};if($.enabled!==!0)return{telemetry:new df({...$,distinctId:S1($.distinctId)})};return D8($)}function pf($){let{telemetry:f,provider:J}=E1($);return{telemetry:f,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function e9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function fP($,f){if($==="console")return new pF;if(!f.endpoint)return null;let J=$Q(f.endpoint,"/v1/logs");return new vF({url:J,headers:f.headers})}function JP($,f){if($==="console")return new sF(new tF);if(!f.endpoint)return null;let J=$Q(f.endpoint,"/v1/traces");return new aF(new uF({url:J,headers:f.headers}))}function QP($,f){if($==="console")return new Jj({exporter:new iF,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=$Q(f.endpoint,"/v1/metrics");return new Jj({exporter:new cF({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function $Q($,f){let J=new URL($),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith(f)?Q:`${Q}${f}`,J.toString()}var oJ=h$(()=>{j1();G8();o9()});var LY={};q(LY,{normalizeUserMessage:()=>LL,buildInitialUserContent:()=>UL});async function UL($,f,J,Q){let Z=_L(f),W=await OL(J,Q);if(Z.length===0&&!W)return $;let j=[{type:"text",text:$},...Z];if(W)j.push(...W);return j}function LL($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let Q of f)if(Q&&typeof Q==="object"&&Q.type==="text"){let Z=Q.text;if(typeof Z==="string")J.push(Z)}return J.join(`
3
- `)}function _L($){if(!$||$.length===0)return[];let f=[];for(let J of $){let Q=zL(J);if(Q)f.push(Q)}return f}function zL($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let Q=J[1],Z=J[2];if(!Q||!Z)return;return{type:"image",mediaType:Q,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function OL($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(Z)=>{let W=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:W,content:j}}catch(j){let X=j instanceof Error?j.message:String(j);return{type:"file",path:W,content:`Error fetching content: ${X}`}}}));if(Q.length===0)return;return Q}var kV={};q(kV,{updateMcpServerOAuthState:()=>Df,setMcpServerDisabled:()=>Pf,resolveMcpServerRegistrations:()=>B1,resolveDefaultMcpSettingsPath:()=>T0,registerMcpServersFromSettingsFile:()=>Uf,normalizeMcpServerOAuthState:()=>y2,loadMcpSettingsFile:()=>Ff,listMcpServerOAuthStatuses:()=>l4,hasMcpSettingsFile:()=>p1,getMcpServerOAuthState:()=>Rf});import{existsSync as FM,mkdirSync as CV,readFileSync as KW,writeFileSync as yV}from"node:fs";import{dirname as SV}from"node:path";import{resolveMcpSettingsPath as PM}from"@cline/shared/storage";import{z as y}from"zod";function BW($){if(!$)return;if($==="http")return"streamableHttp";return $}function T0(){return PM()}function qM($){let f=KW($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function bV($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function wM($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function Ff($={}){let f=$.filePath??T0(),J=KW(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=NM.safeParse(Q);if(!Z.success){let W=Z.error.issues.map((j)=>{let X=j.path.join(".");return X?`${X}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${W}`)}return Z.data}function CM($){let f=KW($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let Q=J,Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Q}function y2($){if(!$)return;let f={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(f).length>0?f:void 0}function yM($){if($===void 0)return;let f=GW.safeParse($);if(!f.success)return;return y2(f.data)}function p1($={}){let f=$.filePath??T0();return FM(f)}function B1($={}){let f=Ff($);return Object.entries(f.mcpServers).map(([J,Q])=>({name:J,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function Pf($){let f=$.filePath??T0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=qM(f),Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let W={...Z},j=bV(W,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let X={...j};if($.disabled)X.disabled=!0;else delete X.disabled;wM(W,J,X),CV(SV(f),{recursive:!0}),yV(f,`${JSON.stringify({...Q,mcpServers:W},null,2)}
4
- `)}function Rf($,f={}){let J=Ff(f);if(!Object.hasOwn(J.mcpServers,$))return;return y2(J.mcpServers[$]?.oauth)}function Df($,f,J={}){let Q=J.filePath??T0(),Z=CM(Q),W=Z.mcpServers,j=bV(W,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let X=yM(j.oauth)??{},Y=y2(f(X));if(Y)j.oauth=Y;else delete j.oauth;return CV(SV(Q),{recursive:!0}),yV(Q,`${JSON.stringify(Z,null,2)}
5
- `,"utf8"),Y??{}}function l4($={}){return B1($).map((J)=>{let Q=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:Q,oauthConfigured:Q&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,Q)=>J.serverName.localeCompare(Q.serverName))}async function Uf($,f={}){let J=B1(f);for(let Q of J)await $.registerServer(Q);return J}var d4,EV,GW,RM,DM,UM,LM,_M,zM,hV,OM,MM,TM,NM;var h5=h$(()=>{d4=y.record(y.string(),y.string()),EV=y.record(y.string(),y.unknown()),GW=y.object({clientInformation:y.record(y.string(),y.unknown()).optional(),tokens:y.record(y.string(),y.unknown()).optional(),codeVerifier:y.string().optional(),discoveryState:y.record(y.string(),y.unknown()).optional(),redirectUrl:y.string().url().optional(),lastError:y.string().optional(),lastAuthenticatedAt:y.number().int().positive().optional()}).strip(),RM=y.object({type:y.literal("stdio"),command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:d4.optional()}),DM=y.object({type:y.literal("sse"),url:y.string().url(),headers:d4.optional()}),UM=y.object({type:y.literal("streamableHttp"),url:y.string().url(),headers:d4.optional()}),LM=y.discriminatedUnion("type",[RM,DM,UM]),_M=y.object({transport:LM,disabled:y.boolean().optional(),metadata:EV.optional(),oauth:GW.optional()}),zM=y.enum(["stdio","sse","http","streamableHttp"]).optional(),hV=y.object({type:y.enum(["stdio","sse","streamableHttp"]).optional(),transportType:zM,disabled:y.boolean().optional(),metadata:EV.optional(),oauth:GW.optional()});OM=hV.extend({command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:d4.optional()}).superRefine(($,f)=>{let J=$.type??BW($.transportType);if(J&&J!=="stdio")f.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),MM=hV.extend({url:y.string().url(),headers:d4.optional()}).superRefine(($,f)=>{let J=$.type??BW($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??BW($.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}}),TM=y.union([_M,OM,MM]),NM=y.object({mcpServers:y.record(y.string(),TM)}).passthrough()});var BB={};q(BB,{createOpenTelemetryTelemetryService:()=>D8,createConfiguredTelemetryService:()=>E1,createConfiguredTelemetryHandle:()=>pf,OpenTelemetryProvider:()=>lf,OpenTelemetryAdapter:()=>P8});var oW=h$(()=>{oJ()});var UK={};q(UK,{writeHubDiscovery:()=>f6,withHubStartupLock:()=>J6,verifyHubConnection:()=>A1,truncateNotificationBody:()=>GJ,toHubStatusUrl:()=>ZQ,toHubHealthUrl:()=>Q6,stopLocalHubServerGracefully:()=>PQ,startHubWebSocketServer:()=>RJ,startHubServer:()=>RK,spawnDetachedHubServerWithRetry:()=>nf,spawnDetachedHubServer:()=>VQ,sendHubCommand:()=>hj,restartLocalHubIfIdleAfterStartupTimeout:()=>Y6,resolveWorkspaceHubOwnerContext:()=>Pj,resolveSharedHubOwnerContext:()=>o0,resolveProductionHubOwnerContext:()=>Y1,resolveHubUrl:()=>RQ,resolveHubOwnerContext:()=>k1,resolveHubEndpointOptions:()=>X1,resolveHubBuildId:()=>$6,resolveDefaultHubPort:()=>rf,resolveDefaultHubPathname:()=>AQ,resolveDefaultHubHost:()=>YQ,resolveCompatibleLocalHubUrl:()=>O8,resolveClineDir:()=>Bj,resolveClineDataDir:()=>m$,requestHubShutdown:()=>z8,rememberRecoverableLocalHubUrl:()=>Q$,readHubDiscovery:()=>Z0,readBearerToken:()=>w9,probeHubServer:()=>I1,probeHubConnection:()=>Ej,prewarmDetachedHubServer:()=>W6,normalizeHubWebSocketUrl:()=>Z$,isHubReconnectableTransportError:()=>GQ,isHubCommandTimeoutError:()=>X6,isDiscoveryFilePresent:()=>Gj,ensureHubWebSocketServer:()=>C9,ensureHubServer:()=>DK,ensureDetachedHubServer:()=>zj,ensureCompatibleLocalHubUrl:()=>u$,createLocalHubScheduleRuntimeHandlers:()=>PK,createInMemoryHubOwnerContext:()=>Kj,createHubServerUrl:()=>s0,createHubAuthToken:()=>eJ,createConfiguredTelemetryService:()=>E1,createConfiguredTelemetryHandle:()=>pf,connectToHub:()=>A6,clearHubDiscovery:()=>C0,NodeHubClient:()=>e0,NativeHubTransportAdapter:()=>PJ,HubUIClient:()=>LQ,HubTransportError:()=>O0,HubSessionClient:()=>UQ,HubServerTransport:()=>e2,HubScheduleService:()=>vf,HubScheduleCommandService:()=>If,HubCommandError:()=>af,DEFAULT_HUB_PORT:()=>jQ,DEFAULT_HUB_PATHNAME:()=>XQ,DEFAULT_HUB_HOST:()=>WQ,BrowserWebSocketHubAdapter:()=>FJ});import{createSessionId as wG}from"@cline/shared";function I0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function O3($,f,J){return{version:$.version,requestId:$.requestId??wG("hubreq_"),ok:!1,error:{code:f,message:J}}}class If{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return I0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return I0($,{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 I0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return I0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return I0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return I0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return I0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return I0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return I0($,{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 I0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return I0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return I0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return O3($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return O3($,"schedule_command_failed",f instanceof Error?f.message:String(f))}}toCreateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:f}}toUpdateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:f}}}class f8{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of f)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of J)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as gG}from"node:path";import{buildClineSystemPrompt as mG}from"@cline/shared";import{nowIso as C3}from"@cline/shared/db";var H0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},o1=[H0.READ_FILES,H0.SEARCH_CODEBASE,H0.RUN_COMMANDS,H0.FETCH_WEB_CONTENT,H0.APPLY_PATCH,H0.EDITOR,H0.SKILLS,H0.ASK,H0.SUBMIT_AND_EXIT];var T3={};q(T3,{mergeRulesForSystemPrompt:()=>gf,loadRulesForSystemPromptFromWatcher:()=>m9,listEnabledRulesFromWatcher:()=>M3,isRuleEnabled:()=>MJ,formatRulesForSystemPrompt:()=>xf});function MJ($){return $.disabled!==!0}function xf($){if($.length===0)return"";return`
1
+ import{createRequire as YF}from"node:module";var{defineProperty:o9,getOwnPropertyNames:jF}=Object;var vj=Object.prototype.hasOwnProperty;function cj($){return this[$]}var q=($,J,Q)=>{var Z=jF(J);for(let W of Z)if(!vj.call($,W)&&W!=="default")o9($,W,{get:cj.bind(J,W),enumerable:!0});if(Q){for(let W of Z)if(!vj.call(Q,W)&&W!=="default")o9(Q,W,{get:cj.bind(J,W),enumerable:!0});return Q}};var fF=($)=>$;function XF($,J){this[$]=fF.bind(null,J)}var w=($,J)=>{for(var Q in J)o9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:XF.bind(J,Q)})};var h$=($,J)=>()=>($&&(J=$($=0)),J);var uj=YF(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as pF}from"@cline/shared";function r($,J,Q){$?.capture({event:J,properties:Q})}function xJ($){if(!$)return;return $.substring(0,rF)}function iF($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function nF($){return typeof $==="string"?$:$.message}function Xf($,J){return $.some((Q)=>J.has(Q.trim().toLowerCase()))}function Yf($){r($,g.CLIENT.EXTENSION_ACTIVATED)}function gJ($,J){let Q=[...J.vcs_types],Z={root_count:J.root_count,vcs_types:Q,is_multi_root:J.root_count>1,has_git:Xf(Q,new Set(["git"])),has_mercurial:Xf(Q,new Set(["mercurial","hg"]))};if(J.init_duration_ms!==void 0)Z.init_duration_ms=J.init_duration_ms;if(J.feature_flag_enabled!==void 0)Z.feature_flag_enabled=J.feature_flag_enabled;if(J.is_remote_workspace!==void 0)Z.is_remote_workspace=J.is_remote_workspace;r($,g.WORKSPACE.INITIALIZED,Z)}function mJ($,J,Q){r($,g.WORKSPACE.INIT_ERROR,{error_type:iF(J),error_message:xJ(nF(J)),fallback_to_single_root:Q.fallback_to_single_root,workspace_count:Q.workspace_count??0})}function Vf($,J){r($,g.WORKSPACE.PATH_RESOLVED,{...J})}function N1($,J){r($,g.USER.AUTH_STARTED,{provider:J})}function w1($,J){r($,g.USER.AUTH_SUCCEEDED,{provider:J})}function S1($,J,Q){r($,g.USER.AUTH_FAILED,{provider:J,errorMessage:xJ(Q)})}function Q$($,J,Q){r($,g.USER.AUTH_LOGGED_OUT,{provider:J,reason:Q})}function Hf($,J){r($,g.USER.PROVIDER_CONFIGURED,{provider:J})}function Bf($,J){$?.captureRequired(g.USER.TELEMETRY_OPT_OUT,J)}function C1($,J){let Q=J.id?.trim();if(Q)$?.setDistinctId(Q);$?.updateCommonProperties({account_id:J.id,account_email:J.email,provider:J.provider,organization_id:J.organizationId,organization_name:J.organizationName,member_id:J.memberId})}function vJ($,J){r($,g.TASK.CREATED,J)}function cJ($,J){r($,g.TASK.RESTARTED,J)}function D4($,J){r($,g.TASK.COMPLETED,J)}function u2($,J){r($,g.TASK.CONVERSATION_TURN,{...J,timestamp:new Date().toISOString()})}function uJ($,J){r($,g.TASK.TOKEN_USAGE,J)}function dJ($,J,Q){r($,g.TASK.MODE_SWITCH,{ulid:J,mode:Q})}function lJ($,J){r($,g.TASK.TOOL_USED,J)}function pJ($,J){r($,g.TASK.SKILL_USED,J)}function rJ($,J){r($,g.TASK.DIFF_EDIT_FAILED,J)}function U4($,J){r($,g.TASK.PROVIDER_API_ERROR,{...J,errorMessage:xJ(J.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function Af($,J){r($,g.SDK.TOOL_TIMEOUT,aF(J))}function aF($){let J={};for(let[Q,Z]of Object.entries($))if(Z!==void 0)J[Q]=Z;return J}function iJ($,J,Q){r($,g.TASK.MENTION_USED,{mentionType:J,contentLength:Q,timestamp:new Date().toISOString()})}function nJ($,J,Q,Z){r($,g.TASK.MENTION_FAILED,{mentionType:J,errorType:Q,errorMessage:xJ(Z),timestamp:new Date().toISOString()})}function aJ($,J,Q,Z,W){r($,g.TASK.MENTION_SEARCH_RESULTS,{queryLength:J.length,resultCount:Q,searchType:Z,isEmpty:W,timestamp:new Date().toISOString()})}function Z$($,J){r($,g.TASK.AGENT_CREATED,{...J,timestamp:new Date().toISOString()})}function sJ($,J){r($,g.TASK.AGENT_TEAM_CREATED,{...J,timestamp:new Date().toISOString()})}function R4($,J){r($,J.event==="ended"?g.TASK.SUBAGENT_COMPLETED:g.TASK.SUBAGENT_STARTED,{...J,timestamp:new Date().toISOString()})}function oJ($,J,Q,Z){r($,g.HOOKS.DISCOVERY_COMPLETED,{hookName:J,globalCount:Q,workspaceCount:Z,totalCount:Q+Z,timestamp:new Date().toISOString()})}function tJ($,J){r($,g.TASK.COMPACTION_EXECUTED,{...J,timestamp:new Date().toISOString()})}function eJ($,J){r($,g.TASK.COMPACTION_SKIPPED,{...J,timestamp:new Date().toISOString()})}var rF=500,g;var O0=h$(()=>{g={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:pF,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as sF,readFileSync as oF,statSync as tF,writeFileSync as eF}from"node:fs";import{dirname as $D}from"node:path";import{resolveGlobalSettingsPath as Gf}from"@cline/shared/storage";import{z as d2}from"zod";function $5(){return z4.parse({})}function JD(){J5=void 0}function QD($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function ZD($){let J;try{J=oF($,"utf8")}catch{return $5()}try{let Q=z4.safeParse(JSON.parse(J));return Q.success?Q.data:$5()}catch{return $5()}}function WD(){let $=Gf(),J=tF($,{throwIfNoEntry:!1}),Q=J?.mtimeMs??0,Z=J?.size??0,W=J5;if(W&&W.path===$&&W.mtimeMs===Q&&W.size===Z)return W;let j=QD(J?ZD($):$5());return J5={path:$,mtimeMs:Q,size:Z,value:j},J5}function T0(){return WD().value}function y1($,J={}){let Q=Gf(),Z=T0();sF($D(Q),{recursive:!0});let W=z4.parse($);if(!Z.telemetryOptOut&&W.telemetryOptOut)Bf(J.telemetry);eF(Q,`${JSON.stringify(W,null,2)}
2
+ `,"utf8"),JD()}function Q5(){return T0().telemetryOptOut}function Ff($,J={}){y1({...T0(),telemetryOptOut:$},J)}function Df(){return T0().autoUpdateEnabled}function Uf($,J={}){y1({...T0(),autoUpdateEnabled:$},J)}function X1($){return new Set($??T0().disabledTools??[])}function L4($){return new Set($??T0().disabledPlugins??[])}function Rf($){return X1().has($)}function Z5($){let J=T0(),Q=new Set(J.disabledTools??[]),Z=Q.has($);if(Z)Q.delete($);else Q.add($);return y1({...J,disabledTools:[...Q]}),!Z}function HZ($,J){let Q=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Q.length===0)return;let Z=T0(),W=X1(Z.disabledTools);for(let j of Q)if(J)W.add(j);else W.delete(j);y1({...Z,disabledTools:[...W]})}function zf($,J){return HZ([$],J),J}function Lf($){return L4().has($)}function _f($,J){let Q=$.trim();if(!Q)return;let Z=T0(),W=L4(Z.disabledPlugins);if(J)W.add(Q);else W.delete(Q);y1({...Z,disabledPlugins:[...W]})}function W5($,J){let Q=L4(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z))}function E1($,J){let Q=X1(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z.name))}function j5($,J){if(!$||$.length===0)return $;let Q=X1(J);if(Q.size===0)return $;return $.map((Z)=>{if(!Z.setup)return Z;return{...Z,setup:(W,j)=>Z.setup?.({...W,registerTool:(f)=>{if(!Q.has(f.name))W.registerTool(f)}},j)}})}var Kf,z4,J5;var t0=h$(()=>{O0();Kf=d2.preprocess(($)=>Array.isArray($)?$.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter(Boolean):void 0,d2.array(d2.string()).optional()).transform(($)=>{if(!$)return;let J=[...new Set($)].sort((Q,Z)=>Q.localeCompare(Z));return J.length>0?J:void 0}),z4=d2.object({telemetryOptOut:d2.boolean().default(!1).catch(!1),autoUpdateEnabled:d2.boolean().default(!0).catch(!0),disabledTools:Kf.optional(),disabledPlugins:Kf.optional()}).strip().transform(($)=>{let J={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)J.disabledTools=$.disabledTools;if($.disabledPlugins?.length)J.disabledPlugins=$.disabledPlugins;return J})});import{existsSync as jD,mkdirSync as fD,readFileSync as XD,writeFileSync as YD}from"node:fs";import{resolve as VD}from"node:path";import{resolveSessionDataDir as HD}from"@cline/shared/storage";import{nanoid as BD}from"nanoid";import*as AD from"node-machine-id";function S0($){let J=$?.trim();if(J)return J;let Q=FD();if(Q)return Q;return DD()}function GD(){let $=AD;return $.machineIdSync??$.default?.machineIdSync}function FD(){try{let $=GD();if(!$)return;return $().trim()||void 0}catch{return}}function DD(){let $=HD(),J=VD($,KD);try{if(jD(J)){let Z=XD(J,"utf8").trim();if(Z.length>0)return Z}}catch{}let Q=`cl-${BD()}`;try{fD($,{recursive:!0}),YD(J,Q,"utf8")}catch{}return Q}var KD="machine-id";var l2=()=>{};class O4{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,J){if(!this.isEnabled())return;this.emitLog($,J,!1)}emitRequired($,J){this.emitLog($,J,!0)}recordCounter($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Z?{description:Z}:void 0),this.counters.set($,j);j.add(J,this.flattenProperties(this.buildAttributes(Q)))}recordHistogram($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Z?{description:Z}:void 0),this.histograms.set($,j);j.record(J,this.flattenProperties(this.buildAttributes(Q)))}recordGauge($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.buildAttributes(Q),f=JSON.stringify(j),X=this.gaugeValues.get($);if(J===null){if(X){if(X.delete(f),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let Y=X;if(!Y)Y=new Map,this.gaugeValues.set($,Y);if(!this.gauges.has($)){let V=this.meter.createObservableGauge($,Z?{description:Z}:void 0);V.addCallback((H)=>{for(let B of this.snapshotGaugeSeries($))H.observe(B.value,this.flattenProperties(B.attributes))}),this.gauges.set($,V)}Y.set(f,{value:J,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,J,Q){if(!this.logger)return;let Z=this.flattenProperties(this.buildAttributes(J,Q));this.logger.emit({severityText:"INFO",body:$,attributes:Z})}buildAttributes($,J=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...J?{_required:!0}:{}}}snapshotGaugeSeries($){let J=this.gaugeValues.get($);if(!J)return[];return Array.from(J.values(),(Q)=>({value:Q.value,attributes:Q.attributes?{...Q.attributes}:void 0}))}flattenProperties($,J="",Q=new WeakSet,Z=0){if(!$)return{};let W={},j=100,f=10;for(let[X,Y]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let V=J?`${J}.${X}`:X;if(Y===null||Y===void 0){W[V]=String(Y);continue}if(Array.isArray(Y)){let H=Y.length>j?Y.slice(0,j):Y;try{W[V]=JSON.stringify(H)}catch{W[V]="[UnserializableArray]"}if(Y.length>j)W[`${V}_truncated`]=!0,W[`${V}_original_length`]=Y.length;continue}if(typeof Y==="object"){if(Y instanceof Date){W[V]=Y.toISOString();continue}if(Y instanceof Error){W[V]=Y.message;continue}if(Q.has(Y)){W[V]="[Circular]";continue}if(Z>=f){W[V]="[MaxDepthExceeded]";continue}Q.add(Y),Object.assign(W,this.flattenProperties(Y,V,Q,Z+1));continue}if(UD(Y)){W[V]=Y;continue}try{W[V]=JSON.stringify(Y)}catch{W[V]=String(Y)}}return W}}function UD($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class T4{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,J){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:J})}emitRequired($,J){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:J})}recordCounter($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordHistogram($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordGauge($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:J,attributes:Q,description:Z,required:W===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class p2{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new T4({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let J=this.buildAttributes($.properties);for(let Q of this.adapters)Q.emit($.event,J)}captureRequired($,J){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.emitRequired($,Q)}recordCounter($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordCounter($,J,j,Z,W)}recordHistogram($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordHistogram($,J,j,Z,W)}recordGauge($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordGauge($,J,j,Z,W)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var BZ=()=>{};import{metrics as RD,trace as zD}from"@opentelemetry/api";import{logs as LD}from"@opentelemetry/api-logs";import{OTLPLogExporter as _D}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as OD}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as TD}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as MD}from"@opentelemetry/resources";import{BatchLogRecordProcessor as qD,ConsoleLogRecordExporter as PD,LoggerProvider as ND}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as wD,MeterProvider as SD,PeriodicExportingMetricReader as Of}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as CD,ConsoleSpanExporter as yD,SimpleSpanProcessor as ED}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as bD}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as hD,ATTR_SERVICE_VERSION as kD}from"@opentelemetry/semantic-conventions";class Tf{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,J){this.resolveProperties(J)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class r2{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let J=MD({[hD]:$.serviceName??"cline",...$.serviceVersion?{[kD]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(J),this.loggerProvider=this.createLoggerProvider(J),this.tracerProvider=this.createTracerProvider(J),this.meterProvider)RD.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)LD.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",J){return zD.getTracer($,J??this.options.serviceVersion)}createAdapter($){return new O4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let J=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new p2({...$,adapters:[J],distinctId:S0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let J=AZ(this.options.metricsExporter);if(J.length===0)return null;let Q=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Z=Math.min(30000,Math.floor(Q*0.8)),W=J.map((j)=>gD(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Q,timeout:Z})).filter((j)=>j!==null);if(W.length===0)return null;return new SD({resource:$,readers:W})}createTracerProvider($){let J=AZ(this.options.tracesExporter);if(J.length===0)return null;let Q=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Z=this.options.otlpTracesHeaders??this.options.otlpHeaders,W=[];for(let j of J){let f=xD(j,{endpoint:Q,headers:Z,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(f)W.push(f)}if(W.length===0)return null;return new bD({resource:$,spanProcessors:W})}createLoggerProvider($){let J=AZ(this.options.logsExporter);if(J.length===0)return null;let Q=J.map((Z)=>{let W=ID(Z,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!W)return null;return new qD(W,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Z)=>Z!==null);if(Q.length===0)return null;return new ND({resource:$,processors:Q})}}function M4($){let J=new r2($),Q=J.createTelemetryService($);return Q.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:J,telemetry:Q}}function b1($){if(Q5())return{telemetry:new Tf($)};if($.enabled!==!0)return{telemetry:new p2({...$,distinctId:S0($.distinctId)})};return M4($)}function i2($){let{telemetry:J,provider:Q}=b1($);return{telemetry:J,provider:Q,flush:async()=>{let j=Q;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([J.dispose(),Q?.dispose()])}}}function AZ($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Q)=>Q.trim()).filter((Q)=>Q==="console"||Q==="otlp")}function ID($,J){if($==="console")return new PD;if(!J.endpoint)return null;let Q=KZ(J.endpoint,"/v1/logs");return new _D({url:Q,headers:J.headers})}function xD($,J){if($==="console")return new ED(new yD);if(!J.endpoint)return null;let Q=KZ(J.endpoint,"/v1/traces");return new CD(new TD({url:Q,headers:J.headers}))}function gD($,J){if($==="console")return new Of({exporter:new wD,exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout});if(!J.endpoint)return null;let Q=KZ(J.endpoint,"/v1/metrics");return new Of({exporter:new OD({url:Q,headers:J.headers}),exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout})}function KZ($,J){let Q=new URL($),Z=Q.pathname.endsWith("/")?Q.pathname.slice(0,-1):Q.pathname;return Q.pathname=Z.endsWith(J)?Z:`${Z}${J}`,Q.toString()}var f5=h$(()=>{t0();l2();BZ()});var nY={};w(nY,{normalizeUserMessage:()=>A_,buildInitialUserContent:()=>B_});async function B_($,J,Q,Z){let W=K_(J),j=await F_(Q,Z);if(W.length===0&&!j)return $;let f=[{type:"text",text:$},...W];if(j)f.push(...j);return f}function A_($){if($==null)return"";if(typeof $==="string")return $;let J=$.content;if(typeof J==="string")return J;if(!Array.isArray(J))return"";let Q=[];for(let Z of J)if(Z&&typeof Z==="object"&&Z.type==="text"){let W=Z.text;if(typeof W==="string")Q.push(W)}return Q.join(`
3
+ `)}function K_($){if(!$||$.length===0)return[];let J=[];for(let Q of $){let Z=G_(Q);if(Z)J.push(Z)}return J}function G_($){let J=$.trim();if(!J)return;let Q=J.match(/^data:([^;,]+);base64,(.+)$/);if(Q){let Z=Q[1],W=Q[2];if(!Z||!W)return;return{type:"image",mediaType:Z,data:W}}return{type:"image",mediaType:"image/png",data:J}}async function F_($,J){if(!$||$.length===0)return;let Q=J??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Z=await Promise.all($.map(async(W)=>{let j=W.replace(/\\/g,"/");try{let f=await Q(W);return{type:"file",path:j,content:f}}catch(f){let X=f instanceof Error?f.message:String(f);return{type:"file",path:j,content:`Error fetching content: ${X}`}}}));if(Z.length===0)return;return Z}var HB={};w(HB,{updateMcpServerOAuthState:()=>R2,setMcpServerDisabled:()=>D2,resolveMcpServerRegistrations:()=>K1,resolveDefaultMcpSettingsPath:()=>A0,registerMcpServersFromSettingsFile:()=>z2,normalizeMcpServerOAuthState:()=>I8,loadMcpSettingsFile:()=>F2,listMcpServerOAuthStatuses:()=>o6,hasMcpSettingsFile:()=>r1,getMcpServerOAuthState:()=>U2});import{existsSync as Hq,mkdirSync as WB,readFileSync as NW,writeFileSync as jB}from"node:fs";import{dirname as fB}from"node:path";import{resolveMcpSettingsPath as Bq}from"@cline/shared/storage";import{z as y}from"zod";function PW($){if(!$)return;if($==="http")return"streamableHttp";return $}function A0(){return Bq()}function Oq($){let J=NW($,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse MCP settings JSON at "${$}": ${W}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Q}function VB($,J){if(!Object.hasOwn($,J))return;let Q=$[J];if(!Q||typeof Q!=="object"||Array.isArray(Q))return;return Q}function Tq($,J,Q){Object.defineProperty($,J,{value:Q,enumerable:!0,configurable:!0,writable:!0})}function F2($={}){let J=$.filePath??A0(),Q=NW(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${J}": ${f}`)}let W=_q.safeParse(Z);if(!W.success){let j=W.error.issues.map((f)=>{let X=f.path.join(".");return X?`${X}: ${f.message}`:f.message}).join("; ");throw Error(`Invalid MCP settings at "${J}": ${j}`)}return W.data}function Mq($){let J=NW($,"utf8"),Q;try{Q=JSON.parse(J)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${$}": ${f}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object`);let Z=Q,W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Z}function I8($){if(!$)return;let J={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(J).length>0?J:void 0}function qq($){if($===void 0)return;let J=wW.safeParse($);if(!J.success)return;return I8(J.data)}function r1($={}){let J=$.filePath??A0();return Hq(J)}function K1($={}){let J=F2($);return Object.entries(J.mcpServers).map(([Q,Z])=>({name:Q,transport:Z.transport,disabled:Z.disabled,metadata:Z.metadata,oauth:Z.oauth}))}function D2($){let J=$.filePath??A0(),Q=$.name.trim();if(!Q)throw Error("MCP server settings toggle requires a server name.");let Z=Oq(J),W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${J}": mcpServers must be an object.`);let j={...W},f=VB(j,Q);if(!f)throw Error(`Unknown MCP server: ${Q}`);let X={...f};if($.disabled)X.disabled=!0;else delete X.disabled;Tq(j,Q,X),WB(fB(J),{recursive:!0}),jB(J,`${JSON.stringify({...Z,mcpServers:j},null,2)}
4
+ `)}function U2($,J={}){let Q=F2(J);if(!Object.hasOwn(Q.mcpServers,$))return;return I8(Q.mcpServers[$]?.oauth)}function R2($,J,Q={}){let Z=Q.filePath??A0(),W=Mq(Z),j=W.mcpServers,f=VB(j,$);if(!f)throw Error(`Unknown MCP server: ${$}`);let X=qq(f.oauth)??{},Y=I8(J(X));if(Y)f.oauth=Y;else delete f.oauth;return WB(fB(Z),{recursive:!0}),jB(Z,`${JSON.stringify(W,null,2)}
5
+ `,"utf8"),Y??{}}function o6($={}){return K1($).map((Q)=>{let Z=Q.transport.type!=="stdio",W=Q.oauth?.tokens?.access_token;return{serverName:Q.name,oauthSupported:Z,oauthConfigured:Z&&typeof W==="string"&&W.trim().length>0,lastError:Q.oauth?.lastError,lastAuthenticatedAt:Q.oauth?.lastAuthenticatedAt}}).sort((Q,Z)=>Q.serverName.localeCompare(Z.serverName))}async function z2($,J={}){let Q=K1(J);for(let Z of Q)await $.registerServer(Z);return Q}var s6,XB,wW,Aq,Kq,Gq,Fq,Dq,Uq,YB,Rq,zq,Lq,_q;var cQ=h$(()=>{s6=y.record(y.string(),y.string()),XB=y.record(y.string(),y.unknown()),wW=y.object({clientInformation:y.record(y.string(),y.unknown()).optional(),tokens:y.record(y.string(),y.unknown()).optional(),codeVerifier:y.string().optional(),discoveryState:y.record(y.string(),y.unknown()).optional(),redirectUrl:y.string().url().optional(),lastError:y.string().optional(),lastAuthenticatedAt:y.number().int().positive().optional()}).strip(),Aq=y.object({type:y.literal("stdio"),command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:s6.optional()}),Kq=y.object({type:y.literal("sse"),url:y.string().url(),headers:s6.optional()}),Gq=y.object({type:y.literal("streamableHttp"),url:y.string().url(),headers:s6.optional()}),Fq=y.discriminatedUnion("type",[Aq,Kq,Gq]),Dq=y.object({transport:Fq,disabled:y.boolean().optional(),metadata:XB.optional(),oauth:wW.optional()}),Uq=y.enum(["stdio","sse","http","streamableHttp"]).optional(),YB=y.object({type:y.enum(["stdio","sse","streamableHttp"]).optional(),transportType:Uq,disabled:y.boolean().optional(),metadata:XB.optional(),oauth:wW.optional()});Rq=YB.extend({command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:s6.optional()}).superRefine(($,J)=>{let Q=$.type??PW($.transportType);if(Q&&Q!=="stdio")J.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),zq=YB.extend({url:y.string().url(),headers:s6.optional()}).superRefine(($,J)=>{let Q=$.type??PW($.transportType)??"sse";if(Q!=="sse"&&Q!=="streamableHttp")J.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??PW($.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}}),Lq=y.union([Dq,Rq,zq]),_q=y.object({mcpServers:y.record(y.string(),Lq)}).passthrough()});var lA={};w(lA,{resolveCoreDistinctId:()=>S0,createOpenTelemetryTelemetryService:()=>M4,createConfiguredTelemetryService:()=>b1,createConfiguredTelemetryHandle:()=>i2,OpenTelemetryProvider:()=>r2,OpenTelemetryAdapter:()=>O4});var B9=h$(()=>{l2();f5()});var $G={};w($G,{writeHubDiscovery:()=>V5,withHubStartupLock:()=>H5,verifyHubConnection:()=>H1,truncateNotificationBody:()=>OJ,toHubStatusUrl:()=>UZ,toHubHealthUrl:()=>B5,stopLocalHubServerGracefully:()=>SZ,startHubWebSocketServer:()=>qJ,startHubServer:()=>tK,spawnDetachedHubServerWithRetry:()=>a2,spawnDetachedHubServer:()=>TZ,sendHubCommand:()=>$X,restartLocalHubIfIdleAfterStartupTimeout:()=>D5,resolveWorkspaceHubOwnerContext:()=>If,resolveSharedHubOwnerContext:()=>$1,resolveProductionHubOwnerContext:()=>V1,resolveHubUrl:()=>CZ,resolveHubOwnerContext:()=>I1,resolveHubEndpointOptions:()=>Y1,resolveHubBuildId:()=>Y5,resolveDefaultHubPort:()=>n2,resolveDefaultHubPathname:()=>OZ,resolveDefaultHubHost:()=>_Z,resolveCompatibleLocalHubUrl:()=>S4,resolveClineDir:()=>Ef,resolveClineDataDir:()=>m$,requestHubShutdown:()=>w4,rememberRecoverableLocalHubUrl:()=>W$,readHubDiscovery:()=>X0,readBearerToken:()=>c9,probeHubServer:()=>x1,probeHubConnection:()=>ef,prewarmDetachedHubServer:()=>K5,normalizeHubWebSocketUrl:()=>j$,isHubReconnectableTransportError:()=>NZ,isHubCommandTimeoutError:()=>F5,isDiscoveryFilePresent:()=>hf,ensureHubWebSocketServer:()=>u9,ensureHubServer:()=>eK,ensureDetachedHubServer:()=>uf,ensureCompatibleLocalHubUrl:()=>u$,createLocalHubScheduleRuntimeHandlers:()=>oK,createInMemoryHubOwnerContext:()=>bf,createHubServerUrl:()=>e0,createHubAuthToken:()=>X5,createConfiguredTelemetryService:()=>b1,createConfiguredTelemetryHandle:()=>i2,connectToHub:()=>U5,clearHubDiscovery:()=>C0,NodeHubClient:()=>J1,NativeHubTransportAdapter:()=>MJ,HubUIClient:()=>bZ,HubTransportError:()=>M0,HubSessionClient:()=>EZ,HubServerTransport:()=>f4,HubScheduleService:()=>c2,HubScheduleCommandService:()=>x2,HubCommandError:()=>s2,DEFAULT_HUB_PORT:()=>zZ,DEFAULT_HUB_PATHNAME:()=>LZ,DEFAULT_HUB_HOST:()=>RZ,BrowserWebSocketHubAdapter:()=>TJ});import{createSessionId as VF}from"@cline/shared";function x0($,J){return{version:$.version,requestId:$.requestId,ok:!0,payload:J}}function dj($,J,Q){return{version:$.version,requestId:$.requestId??VF("hubreq_"),ok:!1,error:{code:J,message:Q}}}class x2{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return x0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return x0($,{schedules:this.schedules.listSchedules({enabled:typeof $.payload?.enabled==="boolean"?$.payload.enabled:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0,tags:Array.isArray($.payload?.tags)?$.payload?.tags:void 0})});case"schedule.get":return x0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return x0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return x0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return x0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return x0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return x0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return x0($,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof $.payload?.scheduleId==="string"?$.payload.scheduleId:void 0,status:typeof $.payload?.status==="string"?$.payload.status:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0})});case"schedule.stats":return x0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return x0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return x0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return dj($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(J){return dj($,"schedule_command_failed",J instanceof Error?J.message:String(J))}}toCreateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:J}}toUpdateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:J}}}class Y4{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},J=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Z of J)if(this.materializeOneOff(Z))$.oneOffQueued+=1;let Q=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Z of Q)try{if(this.materializeSchedule(Z))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as zF}from"node:path";import{buildClineSystemPrompt as LF}from"@cline/shared";import{nowIso as aj}from"@cline/shared/db";var K0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},e1=[K0.READ_FILES,K0.SEARCH_CODEBASE,K0.RUN_COMMANDS,K0.FETCH_WEB_CONTENT,K0.APPLY_PATCH,K0.EDITOR,K0.SKILLS,K0.ASK,K0.SUBMIT_AND_EXIT];var pj={};w(pj,{mergeRulesForSystemPrompt:()=>m2,loadRulesForSystemPromptFromWatcher:()=>t9,listEnabledRulesFromWatcher:()=>lj,isRuleEnabled:()=>EJ,formatRulesForSystemPrompt:()=>g2});function EJ($){return $.disabled!==!0}function g2($){if($.length===0)return"";return`
6
6
 
7
7
  # Rules
8
- ${$.map((J)=>`## ${J.name}
9
- ${J.instructions}`).join(`
8
+ ${$.map((Q)=>`## ${Q.name}
9
+ ${Q.instructions}`).join(`
10
10
 
11
- `)}`}function gf($,f){let J=$?.trim(),Q=f?.trim();if(J&&Q)return`${J}
11
+ `)}`}function m2($,J){let Q=$?.trim(),Z=J?.trim();if(Q&&Z)return`${Q}
12
12
 
13
- ${Q}`;return J||Q||void 0}function M3($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(MJ).sort((J,Q)=>J.name.localeCompare(Q.name))}function m9($){return xf(M3($))}var w3={};q(w3,{normalizeWorkspacePath:()=>T1,generateWorkspaceInfoWithDiagnostics:()=>J8,generateWorkspaceInfo:()=>mf,buildWorkspaceMetadataWithInfo:()=>v9,buildWorkspaceMetadata:()=>Q8});import{basename as CG,resolve as yG}from"node:path";import{performance as N3}from"node:perf_hooks";import{processWorkspaceInfo as q3}from"@cline/shared";import SG from"simple-git";function T1($){return yG($)}async function mf($){return(await J8($)).info}function TJ($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function J8($){let f=T1($),J={rootPath:f,hint:CG(f)},Q;try{let Z=SG({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let X=j.map((Y)=>{let A=Y.refs.fetch||Y.refs.push;return`${Y.name}: ${A}`});J.associatedRemoteUrls=X}}catch(j){Q??=TJ(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){Q??=TJ(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){Q??=TJ(j)}return{info:J,vcsType:"git",error:Q}}catch(Z){return{info:J,vcsType:"none",error:TJ(Z)}}}async function Q8($){let f=await mf($);return q3(f)}async function v9($){let f=N3.now(),J=await J8($),Q=N3.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:q3(Z),durationMs:Q,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as EG,writeFileSync as hG}from"node:fs";import{join as bG}from"node:path";import{resolveCronReportsDir as kG}from"@cline/shared/storage";function e1($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function b$($,f){if(f===void 0||f===null)return;return`${$}: ${e1(f)}`}function IG($,f,J){let Q=[`runId: ${e1($.runId)}`,`specId: ${e1(f.specId)}`,`externalId: ${e1(f.externalId)}`,`title: ${e1(f.title)}`,`triggerKind: ${e1($.triggerKind)}`,`status: ${e1($.status)}`,`sourcePath: ${e1(f.sourcePath)}`],Z=[b$("sessionId",$.sessionId),b$("startedAt",$.startedAt),b$("completedAt",$.completedAt),b$("triggerEventId",$.triggerEventId),b$("triggerEventType",J?.eventType),b$("triggerEventSource",J?.source),b$("triggerEventSubject",J?.subject)];for(let W of Z)if(W)Q.push(W);return`---
14
- ${Q.join(`
13
+ ${Z}`;return Q||Z||void 0}function lj($){return[...$.getSnapshot("rule").values()].map((Q)=>Q.item).filter(EJ).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function t9($){return g2(lj($))}var nj={};w(nj,{normalizeWorkspacePath:()=>P1,generateWorkspaceInfoWithDiagnostics:()=>V4,generateWorkspaceInfo:()=>v2,buildWorkspaceMetadataWithInfo:()=>e9,buildWorkspaceMetadata:()=>H4});import{basename as HF,resolve as BF}from"node:path";import{performance as rj}from"node:perf_hooks";import{processWorkspaceInfo as ij}from"@cline/shared";import AF from"simple-git";function P1($){return BF($)}async function v2($){return(await V4($)).info}function bJ($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function V4($){let J=P1($),Q={rootPath:J,hint:HF(J)},Z;try{let W=AF({baseDir:J});if(!await W.checkIsRepo())return{info:Q,vcsType:"none"};try{let f=await W.getRemotes(!0);if(f.length>0){let X=f.map((Y)=>{let V=Y.refs.fetch||Y.refs.push;return`${Y.name}: ${V}`});Q.associatedRemoteUrls=X}}catch(f){Z??=bJ(f)}try{let f=(await W.revparse(["HEAD"])).trim();if(f.length>0)Q.latestGitCommitHash=f}catch(f){Z??=bJ(f)}try{let f=(await W.branch()).current.trim();if(f.length>0)Q.latestGitBranchName=f}catch(f){Z??=bJ(f)}return{info:Q,vcsType:"git",error:Z}}catch(W){return{info:Q,vcsType:"none",error:bJ(W)}}}async function H4($){let J=await v2($);return ij(J)}async function e9($){let J=rj.now(),Q=await V4($),Z=rj.now()-J,W=Q.info;return{workspaceInfo:W,workspaceMetadata:ij(W),durationMs:Z,vcsType:Q.vcsType,initError:Q.error}}import{mkdirSync as KF,writeFileSync as GF}from"node:fs";import{join as FF}from"node:path";import{resolveCronReportsDir as DF}from"@cline/shared/storage";function $$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function k$($,J){if(J===void 0||J===null)return;return`${$}: ${$$(J)}`}function UF($,J,Q){let Z=[`runId: ${$$($.runId)}`,`specId: ${$$(J.specId)}`,`externalId: ${$$(J.externalId)}`,`title: ${$$(J.title)}`,`triggerKind: ${$$($.triggerKind)}`,`status: ${$$($.status)}`,`sourcePath: ${$$(J.sourcePath)}`],W=[k$("sessionId",$.sessionId),k$("startedAt",$.startedAt),k$("completedAt",$.completedAt),k$("triggerEventId",$.triggerEventId),k$("triggerEventType",Q?.eventType),k$("triggerEventSource",Q?.source),k$("triggerEventSubject",Q?.subject)];for(let j of W)if(j)Z.push(j);return`---
14
+ ${Z.join(`
15
15
  `)}
16
16
  ---
17
- `}function xG($){let f=[];if($.triggerEvent){let J=$.triggerEvent,Q=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((Z)=>Z.length>0);f.push(`## Trigger Event
17
+ `}function RF($){let J=[];if($.triggerEvent){let Q=$.triggerEvent,Z=[`- eventId: ${Q.eventId}`,`- eventType: ${Q.eventType}`,`- source: ${Q.source}`,Q.subject?`- subject: ${Q.subject}`:"",`- occurredAt: ${Q.occurredAt}`,Q.dedupeKey?`- dedupeKey: ${Q.dedupeKey}`:"",Q.attributes?`- attributes: ${JSON.stringify(Q.attributes)}`:""].filter((W)=>W.length>0);J.push(`## Trigger Event
18
18
 
19
- ${Q.join(`
19
+ ${Z.join(`
20
20
  `)}
21
- `)}if($.error)f.push(`## Error
21
+ `)}if($.error)J.push(`## Error
22
22
 
23
23
  ${$.error}
24
- `);if($.finalText&&$.finalText.trim().length>0)f.push(`## Summary
24
+ `);if($.finalText&&$.finalText.trim().length>0)J.push(`## Summary
25
25
 
26
26
  ${$.finalText.trim()}
27
- `);if($.usage){let J=$.usage,Q=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",$.durationMs!==void 0?`- durationMs: ${$.durationMs}`:""].filter((Z)=>Z.length>0);if(Q.length>0)f.push(`## Usage
27
+ `);if($.usage){let Q=$.usage,Z=[Q.inputTokens!==void 0?`- inputTokens: ${Q.inputTokens}`:"",Q.outputTokens!==void 0?`- outputTokens: ${Q.outputTokens}`:"",Q.cacheReadTokens!==void 0?`- cacheReadTokens: ${Q.cacheReadTokens}`:"",Q.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${Q.cacheWriteTokens}`:"",Q.totalCost!==void 0?`- totalCostUsd: ${Q.totalCost}`:"",$.durationMs!==void 0?`- durationMs: ${$.durationMs}`:""].filter((W)=>W.length>0);if(Z.length>0)J.push(`## Usage
28
28
 
29
- ${Q.join(`
29
+ ${Z.join(`
30
30
  `)}
31
- `)}if($.toolCalls&&$.toolCalls.length>0){let J=$.toolCalls.map((Q)=>{let Z=[`- ${Q.name}`];if(Q.durationMs!==void 0)Z.push(`(${Q.durationMs}ms)`);if(Q.error)Z.push(`error: ${Q.error}`);return Z.join(" ")});f.push(`## Tool Calls
31
+ `)}if($.toolCalls&&$.toolCalls.length>0){let Q=$.toolCalls.map((Z)=>{let W=[`- ${Z.name}`];if(Z.durationMs!==void 0)W.push(`(${Z.durationMs}ms)`);if(Z.error)W.push(`error: ${Z.error}`);return W.join(" ")});J.push(`## Tool Calls
32
32
 
33
- ${J.join(`
33
+ ${Q.join(`
34
34
  `)}
35
- `)}return f.join(`
36
- `)}function c9($){let f=kG($.specs);EG(f,{recursive:!0});let J=bG(f,`${$.run.runId}.md`),Q=`${IG($.run,$.spec,$.data.triggerEvent)}
37
- ${xG($.data)}`;return hG(J,Q,"utf8"),J}class u9{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=Q)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var vG=15000,cG=90,y3=["rules","skills","plugins"];function uG($,f){return new Set($.extensions??y3).has(f)}function dG($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)J[Q]={enabled:!0,autoApprove:!0};if(f==="yolo")J[H0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function lG($){let f=$?.trim();if(!f)return;return["# Notes Directory",`Use ${f} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
38
- `)}class d9 extends Error{constructor($){super($);this.name="TimeoutError"}}async function pG($,f){if(f<=0)return $;let J,Q=new Promise((Z,W)=>{J=setTimeout(()=>{W(new d9("cron run timed out"))},f)});try{return await Promise.race([$,Q])}finally{if(J)clearTimeout(J)}}class Z8{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 u9($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??cG)*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??vG);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:C3(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,Q)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let W=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,X,Y=Date.now(),A;if(J.timeoutSeconds&&J.timeoutSeconds>0)A=Y+J.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let V=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(V)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let B={config:V,prompt:this.buildPrompt(J,W)},K=this.options.runtimeHandlers.sendSession(j,B),G=A?Math.max(1,A-Date.now()):0,P=(await pG(K,G)).result,F=Date.now(),D=c9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:P.text,usage:P.usage,toolCalls:P.toolCalls,durationMs:F-Y,triggerEvent:W}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:D,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,C3())}catch(V){let H=V instanceof d9;if(j&&H)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=V instanceof Error?V.message:String(V),K=Date.now(),G=c9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-Y,triggerEvent:W}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:B,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(X?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(J);if(!Q)return;let Z=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:Z,errorMessage:Q.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let Q={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
35
+ `)}return J.join(`
36
+ `)}function $Z($){let J=DF($.specs);KF(J,{recursive:!0});let Q=FF(J,`${$.run.runId}.md`),Z=`${UF($.run,$.spec,$.data.triggerEvent)}
37
+ ${RF($.data)}`;return GF(Q,Z,"utf8"),Q}class JZ{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,J,Q){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Z=Math.max(1,Math.floor(Q)),W=this.activeExecutions.get($)??new Set;if(W.size>=Z)return!1;return W.add(J),this.activeExecutions.set($,W),!0}release($,J){let Q=this.activeExecutions.get($);if(!Q)return;if(Q.delete(J),Q.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let J of this.activeExecutions.values())$+=J.size;return $}}var _F=15000,OF=90,sj=["rules","skills","plugins"];function TF($,J){return new Set($.extensions??sj).has(J)}function MF($,J){if($.tools===void 0)return{"*":{autoApprove:!0}};let Q={"*":{enabled:!1,autoApprove:!0}};for(let Z of $.tools)Q[Z]={enabled:!0,autoApprove:!0};if(J==="yolo")Q[K0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Q}function qF($){let J=$?.trim();if(!J)return;return["# Notes Directory",`Use ${J} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
38
+ `)}class QZ extends Error{constructor($){super($);this.name="TimeoutError"}}async function PF($,J){if(J<=0)return $;let Q,Z=new Promise((W,j)=>{Q=setTimeout(()=>{j(new QZ("cron run timed out"))},J)});try{return await Promise.race([$,Z])}finally{if(Q)clearTimeout(Q)}}class B4{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 JZ($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??OF)*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??_F);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let J=[...this.activeRuns.entries()];await Promise.all(J.map(async([Q,Z])=>{if(Z.sessionId)try{await this.options.runtimeHandlers.abortSession(Z.sessionId)}catch{}try{this.store.requeueRun({runId:Q,claimToken:Z.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:aj(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((J)=>this.executeClaim(J)))}catch($){let J=this.options.logger;if(J)if(J.error)J.error("cron.runner.tick.failed",{error:$});else J.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,J])=>{let Q=this.store.getRun($);return Q?[{...Q,...J}]:[]})}async executeClaim($){let J=$.run,Q=this.store.getSpec(J.specId);if(!Q){this.store.completeRun(J.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Q.enabled||Q.removed){this.store.completeRun(J.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Z=Q.maxParallel&&Q.maxParallel>0?Q.maxParallel:1;if(!this.limiter.acquire(Q.specId,J.runId,Z)){this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Q.specId,J.runId),this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(J.runId,{claimToken:$.claimToken});let j=J.triggerEventId?this.store.getEventLog(J.triggerEventId):void 0,f,X,Y=Date.now(),V;if(Q.timeoutSeconds&&Q.timeoutSeconds>0)V=Y+Q.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Q);if(f=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!f)throw Error("runtime returned empty sessionId");this.activeRuns.set(J.runId,{claimToken:$.claimToken,sessionId:f}),this.store.attachSessionIdToRun(J.runId,f);let A={config:H,prompt:this.buildPrompt(Q,j)},K=this.options.runtimeHandlers.sendSession(f,A),G=V?Math.max(1,V-Date.now()):0,D=(await PF(K,G)).result,U=Date.now(),F=$Z({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"done"},spec:Q,data:{finalText:D.text,usage:D.usage,toolCalls:D.toolCalls,durationMs:U-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"done",sessionId:f,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Q,J.runId),this.store.updateSpecLastRunAt(Q.specId,aj())}catch(H){let B=H instanceof QZ;if(f&&B)try{await this.options.runtimeHandlers.abortSession(f)}catch{}let A=H instanceof Error?H.message:String(H),K=Date.now(),G=$Z({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"failed"},spec:Q,data:{error:A,durationMs:K-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"failed",sessionId:f,reportPath:G,error:A,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Q,J.runId)}finally{if(X?.(),f)try{await this.options.runtimeHandlers.stopSession(f)}catch{}this.activeRuns.delete(J.runId),this.limiter.release(Q.specId,J.runId)}}publishScheduleExecutionEvent($,J,Q){if(J.source!=="hub-schedule"||!this.options.eventPublisher)return;let Z=this.store.getRun(Q);if(!Z)return;let W=Z.status==="done"?"success":Z.status==="cancelled"?"aborted":Z.status==="running"?"running":Z.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:J.externalId,executionId:Z.runId,sessionId:Z.sessionId,triggeredAt:new Date(Z.scheduledFor??Z.createdAt).getTime(),startedAt:Z.startedAt?new Date(Z.startedAt).getTime():void 0,endedAt:Z.completedAt?new Date(Z.completedAt).getTime():void 0,status:W,errorMessage:Z.error})}buildPrompt($,J){let Q=$.prompt??"";if(!J)return Q;let Z={eventId:J.eventId,eventType:J.eventType,source:J.source,subject:J.subject,occurredAt:J.occurredAt,workspaceRoot:J.workspaceRoot,dedupeKey:J.dedupeKey,attributes:J.attributes,payload:J.payload};return`${Q}
39
39
 
40
40
  Trigger event:
41
- ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,Q){let Z=lG($.notesDirectory),W=gf(void 0,Z),j=await Q8(f),X=mG({ide:"Cline Cron",workspaceRoot:f,workspaceName:gG(f),metadata:j,rules:$.systemPrompt?void 0:W,mode:J,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?gf(X,W)??X:X}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),Q=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,W=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:W,provider:J,model:Q,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:dG($,j),configExtensions:y3.filter((X)=>uG($,X))}}}function W8($,f,J,Q){let Z=new Set;function W(j){let X=j.toLowerCase();if(Q){let A=Q.indexOf(X);if(A!==-1)return A+f}let Y=Number(j);if(!Number.isInteger(Y)||Y<f||Y>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return Y}for(let j of $.split(",")){if(j==="*"){for(let A=f;A<=J;A+=1)Z.add(A);continue}let X=j.indexOf("/");if(X!==-1){let A=j.slice(0,X),V=Number(j.slice(X+1));if(!Number.isInteger(V)||V<1)throw Error(`Invalid step "${j.slice(X+1)}"`);let H=f,B=J;if(A!=="*"){let K=A.indexOf("-");if(K!==-1)H=W(A.slice(0,K)),B=W(A.slice(K+1));else H=W(A)}if(H>B)throw Error(`Invalid cron range "${A}"`);for(let K=H;K<=B;K+=V)Z.add(K);continue}let Y=j.indexOf("-");if(Y!==-1){let A=W(j.slice(0,Y)),V=W(j.slice(Y+1));if(A>V)throw Error(`Invalid cron range "${j}"`);for(let H=A;H<=V;H+=1)Z.add(H);continue}Z.add(W(j))}return[...Z].sort((j,X)=>j-X)}var rG=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],E3=["sun","mon","tue","wed","thu","fri","sat"];function j8($,f,J){let Q=$[f];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return Q}function l9($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function p9($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:W8(j8(f,0,$),0,59),hours:W8(j8(f,1,$),0,23),daysOfMonth:W8(j8(f,2,$),1,31),months:W8(j8(f,3,$),1,12,rG),daysOfWeek:W8(j8(f,4,$),0,6,E3)}}function r9($){p9($)}function h3($,f,J=Date.now()){k$($,J,f)}var S3=new Map,iG=new Map(E3.map(($,f)=>[$,f]));function b3($){let f=$?.trim();return f?f:void 0}function k3($){let f=S3.get($);if(f)return f;let J=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return S3.set($,J),J}function nG($){let f=b3($);if(!f)return;k3(f).format(new Date)}function aG($,f){let J=k3(f).formatToParts(new Date($)),Q=new Map(J.map((j)=>[j.type,j.value])),Z=Q.get("weekday")?.toLowerCase().slice(0,3)??"",W=iG.get(Z);if(W===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:W,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function tG($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function sG($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function oG($,f,J){let Q=p9($),Z=new Date(f);Z.setSeconds(0,0);let W=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let X=j.getTime();while(W<=X){if(sG(Q,aG(W,J)))return W;W+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function k$($,f,J){let Q=b3(J);if(Q)return nG(Q),oG($,f,Q);let Z=p9($),W=new Date(f);W.setSeconds(0,0),W=new Date(W.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(W<=j){let{month:X,dayOfMonth:Y,dayOfWeek:A,hour:V,minute:H}=tG(W.getTime());if(!Z.months.includes(X)){let B=Z.months.find((G)=>G>X)??l9(Z.months,"months"),K=B<=X?1:0;W=new Date(W.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(Y)||!Z.daysOfWeek.includes(A)){W=new Date(W.getFullYear(),W.getMonth(),Y+1,0,0,0,0);continue}if(!Z.hours.includes(V)){let B=Z.hours.find((G)=>G>V)??l9(Z.hours,"hours"),K=B<=V?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(H)){let B=Z.minutes.find((G)=>G>H)??l9(Z.minutes,"minutes"),K=B<=H?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate(),W.getHours()+K,B,0,0);continue}return W.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as X8}from"node:crypto";import{asOptionalString as x,asString as n,loadSqliteDb as $F,nowIso as F0}from"@cline/shared/db";import{resolveCronDbPath as fF}from"@cline/shared/storage";var eG=[`CREATE TABLE IF NOT EXISTS cron_specs (
41
+ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Q=setInterval(()=>{let Z=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Z))clearInterval(Q)},J);return()=>clearInterval(Q)}async buildSystemPrompt($,J,Q,Z){let W=qF($.notesDirectory),j=m2(void 0,W),f=await H4(J),X=LF({ide:"Cline Cron",workspaceRoot:J,workspaceName:zF(J),metadata:f,rules:$.systemPrompt?void 0:j,mode:Q,providerId:Z,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?m2(X,j)??X:X}async buildStartRequest($){let J=($.workspaceRoot??"").trim(),Q=($.providerId??"").trim(),Z=($.modelId??"").trim(),W=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():J;if(!J)throw Error("cron spec requires workspaceRoot");let f=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:J,cwd:j,provider:Q,model:Z,mode:f,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,J,f,Q),maxIterations:$.maxIterations,enableTools:W?.enableTools??!0,enableSpawn:W?.enableSpawn??!0,enableTeams:W?.enableTeams??!0,autoApproveTools:W?.autoApproveTools??!0,toolPolicies:MF($,f),configExtensions:sj.filter((X)=>TF($,X))}}}function A4($,J,Q,Z){let W=new Set;function j(f){let X=f.toLowerCase();if(Z){let V=Z.indexOf(X);if(V!==-1)return V+J}let Y=Number(f);if(!Number.isInteger(Y)||Y<J||Y>Q)throw Error(`Invalid cron value "${f}" for range [${J}-${Q}]`);return Y}for(let f of $.split(",")){if(f==="*"){for(let V=J;V<=Q;V+=1)W.add(V);continue}let X=f.indexOf("/");if(X!==-1){let V=f.slice(0,X),H=Number(f.slice(X+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${f.slice(X+1)}"`);let B=J,A=Q;if(V!=="*"){let K=V.indexOf("-");if(K!==-1)B=j(V.slice(0,K)),A=j(V.slice(K+1));else B=j(V)}if(B>A)throw Error(`Invalid cron range "${V}"`);for(let K=B;K<=A;K+=H)W.add(K);continue}let Y=f.indexOf("-");if(Y!==-1){let V=j(f.slice(0,Y)),H=j(f.slice(Y+1));if(V>H)throw Error(`Invalid cron range "${f}"`);for(let B=V;B<=H;B+=1)W.add(B);continue}W.add(j(f))}return[...W].sort((f,X)=>f-X)}var NF=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],tj=["sun","mon","tue","wed","thu","fri","sat"];function K4($,J,Q){let Z=$[J];if(typeof Z!=="string")throw Error(`Invalid cron pattern "${Q}": missing field ${J+1}`);return Z}function ZZ($,J){let Q=$[0];if(typeof Q!=="number")throw Error(`Invalid cron pattern: no values parsed for ${J}`);return Q}function WZ($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${J.length}`);return{minutes:A4(K4(J,0,$),0,59),hours:A4(K4(J,1,$),0,23),daysOfMonth:A4(K4(J,2,$),1,31),months:A4(K4(J,3,$),1,12,NF),daysOfWeek:A4(K4(J,4,$),0,6,tj)}}function jZ($){WZ($)}function ej($,J,Q=Date.now()){I$($,Q,J)}var oj=new Map,wF=new Map(tj.map(($,J)=>[$,J]));function $f($){let J=$?.trim();return J?J:void 0}function Jf($){let J=oj.get($);if(J)return J;let Q=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return oj.set($,Q),Q}function SF($){let J=$f($);if(!J)return;Jf(J).format(new Date)}function CF($,J){let Q=Jf(J).formatToParts(new Date($)),Z=new Map(Q.map((f)=>[f.type,f.value])),W=Z.get("weekday")?.toLowerCase().slice(0,3)??"",j=wF.get(W);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${J}"`);return{month:Number(Z.get("month")),dayOfMonth:Number(Z.get("day")),dayOfWeek:j,hour:Number(Z.get("hour")),minute:Number(Z.get("minute"))}}function yF($){let J=new Date($);return{month:J.getMonth()+1,dayOfMonth:J.getDate(),dayOfWeek:J.getDay(),hour:J.getHours(),minute:J.getMinutes()}}function EF($,J){return $.months.includes(J.month)&&$.daysOfMonth.includes(J.dayOfMonth)&&$.daysOfWeek.includes(J.dayOfWeek)&&$.hours.includes(J.hour)&&$.minutes.includes(J.minute)}function bF($,J,Q){let Z=WZ($),W=new Date(J);W.setSeconds(0,0);let j=W.getTime()+60000,f=new Date(J);f.setFullYear(f.getFullYear()+4);let X=f.getTime();while(j<=X){if(EF(Z,CF(j,Q)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Q}"`)}function I$($,J,Q){let Z=$f(Q);if(Z)return SF(Z),bF($,J,Z);let W=WZ($),j=new Date(J);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let f=new Date(J);f.setFullYear(f.getFullYear()+4);while(j<=f){let{month:X,dayOfMonth:Y,dayOfWeek:V,hour:H,minute:B}=yF(j.getTime());if(!W.months.includes(X)){let A=W.months.find((G)=>G>X)??ZZ(W.months,"months"),K=A<=X?1:0;j=new Date(j.getFullYear()+K,A-1,1,0,0,0,0);continue}if(!W.daysOfMonth.includes(Y)||!W.daysOfWeek.includes(V)){j=new Date(j.getFullYear(),j.getMonth(),Y+1,0,0,0,0);continue}if(!W.hours.includes(H)){let A=W.hours.find((G)=>G>H)??ZZ(W.hours,"hours"),K=A<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+K,A,0,0,0);continue}if(!W.minutes.includes(B)){let A=W.minutes.find((G)=>G>B)??ZZ(W.minutes,"minutes"),K=A<=B?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+K,A,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as G4}from"node:crypto";import{asOptionalString as x,asString as a,loadSqliteDb as kF,nowIso as D0}from"@cline/shared/db";import{resolveCronDbPath as IF}from"@cline/shared/storage";var hF=[`CREATE TABLE IF NOT EXISTS cron_specs (
42
42
  spec_id TEXT PRIMARY KEY,
43
43
  external_id TEXT NOT NULL,
44
44
  source_path TEXT NOT NULL UNIQUE,
@@ -129,17 +129,17 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
129
129
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
130
130
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
131
131
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
132
- ON cron_specs(source_path);`];function I3($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of eG)$.exec(f)}function NJ($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function i9($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let Q=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function I$($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function $$($){return{specId:n($.spec_id),externalId:n($.external_id),sourcePath:n($.source_path),triggerKind:n($.trigger_kind),sourceMtimeMs:I$($.source_mtime_ms),sourceHash:x($.source_hash),parseStatus:n($.parse_status)==="invalid"?"invalid":"valid",parseError:x($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:n($.title),prompt:x($.prompt),workspaceRoot:x($.workspace_root),scheduleExpr:x($.schedule_expr),timezone:x($.timezone),eventType:x($.event_type),filters:NJ(x($.filters_json)),debounceSeconds:I$($.debounce_seconds),dedupeWindowSeconds:I$($.dedupe_window_seconds),cooldownSeconds:I$($.cooldown_seconds),mode:x($.mode),systemPrompt:x($.system_prompt),providerId:x($.provider_id),modelId:x($.model_id),maxIterations:I$($.max_iterations),timeoutSeconds:I$($.timeout_seconds),maxParallel:I$($.max_parallel),tools:i9(x($.tools_json),{preserveEmpty:!0}),notesDirectory:x($.notes_directory),extensions:i9(x($.extensions_json),{preserveEmpty:!0}),source:x($.source),tags:i9(x($.tags_json)),metadata:NJ(x($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:x($.last_materialized_run_id),lastRunAt:x($.last_run_at),nextRunAt:x($.next_run_at),createdAt:n($.created_at),updatedAt:n($.updated_at)}}function n9($){return{runId:n($.run_id),specId:n($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:n($.trigger_kind),status:n($.status),claimToken:x($.claim_token),claimStartedAt:x($.claim_started_at),claimUntilAt:x($.claim_until_at),scheduledFor:x($.scheduled_for),triggerEventId:x($.trigger_event_id),startedAt:x($.started_at),completedAt:x($.completed_at),sessionId:x($.session_id),reportPath:x($.report_path),error:x($.error),attemptCount:Number($.attempt_count??0),createdAt:n($.created_at),updatedAt:n($.updated_at)}}function x3($){return{eventId:n($.event_id),eventType:n($.event_type),source:n($.source),subject:x($.subject),occurredAt:n($.occurred_at),receivedAt:n($.received_at),workspaceRoot:x($.workspace_root),dedupeKey:x($.dedupe_key),payload:NJ(x($.payload_json)),attributes:NJ(x($.attributes_json)),processingStatus:n($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:x($.error),createdAt:n($.created_at),updatedAt:n($.updated_at)}}function g3($){return $?JSON.stringify($):null}var JF=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function m3($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function QF($,f,J,Q){for(let Z of JF){let W=$[Z],j=f[Z];if(m3(W)!==m3(j))return!0}if(J===!1&&Q===!0)return!0;return!1}function ZF($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function WF($){return`hub/schedules/${$}.cron.md`}function jF($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function a9($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((f)=>f.trim().length>0),enabled:$.enabled!==!1,metadata:jF($)}}function v3($){return JSON.stringify(a9($))}function XF($,f){let J=$.metadata?{...$.metadata}:{},Q=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,W=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:Q,tags:f.tags??$.tags,runtimeOptions:W,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class Y8{db;constructor($={}){let f=$.dbPath??fF();this.db=$F(f),I3(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?$$(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?$$(f):void 0}getSpecByExternalId($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return f?$$(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>$$(j))}createHubSchedule($){let f=`sched_${X8()}`,J=this.upsertSpec({externalId:f,sourcePath:WF(f),triggerKind:"schedule",sourceHash:v3($),parseStatus:"valid",spec:a9($)});this.initializeScheduleNextRun(J.record.specId);let Q=this.getSpec(J.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
132
+ ON cron_specs(source_path);`];function Qf($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let J of hF)$.exec(J)}function hJ($){if(!$)return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function fZ($,J={}){if(!$)return;try{let Q=JSON.parse($);if(!Array.isArray(Q))return;let Z=Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if(J.preserveEmpty)return Z;return Z.length>0?Z:void 0}catch{return}}function x$($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function J$($){return{specId:a($.spec_id),externalId:a($.external_id),sourcePath:a($.source_path),triggerKind:a($.trigger_kind),sourceMtimeMs:x$($.source_mtime_ms),sourceHash:x($.source_hash),parseStatus:a($.parse_status)==="invalid"?"invalid":"valid",parseError:x($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:a($.title),prompt:x($.prompt),workspaceRoot:x($.workspace_root),scheduleExpr:x($.schedule_expr),timezone:x($.timezone),eventType:x($.event_type),filters:hJ(x($.filters_json)),debounceSeconds:x$($.debounce_seconds),dedupeWindowSeconds:x$($.dedupe_window_seconds),cooldownSeconds:x$($.cooldown_seconds),mode:x($.mode),systemPrompt:x($.system_prompt),providerId:x($.provider_id),modelId:x($.model_id),maxIterations:x$($.max_iterations),timeoutSeconds:x$($.timeout_seconds),maxParallel:x$($.max_parallel),tools:fZ(x($.tools_json),{preserveEmpty:!0}),notesDirectory:x($.notes_directory),extensions:fZ(x($.extensions_json),{preserveEmpty:!0}),source:x($.source),tags:fZ(x($.tags_json)),metadata:hJ(x($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:x($.last_materialized_run_id),lastRunAt:x($.last_run_at),nextRunAt:x($.next_run_at),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function XZ($){return{runId:a($.run_id),specId:a($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:a($.trigger_kind),status:a($.status),claimToken:x($.claim_token),claimStartedAt:x($.claim_started_at),claimUntilAt:x($.claim_until_at),scheduledFor:x($.scheduled_for),triggerEventId:x($.trigger_event_id),startedAt:x($.started_at),completedAt:x($.completed_at),sessionId:x($.session_id),reportPath:x($.report_path),error:x($.error),attemptCount:Number($.attempt_count??0),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function Zf($){return{eventId:a($.event_id),eventType:a($.event_type),source:a($.source),subject:x($.subject),occurredAt:a($.occurred_at),receivedAt:a($.received_at),workspaceRoot:x($.workspace_root),dedupeKey:x($.dedupe_key),payload:hJ(x($.payload_json)),attributes:hJ(x($.attributes_json)),processingStatus:a($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:x($.error),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function Wf($){return $?JSON.stringify($):null}var xF=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function jf($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function gF($,J,Q,Z){for(let W of xF){let j=$[W],f=J[W];if(jf(j)!==jf(f))return!0}if(Q===!1&&Z===!0)return!0;return!1}function mF($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function vF($){return`hub/schedules/${$}.cron.md`}function cF($){let J={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(J).length>0?J:void 0}function YZ($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((J)=>J.trim().length>0),enabled:$.enabled!==!1,metadata:cF($)}}function ff($){return JSON.stringify(YZ($))}function uF($,J){let Q=$.metadata?{...$.metadata}:{},Z=J.createdBy===null?void 0:J.createdBy!==void 0?J.createdBy:typeof Q.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,W=J.cwd!==void 0?J.cwd:typeof Q.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,j=J.runtimeOptions!==void 0?J.runtimeOptions:Q.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0;return delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions,{name:J.name??$.title,cronPattern:J.cronPattern??$.scheduleExpr??"",prompt:J.prompt??$.prompt??"",workspaceRoot:J.workspaceRoot??$.workspaceRoot??"",cwd:W,modelSelection:J.modelSelection!==void 0?J.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:J.enabled??$.enabled,mode:J.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:J.systemPrompt===null?void 0:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,maxIterations:J.maxIterations===null?void 0:J.maxIterations!==void 0?J.maxIterations:$.maxIterations,timeoutSeconds:J.timeoutSeconds===null?void 0:J.timeoutSeconds!==void 0?J.timeoutSeconds:$.timeoutSeconds,maxParallel:J.maxParallel??$.maxParallel??1,createdBy:Z,tags:J.tags??$.tags,runtimeOptions:j,metadata:J.metadata!==void 0?J.metadata:Object.keys(Q).length>0?Q:void 0}}class F4{db;constructor($={}){let J=$.dbPath??IF();this.db=kF(J),Qf(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return J?J$(J):void 0}getSpec($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return J?J$(J):void 0}getSpecByExternalId($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return J?J$(J):void 0}listSpecs($={}){let J=[],Q=[];if($.triggerKind)J.push("trigger_kind = ?"),Q.push($.triggerKind);if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.parseStatus)J.push("parse_status = ?"),Q.push($.parseStatus);if(!$.includeRemoved)J.push("removed = 0");let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Z} ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((f)=>J$(f))}createHubSchedule($){let J=`sched_${G4()}`,Q=this.upsertSpec({externalId:J,sourcePath:vF(J),triggerKind:"schedule",sourceHash:ff($),parseStatus:"valid",spec:YZ($)});this.initializeScheduleNextRun(Q.record.specId);let Z=this.getSpec(Q.record.specId);if(!Z)throw Error("failed to create hub schedule");return Z}getHubSchedule($){let J=this.db.prepare(`SELECT * FROM cron_specs
133
133
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
134
- ORDER BY created_at ASC LIMIT 1`).get($);return f?$$(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let W of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${W.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
135
- WHERE ${f.join(" AND ")}
136
- ORDER BY created_at DESC LIMIT ?`).all(...J,Q).map((W)=>$$(W))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let Q=XF(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:v3(Q),parseStatus:"valid",spec:a9(Q)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:F0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
134
+ ORDER BY created_at ASC LIMIT 1`).get($);return J?J$(J):void 0}listHubSchedules($={}){let J=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Q=[];if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)J.push("tags_json LIKE ?"),Q.push(`%"${j.trim()}"%`);let Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
135
+ WHERE ${J.join(" AND ")}
136
+ ORDER BY created_at DESC LIMIT ?`).all(...Q,Z).map((j)=>J$(j))}updateHubSchedule($,J){let Q=this.getHubSchedule($);if(!Q)return;let Z=uF(Q,J),W=this.upsertSpec({externalId:$,sourcePath:Q.sourcePath,triggerKind:"schedule",sourceHash:ff(Z),parseStatus:"valid",spec:YZ(Z)});if(J.cronPattern!==void 0||J.enabled!==void 0)this.initializeScheduleNextRun(W.record.specId);return this.getSpec(W.record.specId)}deleteHubSchedule($){let J=this.getHubSchedule($);if(!J)return!1;return this.markSpecRemoved(J.specId),this.cancelQueuedRunsForSpec(J.specId),!0}enqueueHubScheduleRun($,J="manual"){let Q=this.getHubSchedule($);if(!Q||!Q.enabled||Q.removed||Q.parseStatus!=="valid")return;return this.enqueueRun({specId:Q.specId,specRevision:Q.revision,triggerKind:J,scheduledFor:D0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
137
137
  WHERE trigger_kind = 'event'
138
138
  AND event_type = ?
139
139
  AND enabled = 1
140
140
  AND removed = 0
141
141
  AND parse_status = 'valid'
142
- ORDER BY created_at ASC`).all($).map((J)=>$$(J))}upsertSpec($){let f=F0(),J=this.getSpecBySourcePath($.sourcePath),Q=$.spec,Z={title:Q?.title??J?.title??ZF($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},W=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!J){let V=`cspec_${X8()}`;this.insertSpecRow(V,$,Z,W,f);let H=this.getSpec(V);if(!H)throw Error("failed to insert cron_spec row");return{record:H,created:!0,revisionChanged:!0}}let X=J.sourceHash!==$.sourceHash&&QF(J,Z,J.enabled,W),Y=X?J.revision+1:J.revision;this.updateSpecRow(J.specId,$,Z,W,Y,f);let A=this.getSpec(J.specId);if(!A)throw Error("failed to reload cron_spec after update");return{record:A,created:!1,revisionChanged:X}}insertSpecRow($,f,J,Q,Z){let W=f.spec;this.db.prepare(`INSERT INTO cron_specs (
142
+ ORDER BY created_at ASC`).all($).map((Q)=>J$(Q))}upsertSpec($){let J=D0(),Q=this.getSpecBySourcePath($.sourcePath),Z=$.spec,W={title:Z?.title??Q?.title??mF($.sourcePath),prompt:Z?.prompt,workspaceRoot:Z?.workspaceRoot,scheduleExpr:Z?.triggerKind==="schedule"?Z.schedule:void 0,timezone:Z?.triggerKind==="schedule"?Z.timezone:void 0,eventType:Z?.triggerKind==="event"?Z.event:void 0,filters:Z?.triggerKind==="event"?Z.filters:void 0,debounceSeconds:Z?.triggerKind==="event"?Z.debounceSeconds:void 0,dedupeWindowSeconds:Z?.triggerKind==="event"?Z.dedupeWindowSeconds:void 0,cooldownSeconds:Z?.triggerKind==="event"?Z.cooldownSeconds:void 0,mode:Z?.mode,systemPrompt:Z?.systemPrompt,providerId:Z?.modelSelection?.providerId,modelId:Z?.modelSelection?.modelId,maxIterations:Z?.maxIterations,timeoutSeconds:Z?.timeoutSeconds,maxParallel:Z&&"maxParallel"in Z?Z.maxParallel:void 0,tools:Z?.tools,notesDirectory:Z?.notesDirectory,extensions:Z?.extensions,source:Z?.source},j=$.parseStatus==="valid"&&(Z?.enabled??!0);if(!Q){let H=`cspec_${G4()}`;this.insertSpecRow(H,$,W,j,J);let B=this.getSpec(H);if(!B)throw Error("failed to insert cron_spec row");return{record:B,created:!0,revisionChanged:!0}}let X=Q.sourceHash!==$.sourceHash&&gF(Q,W,Q.enabled,j),Y=X?Q.revision+1:Q.revision;this.updateSpecRow(Q.specId,$,W,j,Y,J);let V=this.getSpec(Q.specId);if(!V)throw Error("failed to reload cron_spec after update");return{record:V,created:!1,revisionChanged:X}}insertSpecRow($,J,Q,Z,W){let j=J.spec;this.db.prepare(`INSERT INTO cron_specs (
143
143
  spec_id, external_id, source_path, trigger_kind,
144
144
  source_mtime_ms, source_hash, parse_status, parse_error,
145
145
  enabled, removed, title, prompt, workspace_root,
@@ -150,7 +150,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
150
150
  tools_json, notes_directory, extensions_json, source,
151
151
  tags_json, metadata_json, revision,
152
152
  created_at, updated_at
153
- ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run($,f.externalId,f.sourcePath,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,Q?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,W?.tags?JSON.stringify(W.tags):null,W?.metadata?JSON.stringify(W.metadata):null,1,Z,Z)}updateSpecRow($,f,J,Q,Z,W){let j=f.spec;this.db.prepare(`UPDATE cron_specs SET
153
+ ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run($,J.externalId,J.sourcePath,J.triggerKind,J.sourceMtimeMs??null,J.sourceHash,J.parseStatus,J.parseError??null,Z?1:0,0,Q.title??"",Q.prompt??null,Q.workspaceRoot??null,Q.scheduleExpr??null,Q.timezone??null,Q.eventType??null,Q.filters?JSON.stringify(Q.filters):null,Q.debounceSeconds??null,Q.dedupeWindowSeconds??null,Q.cooldownSeconds??null,Q.mode??null,Q.systemPrompt??null,Q.providerId??null,Q.modelId??null,Q.maxIterations??null,Q.timeoutSeconds??null,Q.maxParallel??null,Q.tools?JSON.stringify(Q.tools):null,Q.notesDirectory??null,Q.extensions?JSON.stringify(Q.extensions):null,Q.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,1,W,W)}updateSpecRow($,J,Q,Z,W,j){let f=J.spec;this.db.prepare(`UPDATE cron_specs SET
154
154
  external_id = ?, trigger_kind = ?,
155
155
  source_mtime_ms = ?, source_hash = ?, parse_status = ?, parse_error = ?,
156
156
  enabled = ?, removed = 0, title = ?, prompt = ?,
@@ -162,31 +162,31 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
162
162
  tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
163
163
  tags_json = ?, metadata_json = ?,
164
164
  revision = ?, updated_at = ?
165
- WHERE spec_id = ?`).run(f.externalId,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,Q?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,Z,W,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(F0(),$)}updateSpecNextRunAt($,f){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f??null,F0(),$)}updateSpecLastRunAt($,f){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f,F0(),$)}updateLastMaterializedRunId($,f){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(f,F0(),$)}initializeScheduleNextRun($){let f=this.getSpec($);if(!f||f.triggerKind!=="schedule"||!f.enabled||!f.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let J=new Date(k$(f.scheduleExpr,Date.now(),f.timezone)).toISOString();this.updateSpecNextRunAt($,J)}materializeDueScheduleRun($){let f=$.nowMs,J=new Date(f).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let Z=$$(Q);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let W=Z.nextRunAt;if(!W){let Y=new Date(k$(Z.scheduleExpr,f,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(Y,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Y}}if(new Date(W).getTime()>f)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:W};let j=`crun_${X8()}`,X;try{X=new Date(k$(Z.scheduleExpr,f,Z.timezone)).toISOString()}catch{X=void 0}return this.db.prepare(`INSERT INTO cron_runs (
165
+ WHERE spec_id = ?`).run(J.externalId,J.triggerKind,J.sourceMtimeMs??null,J.sourceHash,J.parseStatus,J.parseError??null,Z?1:0,Q.title??"",Q.prompt??null,Q.workspaceRoot??null,Q.scheduleExpr??null,Q.timezone??null,Q.eventType??null,Q.filters?JSON.stringify(Q.filters):null,Q.debounceSeconds??null,Q.dedupeWindowSeconds??null,Q.cooldownSeconds??null,Q.mode??null,Q.systemPrompt??null,Q.providerId??null,Q.modelId??null,Q.maxIterations??null,Q.timeoutSeconds??null,Q.maxParallel??null,Q.tools?JSON.stringify(Q.tools):null,Q.notesDirectory??null,Q.extensions?JSON.stringify(Q.extensions):null,Q.source??null,f?.tags?JSON.stringify(f.tags):null,f?.metadata?JSON.stringify(f.metadata):null,W,j,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(D0(),$)}updateSpecNextRunAt($,J){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(J??null,D0(),$)}updateSpecLastRunAt($,J){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(J,D0(),$)}updateLastMaterializedRunId($,J){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(J,D0(),$)}initializeScheduleNextRun($){let J=this.getSpec($);if(!J||J.triggerKind!=="schedule"||!J.enabled||!J.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Q=new Date(I$(J.scheduleExpr,Date.now(),J.timezone)).toISOString();this.updateSpecNextRunAt($,Q)}materializeDueScheduleRun($){let J=$.nowMs,Q=new Date(J).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Z=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Z)return this.db.exec("COMMIT;"),{queued:!1};let W=J$(Z);if(W.triggerKind!=="schedule"||!W.enabled||W.removed||W.parseStatus!=="valid"||!W.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let j=W.nextRunAt;if(!j){let Y=new Date(I$(W.scheduleExpr,J,W.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(Y,Q,W.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Y}}if(new Date(j).getTime()>J)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:j};let f=`crun_${G4()}`,X;try{X=new Date(I$(W.scheduleExpr,J,W.timezone)).toISOString()}catch{X=void 0}return this.db.prepare(`INSERT INTO cron_runs (
166
166
  run_id, spec_id, spec_revision, trigger_kind, status,
167
167
  scheduled_for, trigger_event_id, attempt_count,
168
168
  created_at, updated_at
169
- ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(j,Z.specId,Z.revision,"schedule","queued",W,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
169
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(f,W.specId,W.revision,"schedule","queued",j,null,0,Q,Q),this.db.prepare(`UPDATE cron_specs SET
170
170
  last_materialized_run_id = ?,
171
171
  last_run_at = ?,
172
172
  next_run_at = ?,
173
173
  updated_at = ?
174
- WHERE spec_id = ?`).run(j,J,X??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:X}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?n9(f):void 0}insertEventLog($,f={}){let J=F0(),Q=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let W=$.eventType.trim();if(!W)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let X=$.occurredAt.trim()||Q,Y=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
174
+ WHERE spec_id = ?`).run(f,Q,X??null,Q,W.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(f),nextRunAt:X}}catch(Z){throw this.db.exec("ROLLBACK;"),Z}}getRun($){let J=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return J?XZ(J):void 0}insertEventLog($,J={}){let Q=D0(),Z=J.receivedAtIso??Q,W=$.eventId.trim();if(!W)throw Error("automation event requires eventId");let j=$.eventType.trim();if(!j)throw Error("automation event requires eventType");let f=$.source.trim();if(!f)throw Error("automation event requires source");let X=$.occurredAt.trim()||Z,Y=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
175
175
  event_id, event_type, source, subject,
176
176
  occurred_at, received_at, workspace_root, dedupe_key,
177
177
  payload_json, attributes_json, processing_status,
178
178
  matched_spec_count, queued_run_count, suppressed_count,
179
179
  error, created_at, updated_at
180
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,W,j,$.subject?.trim()||null,X,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,g3($.payload),g3($.attributes),"received",0,0,0,null,J,J).changes??0,A=this.getEventLog(Z);if(!A)throw Error("failed to insert cron_event_log row");return{record:A,created:Y===1}}getEventLog($){let f=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return f?x3(f):void 0}listEventLogs($={}){let f=[],J=[];if($.eventType)f.push("event_type = ?"),J.push($.eventType);if($.source)f.push("source = ?"),J.push($.source);if($.processingStatus)f.push("processing_status = ?"),J.push($.processingStatus);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
180
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(W,j,f,$.subject?.trim()||null,X,Z,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,Wf($.payload),Wf($.attributes),"received",0,0,0,null,Q,Q).changes??0,V=this.getEventLog(W);if(!V)throw Error("failed to insert cron_event_log row");return{record:V,created:Y===1}}getEventLog($){let J=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return J?Zf(J):void 0}listEventLogs($={}){let J=[],Q=[];if($.eventType)J.push("event_type = ?"),Q.push($.eventType);if($.source)J.push("source = ?"),Q.push($.source);if($.processingStatus)J.push("processing_status = ?"),Q.push($.processingStatus);let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Z}
181
181
  ORDER BY received_at DESC, created_at DESC
182
- LIMIT ?`).all(...J,Z).map((j)=>x3(j))}updateEventLogProcessing($,f){return(this.db.prepare(`UPDATE cron_event_log SET
182
+ LIMIT ?`).all(...Q,W).map((f)=>Zf(f))}updateEventLogProcessing($,J){return(this.db.prepare(`UPDATE cron_event_log SET
183
183
  processing_status = ?,
184
184
  matched_spec_count = COALESCE(?, matched_spec_count),
185
185
  queued_run_count = COALESCE(?, queued_run_count),
186
186
  suppressed_count = COALESCE(?, suppressed_count),
187
187
  error = ?,
188
188
  updated_at = ?
189
- WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,F0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let X=j.map(()=>"?").join(",");f.push(`status IN (${X})`);for(let Y of j)J.push(Y)}}let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>n9(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
189
+ WHERE event_id = ?`).run(J.status,J.matchedSpecCount??null,J.queuedRunCount??null,J.suppressedCount??null,J.error??null,D0(),$).changes??0)===1}listRuns($={}){let J=[],Q=[];if($.specId)J.push("spec_id = ?"),Q.push($.specId);if($.status){let f=Array.isArray($.status)?$.status:[$.status];if(f.length>0){let X=f.map(()=>"?").join(",");J.push(`status IN (${X})`);for(let Y of f)Q.push(Y)}}let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Z} ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((f)=>XZ(f))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
190
190
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
191
191
  WHERE r.spec_id = ?
192
192
  AND r.trigger_kind = 'event'
@@ -197,28 +197,28 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
197
197
  WHERE r.spec_id = ?
198
198
  AND r.trigger_kind = 'event'
199
199
  AND e.received_at >= ?
200
- LIMIT 1`).get($.specId,$.sinceIso)}findQueuedEventRunForDedupe($){let f=this.db.prepare(`SELECT r.* FROM cron_runs r
200
+ LIMIT 1`).get($.specId,$.sinceIso)}findQueuedEventRunForDedupe($){let J=this.db.prepare(`SELECT r.* FROM cron_runs r
201
201
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
202
202
  WHERE r.spec_id = ?
203
203
  AND r.trigger_kind = 'event'
204
204
  AND r.status = 'queued'
205
205
  AND e.dedupe_key = ?
206
206
  ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
207
- LIMIT 1`).get($.specId,$.dedupeKey);return f?n9(f):void 0}updateQueuedEventRunForDebounce($){let f=F0();if((this.db.prepare(`UPDATE cron_runs SET
207
+ LIMIT 1`).get($.specId,$.dedupeKey);return J?XZ(J):void 0}updateQueuedEventRunForDebounce($){let J=D0();if((this.db.prepare(`UPDATE cron_runs SET
208
208
  trigger_event_id = ?,
209
209
  scheduled_for = ?,
210
210
  updated_at = ?
211
211
  WHERE run_id = ?
212
212
  AND trigger_kind = 'event'
213
- AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,f,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,f){return!!this.db.prepare(`SELECT run_id FROM cron_runs
213
+ AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,J,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,J){return!!this.db.prepare(`SELECT run_id FROM cron_runs
214
214
  WHERE spec_id = ? AND spec_revision = ?
215
215
  AND trigger_kind = 'one_off'
216
- LIMIT 1`).get($,f)}enqueueRun($){let f=`crun_${X8()}`,J=F0();this.db.prepare(`INSERT INTO cron_runs (
216
+ LIMIT 1`).get($,J)}enqueueRun($){let J=`crun_${G4()}`,Q=D0();this.db.prepare(`INSERT INTO cron_runs (
217
217
  run_id, spec_id, spec_revision, trigger_kind, status,
218
218
  scheduled_for, trigger_event_id, attempt_count,
219
219
  created_at, updated_at
220
- ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(f,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId($.specId,f);let Q=this.getRun(f);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 = ?
221
- WHERE spec_id = ? AND status = 'queued'`).run(F0(),$).changes??0}claimDueRuns($){let f=$.nowIso,J=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(f).getTime()+J).toISOString(),Z=Math.max(1,Math.floor($.limit??25)),W=[];this.db.exec("BEGIN IMMEDIATE;");try{let j=this.db.prepare(`SELECT * FROM cron_runs
220
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(J,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,Q,Q),this.updateLastMaterializedRunId($.specId,J);let Z=this.getRun(J);if(!Z)throw Error("failed to insert cron_run row");return Z}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
221
+ WHERE spec_id = ? AND status = 'queued'`).run(D0(),$).changes??0}claimDueRuns($){let J=$.nowIso,Q=Math.max(1000,Math.floor($.leaseMs)),Z=new Date(new Date(J).getTime()+Q).toISOString(),W=Math.max(1,Math.floor($.limit??25)),j=[];this.db.exec("BEGIN IMMEDIATE;");try{let f=this.db.prepare(`SELECT * FROM cron_runs
222
222
  WHERE (
223
223
  status = 'queued'
224
224
  OR (
@@ -230,7 +230,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
230
230
  )
231
231
  AND (scheduled_for IS NULL OR scheduled_for <= ?)
232
232
  ORDER BY COALESCE(scheduled_for, created_at) ASC
233
- LIMIT ?`).all(f,f,Z);for(let X of j){let Y=n(X.run_id);if(!Y)continue;let A=`cclaim_${X8()}`;if((this.db.prepare(`UPDATE cron_runs SET
233
+ LIMIT ?`).all(J,J,W);for(let X of f){let Y=a(X.run_id);if(!Y)continue;let V=`cclaim_${G4()}`;if((this.db.prepare(`UPDATE cron_runs SET
234
234
  status = 'running',
235
235
  claim_token = ?,
236
236
  claim_started_at = ?,
@@ -251,8 +251,8 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
251
251
  AND claim_until_at <= ?
252
252
  AND completed_at IS NULL
253
253
  )
254
- )`).run(A,f,Q,f,f,Y,f).changes??0)!==1)continue;let H=this.getRun(Y);if(!H)continue;W.push({run:H,claimToken:A,claimUntilAt:Q})}this.db.exec("COMMIT;")}catch(j){throw this.db.exec("ROLLBACK;"),j}return W}renewClaim($,f,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
255
- WHERE run_id = ? AND claim_token = ?`).run(J,F0(),$,f).changes??0)===1}completeRun($,f){let J=f.completedAtIso??F0(),Q=f.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
254
+ )`).run(V,J,Z,J,J,Y,J).changes??0)!==1)continue;let B=this.getRun(Y);if(!B)continue;j.push({run:B,claimToken:V,claimUntilAt:Z})}this.db.exec("COMMIT;")}catch(f){throw this.db.exec("ROLLBACK;"),f}return j}renewClaim($,J,Q){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
255
+ WHERE run_id = ? AND claim_token = ?`).run(Q,D0(),$,J).changes??0)===1}completeRun($,J){let Q=J.completedAtIso??D0(),Z=J.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
256
256
  status = ?,
257
257
  session_id = COALESCE(?, session_id),
258
258
  report_path = COALESCE(?, report_path),
@@ -262,7 +262,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
262
262
  claim_token = NULL,
263
263
  claim_until_at = NULL,
264
264
  updated_at = ?
265
- ${Q}`).run(f.status,f.sessionId??null,f.reportPath??null,f.error??null,J,J,$,...f.claimToken?[f.claimToken]:[]).changes??0)>0}requeueRun($){let f=F0();return(this.db.prepare(`UPDATE cron_runs SET
265
+ ${Z}`).run(J.status,J.sessionId??null,J.reportPath??null,J.error??null,Q,Q,$,...J.claimToken?[J.claimToken]:[]).changes??0)>0}requeueRun($){let J=D0();return(this.db.prepare(`UPDATE cron_runs SET
266
266
  status = 'queued',
267
267
  claim_started_at = NULL,
268
268
  claim_token = NULL,
@@ -274,9 +274,9 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
274
274
  error = ?,
275
275
  scheduled_for = COALESCE(?, scheduled_for),
276
276
  updated_at = ?
277
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,F0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,F0(),$)}}function wJ($){return $?new Date($).getTime():void 0}function YF($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function qJ($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:wJ($.nextRunAt),lastRunAt:wJ($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:YF($)}}function AF($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function t9($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:wJ($.startedAt),endedAt:wJ($.completedAt),status:AF($.status),errorMessage:$.error}}class vf{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new Y8({dbPath:$.dbPath}),this.materializer=new f8({store:this.store}),this.runner=new Z8({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(r9($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return qJ(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?qJ(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>qJ(f))}updateSchedule($,f){if(f.cronPattern!==void 0)r9(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let Q=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule($,{...f,scheduleId:$});return W?qJ(W):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return t9(J,$)}triggerScheduleNowDetached($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;return this.runner.tick().catch(()=>{return}),t9(f,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let W=f??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return t9(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,Q=0,Z=0,W;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!W&&j.status!=="success"&&j.status!=="completed")W=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,Q+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,Q)=>String(J.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}oJ();import{createSessionId as sP,isHubProtocolCompatible as oP,resolveClineBuildEnv as eP,resolveHubCommandTimeoutMs as $R}from"@cline/shared";var Zj={};q(Zj,{splitCoreSessionConfig:()=>U8,isSessionNotFoundError:()=>b1,SessionNotFoundError:()=>h1,SESSION_NOT_FOUND_ERROR_CODE:()=>g$});var g$="session_not_found";class h1 extends Error{sessionId;code="session_not_found";constructor($,f){super(f??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function b1($){return $ instanceof h1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function U8($){let{hooks:f,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:A,compaction:V,...H}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(Q)B.telemetry=Q;if(Z)B.extensionContext=Z;if(W)B.extraTools=W;if(j)B.extensions=j;if(X)B.onTeamEvent=X;if(Y)B.onConsecutiveMistakeLimitReached=Y;if(A?.createCheckpoint)B.checkpoint=A;if(V?.compact)B.compaction=V;let K=Object.keys(B).length>0?B:void 0;return{config:{...H,...A?{checkpoint:{enabled:A.enabled}}:{},...V?{compaction:{enabled:V.enabled,strategy:V.strategy,thresholdRatio:V.thresholdRatio,reserveTokens:V.reserveTokens,preserveRecentTokens:V.preserveRecentTokens,maxInputTokens:V.maxInputTokens,summarizer:V.summarizer}}:{}},...K?{localRuntime:K}:{}}}import{spawn as wP}from"node:child_process";import{closeSync as CP,mkdirSync as yP,openSync as SP}from"node:fs";import{basename as EP,dirname as hP,join as bP}from"node:path";import{fileURLToPath as kP}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as IP,isHubDaemonProcess as Dj,isHubProtocolCompatible as xP,resolveClineBuildEnv as Uj,withResolvedClineBuildEnv as gP}from"@cline/shared";import{createHash as ZP,randomBytes as WP}from"node:crypto";import{existsSync as jP}from"node:fs";import{chmod as XP,mkdir as fQ,readFile as Aj,rm as JQ,writeFile as Vj}from"node:fs/promises";import{dirname as Hj,join as QQ}from"node:path";import{resolveClineDataDir as m$,resolveClineDir as Bj}from"@cline/shared/storage";var jj="0.0.47";var L8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:jj,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var YP="CLINE_HUB_DISCOVERY_PATH",AP="CLINE_HUB_BUILD_ID",Xj=30000,VP=15000,HP=100;function BP($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function KP($){return ZP("sha256").update($).digest("hex").slice(0,12)}function GP($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function eJ(){return WP(32).toString("hex")}function FP($){return new Promise((f)=>setTimeout(f,$))}function PP($){return`${$}.lock`}async function RP($){try{let f=JSON.parse(await Aj(QQ($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function Yj($){await JQ($,{recursive:!0,force:!0}).catch(()=>{return})}function $6(){return process.env[AP]?.trim()||String(L8.version)}function k1($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${KP($)}`,J=process.env[YP]?.trim()||QQ(m$(),"locks","hub","owners",`${BP(f)}.json`);return{ownerId:f,discoveryPath:J}}function Kj($=`hub-${Date.now().toString(36)}`){return k1($)}async function Z0($){try{let f=JSON.parse(await Aj($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,minClientProtocolVersion:typeof f.minClientProtocolVersion==="string"?f.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof f.maxClientProtocolVersion==="string"?f.maxClientProtocolVersion:void 0,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof f.coreVersion==="string"?f.coreVersion:void 0,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function f6($,f){await fQ(Hj($),{recursive:!0}),await JQ($,{force:!0}).catch(()=>{return}),await Vj($,`${JSON.stringify(f,null,2)}
278
- `,{encoding:"utf8",mode:384}),await XP($,384)}async function C0($){await JQ($,{force:!0}).catch(()=>{return})}async function J6($,f){let J=PP($);await fQ(Hj(J),{recursive:!0});let Q=Date.now()+VP;while(!0)try{await fQ(J,{recursive:!1}),await Vj(QQ(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
279
- `,"utf8");try{return await f()}finally{await Yj(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await RP(J),X=j?Date.now()-Date.parse(j.acquiredAt):Xj+1;if(!j||!GP(j.pid)||X>Xj){await Yj(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await FP(HP)}}async function I1($,f){try{let J=await fetch(f?.authToken?ZQ($):Q6($),{headers:f?.authToken?{authorization:`Bearer ${f.authToken}`}:void 0});if(!J.ok)return;let Q=await J.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((Z)=>typeof Z==="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 s0($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function Q6($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function ZQ($){let f=new URL(Q6($));return f.pathname="/status",f.toString()}function Gj($){return jP($)}import{CLINE_HUB_DEV_PORT as DP,CLINE_HUB_PORT as UP,resolveClineBuildEnv as LP}from"@cline/shared";var _P="CLINE_HUB_HOST",zP="CLINE_HUB_PORT",OP="CLINE_HUB_PATHNAME",WQ="127.0.0.1",jQ=UP,XQ="/hub";function Fj($){return LP($)==="development"?DP:jQ}function YQ($={}){return($.env??process.env)[_P]?.trim()||WQ}function rf($={}){let J=($.env??process.env)[zP]?.trim();if(!J)return Fj($);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return Fj($);return Q}function AQ($={}){return($.env??process.env)[OP]?.trim()||XQ}function X1($={},f={}){return{host:$.host??YQ(f),port:$.port??rf(f),pathname:$.pathname??AQ(f)}}import{join as MP}from"node:path";var TP="shared:cline",NP="CLINE_HUB_DISCOVERY_PATH",qP="hub-production";function Pj($){let f=T1($.trim());return k1(`workspace:${f||$.trim()}`)}function o0($=TP){return k1($)}function Y1(){return{ownerId:qP,discoveryPath:process.env[NP]?.trim()||MP(m$(),"locks","hub","production.json")}}var mP=8000,vP=200,cP=3000,uP=100,dP=[100,250,500,1000,2000],lP="--cline-hub-daemon";function pP($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function rP(){try{let $=bP(m$(),"logs","hub-daemon.log");return yP(hP($),{recursive:!0}),{fd:SP($,"a"),logPath:$}}catch{return}}function Lj(){return Uj()==="production"?Y1():o0()}function v$($){return xP($).compatible}function Rj($,f,J){if(!f||f.url!==J)return $;return{...$,authToken:$.authToken??f.authToken,pid:$.pid??f.pid}}async function c$($,f){try{return await I1($,{authToken:f})}catch{return}}async function iP($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await c$($))?.url)return!0;await new Promise((Z)=>setTimeout(Z,uP))}return!1}async function Z6($,f){if(await z8($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let J=await iP($.url,cP);return await C0(f).catch(()=>{return}),J}async function _8($,f){if(v$($))return!0;return Z6($,f)}async function _j($){if(Uj()!=="production")return;let f=o0();if(f.discoveryPath===$.discoveryPath)return;let J=await Z0(f.discoveryPath);if(J?.url)await Z6(J,f.discoveryPath);else await C0(f.discoveryPath).catch(()=>{return})}function nP(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return kP(new URL(`./entry.${$}`,import.meta.url))}function aP($,f){let J=nP(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=EP(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=W?[lP]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...X,"--cwd",$,...pP(f)],cwd:$,env:{...gP(process.env),CLINE_NO_INTERACTIVE:"1",[IP]:"1"}}}function tP($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function VQ($,f={}){if(Dj())return;let J=aP($,f),Q=rP();try{wP(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd,windowsHide:!0}).unref()}finally{if(Q)CP(Q.fd)}}async function nf($,f={}){for(let J=0;;J++)try{VQ($,f);return}catch(Q){let Z=dP[J];if(!tP(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function W6($,f={}){if(Dj())return;let J=Lj(),Q=X1(f),Z=s0(Q.host,Q.port,Q.pathname),W=f.allowPortFallback===!0&&Q.port!==0;_j(J).catch(()=>{return}).then(()=>Z0(J.discoveryPath)).then(async(j)=>{let X=!1;if(j?.url)if(!j.authToken){if(X=!0,!await Z6(j,J.discoveryPath)&&!W)return}else{let V=await c$(j.url,j.authToken);if(V?.url&&v$(V)&&await A1(V.url,{authToken:j.authToken}))return;if(V?.url)await _8({...V,authToken:j.authToken},J.discoveryPath);else await C0(J.discoveryPath).catch(()=>{return})}let Y=await c$(Z);if(Y?.url){if(v$(Y)){if(!W||!X)return}else if(!await _8({...Y,authToken:void 0},J.discoveryPath)&&!W)return}let A=W?{...Q,port:0}:Q;await nf($,A)}).catch(()=>{})}async function zj($,f={}){let J=Lj(),Q=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=X1(f),W=s0(Z.host,Z.port,Z.pathname),j=(K)=>{if(!Q)Q$(K.url,K.authToken);return K};await _j(J).catch(()=>{return});let X=await Z0(J.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await Z6(X,J.discoveryPath);else{let G=await c$(X.url,K);if(G?.url&&v$(G)&&await A1(G.url,{authToken:K}))return j({url:G.url,authToken:K});if(G?.url)await _8({...G,authToken:K},J.discoveryPath);else await C0(J.discoveryPath).catch(()=>{return})}}let A=await c$(W);if(A?.url){let K=Rj(A,X,W);if(v$(A))throw Error(`A compatible Cline Hub is already running at ${W}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await _8(K,J.discoveryPath)&&f.allowPortFallback!==!0&&Z.port!==0)throw Error(`An incompatible Cline Hub is already running at ${W} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let H=f.allowPortFallback===!0&&Z.port!==0?{...Z,port:0}:Z;await nf($,H);let B=Date.now()+mP;while(Date.now()<B){let K=await Z0(J.discoveryPath);if(K?.url&&K.authToken){let R=await c$(K.url,K.authToken);if(R?.url&&v$(R)&&await A1(R.url,{authToken:K.authToken}))return j({url:R.url,authToken:K.authToken})}let G=await c$(W);if(G?.url&&!v$(G)){let R=Rj(G,K,W);if(!await _8(R,J.discoveryPath)&&f.allowPortFallback!==!0&&Z.port!==0)throw Error(`An incompatible Cline Hub is still running at ${W} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,vP))}throw Error("Timed out waiting for detached hub startup.")}function j6(){return eP()==="production"?Y1():o0()}function fR(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function qj($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return qj($.data);return String($)}function JR($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function Oj($){let f=$,J=JR(f.reason);return new O0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:HQ,{closeCode:f.code,closeReason:J||void 0})}function QR($,f){if($ instanceof O0)return $;if($ instanceof Error)return new O0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new O0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new O0("hub_connect_failed",J);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new O0("hub_connect_failed",Q?`Failed to connect to hub at ${f.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var ZR=8000,WR=200,Mj="*",Tj=8000,jR="cline-hub-auth.",wj=new Map,Cj=new Set,XR=3000,YR=3000,AR=100,HQ="Hub connection closed",VR=250,HR=5000,Nj=0.5;class O0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function GQ($){return $ instanceof O0}class af extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function X6($,f){return $ instanceof af&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function yj($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=FQ($.toString());return J?wj.get(J):void 0}function BR($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function FQ($){if(!BR($))return;let f=new URL(Z$($));return f.search="",f.hash="",f.toString()}function BQ($){let f=FQ($);return!!f&&Cj.has(f)}function Q$($,f){let J=FQ($);if(J){if(Cj.add(J),f?.trim())wj.set(J,f)}return $}class e0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new O0("hub_connection_closed",HQ);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||yj($);$.hash="";let Q=new(fR())($.toString(),f?[`${jR}${f}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new O0("hub_connect_timeout",`Timed out connecting to hub after ${Tj}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},Tj);Q.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),W()}),Q.addEventListener("error",(A)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=QR(A,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(A)=>{if(X)return;if(X=!0,clearTimeout(Y),!Z)this.lastCloseError=Oj(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(qj(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=Oj(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,Q={listener:$,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,Q){let Z=0,W=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,Q){await this.connect();let Z=sP("hubreq_"),W=$R($,Q?.timeoutMs),j=new Promise((Y,A)=>{let V=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;A(new af($,"hub_command_timeout",`Hub command ${$} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(H)=>{if(V)clearTimeout(V);Y(H)},reject:(H)=>{if(V)clearTimeout(V);A(H)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:f}})}catch(Y){throw this.pendingReplies.delete(Z),Y}let X=await j;if(!X.ok){if(X.error?.code===g$){let Y=J??(typeof f?.sessionId==="string"?f.sessionId:void 0);throw new h1(Y,X.error.message)}throw new af($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!BQ(this.currentUrl)||!GQ($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await u$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(VR*2**this.reconnectAttempt,HR),f=Math.round($*(1-Nj)+Math.random()*$*Nj);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!BQ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await u$({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 O0("hub_connection_closed",HQ),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new O0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(J)??0)+f;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,Q),f>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??Mj}subscriptionSessionIdFromKey($){return $===Mj?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Z$($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function A1($,f){let J=new e0({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function KQ($,f){let J=Z$($),Q=await I1(J,{authToken:f?.authToken});if(!Q)return{status:"unreachable",url:J};if(!oP(Q).compatible)return{status:"protocol_mismatch",url:J};if(f?.verifyConnection===!0&&!await A1(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function KR($){let f=Date.now()+ZR;while(Date.now()<f){let J=await Z0($.discoveryPath);if(J?.url){let Q=await KQ(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return Q$(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,WR))}return}async function GR($){let f=Date.now()+YR;while(Date.now()<f){if(!(await I1($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,AR))}return!1}function FR($,f){try{return Z$($)===Z$(f)}catch{return!1}}function PR($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function RR($,f,J){let Q=new e0({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:XR});return!PR(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function O8($={}){if($.endpoint?.trim()){let Z=await KQ($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=j6(),J=await Z0(f.discoveryPath);if(!J?.url)return;let Q=await KQ(J.url,{authToken:J.authToken});if(Q.status==="compatible")return Q$(Q.url,J.authToken);if(Q.status==="protocol_mismatch")await C0(f.discoveryPath).catch(()=>{return});return}async function u$($={}){let f=await O8($);if(f&&await A1(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=j6();return await nf($.workspaceRoot??process.cwd()),await KR(J)}async function z8($,f){let J=new URL($),Q=f?.trim()||yj(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function PQ($=j6()){let f=await Z0($.discoveryPath);if(!f?.url)return!1;try{if(await z8(f.url,f.authToken))return!0}catch{}return!1}async function Y6($){if(!BQ($.url))return;let f=j6(),J=await Z0(f.discoveryPath);if(!J?.url||!FR(J.url,$.url))return;if(!await RR(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await PQ())return;if(!await GR(J.url))return;return await C0(f.discoveryPath).catch(()=>{return}),await u$({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as DR}from"@cline/shared";function UR($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var LR="cline-hub-auth.";function _R($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function zR($,f){let J=new URL($),Q=new URL(f);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}function Sj(){return DR()==="production"?Y1():o0()}async function OR($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=Sj(),Q=await Z0(J.discoveryPath);if(Q?.url&&zR($.toString(),Q.url))return Q.authToken;return}async function RQ($={}){let f=X1($);if(!_R($)){let J=Sj(),Q=await Z0(J.discoveryPath);if(Q?.url)return Q.url}return s0(f.host,f.port,f.pathname)}async function A6($){return await new Promise((f,J)=>{(async()=>{let Q=new URL($),Z=await OR(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${LR}${Z}`]:void 0),j=new Map,X=0;W.addEventListener("open",()=>{f({send(Y){let A=Y.requestId??`hub-client-${++X}`;return new Promise((V,H)=>{j.set(A,{resolve:V,reject:H});let B={kind:"command",envelope:{...Y,requestId:A}};W.send(JSON.stringify(B))})},close(){W.close()}})}),W.addEventListener("message",(Y)=>{let A=JSON.parse(String(Y.data));if(A.kind==="reply"&&A.envelope.requestId){let V=j.get(A.envelope.requestId);if(V)j.delete(A.envelope.requestId),V.resolve(A.envelope)}}),W.addEventListener("close",()=>{for(let Y of j.values())Y.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(Y)=>{J(UR(Y,$))})})().catch(J)})}async function Ej($){try{return(await A6($)).close(),!0}catch{return!1}}async function hj($,f){let J=await RQ($),Q=await A6(J);try{return await Q.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{Q.close()}}function DQ($){return $?JSON.parse(JSON.stringify($)):{}}function V6($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?DQ(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function bj($,f){return $.error?.message??`hub command failed: ${f}`}function MR($){let f=DQ($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let Q=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...f,error:Q.message.trim()};return f}function kj($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function TR($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function NR($){let f=DQ($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||kj(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||kj(f)||"",eventType:"schedule.execution.failed",payload:f};let J=$.sessionId?.trim();if(!J)return;switch($.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:f};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:f};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:f};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:f};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:f};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:f};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:f};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:f};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:MR($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class UQ{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new e0({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),J=V6(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(b1(J))return;throw J}return V6(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(bj(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},f);if(!Z.ok)throw Error(bj(Z,"session.restore"));let W=V6(Z.payload);if(J&&!W?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,X=TR(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((Q)=>V6({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=NR(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;f.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}streamTeamProgress($,f){let J=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;f.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{f.onError?.(Q instanceof Error?Q:Error(String(Q)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class LQ{client;constructor($){this.client=new e0({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}import{normalizeProviderId as FS}from"@cline/llms";var FK={};q(FK,{LocalRuntimeHost:()=>U1});import{readdirSync as jS}from"node:fs";import{homedir as XS}from"node:os";import{isAbsolute as YS,join as Z3,resolve as W3}from"node:path";import{captureSdkError as yf,createSessionId as AS,isLikelyAuthError as VS,normalizeUserInput as HS}from"@cline/shared";import{setHomeDirIfUnset as BS}from"@cline/shared/storage";var AX={};q(AX,{saveProviderOAuthCredentials:()=>p$,resolveProviderApiKeyFromSettings:()=>EQ,loginAndSaveProviderOAuthCredentials:()=>S8,isOAuthProvider:()=>l$,getProviderOAuthCredentialsFromSettings:()=>E8,getProviderAuthStorageId:()=>SQ,getProviderAuthHandler:()=>B0,getPersistedProviderApiKey:()=>z6,formatProviderOAuthApiKey:()=>hQ});import{getClineEnvironmentConfig as YX}from"@cline/shared";_0();var pj={};q(pj,{startClineDeviceAuth:()=>NQ,refreshClineToken:()=>G6,loginClineOAuth:()=>M8,getValidClineCredentials:()=>T8,completeClineDeviceAuth:()=>qQ});import{getClineEnvironmentConfig as _Q}from"@cline/shared";var Ij={};q(Ij,{startLocalOAuthServer:()=>$1});function qR(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function $1($){let f=await import("node:http"),J=$.host??"127.0.0.1",Q=$.timeoutMs??300000,Z=$.successHtml??wR,W=qR(),j=!1,X=null,Y=null,A=null,V=(K)=>{if(j)return;j=!0,W.resolve(K)},H=()=>{if(X)clearTimeout(X),X=null;let K=A;if(A=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return X=setTimeout(()=>{H(),V(null)},Q),W.promise};for(let K of $.ports){let G=f.createServer((P,F)=>{try{let D=new URL(P.url||"",`http://${J}:${K}`);if(D.pathname!==$.callbackPath){F.statusCode=404,F.end("Not found");return}let z={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(z.error){F.statusCode=400,F.end(`Authentication failed: ${z.error}`),H(),V(z);return}if(!z.code){F.statusCode=400,F.end("Missing authorization code");return}if($.expectedState&&z.state!==$.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(Z),H(),V(z)}catch{F.statusCode=500,F.end("Internal error")}}),R=await new Promise((P)=>{let F=(D)=>{G.off("error",F),P({bound:!1,error:D})};G.once("error",F),G.listen(K,J,()=>{G.off("error",F),Y=G,P({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw H(),R.error}if(R.bound){A=K;let P=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:P})).catch(()=>{});return{callbackUrl:P,waitForCallback:B,cancelWait:()=>{H(),V(null)},close:()=>{H(),V(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var wR=`<!DOCTYPE html>
277
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,D0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,D0(),$)}}function IJ($){return $?new Date($).getTime():void 0}function dF($){let J=$.metadata?{...$.metadata}:void 0;if(J)delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions;return J}function kJ($){let J=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof J?.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:IJ($.nextRunAt),lastRunAt:IJ($.lastRunAt),createdBy:typeof J?.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:J?.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0,metadata:dF($)}}function lF($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function VZ($,J){return{executionId:$.runId,scheduleId:J,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:IJ($.startedAt),endedAt:IJ($.completedAt),status:lF($.status),errorMessage:$.error}}class c2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new F4({dbPath:$.dbPath}),this.materializer=new Y4({store:this.store}),this.runner=new B4({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(jZ($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return kJ(this.store.createHubSchedule($))}getSchedule($){let J=this.store.getHubSchedule($);return J?kJ(J):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((J)=>kJ(J))}updateSchedule($,J){if(J.cronPattern!==void 0)jZ(J.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let Z=J.workspaceRoot!==void 0?J.workspaceRoot.trim():Q.workspaceRoot;if((J.enabled??Q.enabled)&&!Z)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...J,scheduleId:$});return j?kJ(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;await this.runner.tick();let Q=this.store.getRun(J.runId)??J;return VZ(Q,$)}triggerScheduleNowDetached($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;return this.runner.tick().catch(()=>{return}),VZ(J,$)}listScheduleExecutions($){let J=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:J?.specId,limit:$.limit};return this.store.listRuns(Q).map((W)=>{let j=J??this.store.getSpec(W.specId);if(!j||j.source!=="hub-schedule")return;return VZ(W,j.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let J=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(J.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,Z=0,W=0,j;for(let f of J){if(f.status==="success"||f.status==="completed")Q+=1;if(!j&&f.status!=="success"&&f.status!=="completed")j=f;if(f.startedAt&&f.endedAt)W+=f.endedAt-f.startedAt,Z+=1}return{totalRuns:J.length,successRate:Q/J.length,avgDurationSeconds:Z>0?W/Z/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let J=this.store.getSpec($.specId);if(!J||J.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:J.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:J.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+J.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let J={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(J).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,Z)=>String(Q.nextRunAt).localeCompare(String(Z.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:Z})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:Z}))}}f5();import{createSessionId as EU,isHubProtocolCompatible as bU,resolveClineBuildEnv as hU,resolveHubCommandTimeoutMs as kU}from"@cline/shared";var Mf={};w(Mf,{splitCoreSessionConfig:()=>q4,isSessionNotFoundError:()=>k1,SessionNotFoundError:()=>h1,SESSION_NOT_FOUND_ERROR_CODE:()=>g$});var g$="session_not_found";class h1 extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function k1($){return $ instanceof h1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function q4($){let{hooks:J,logger:Q,telemetry:Z,extensionContext:W,extraTools:j,extensions:f,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:H,...B}=$,A={};if(J)A.hooks=J;if(Q)A.logger=Q;if(Z)A.telemetry=Z;if(W)A.extensionContext=W;if(j)A.extraTools=j;if(f)A.extensions=f;if(X)A.onTeamEvent=X;if(Y)A.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)A.checkpoint=V;if(H?.compact)A.compaction=H;let K=Object.keys(A).length>0?A:void 0;return{config:{...B,...V?{checkpoint:{enabled:V.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...K?{localRuntime:K}:{}}}import{spawn as VU}from"node:child_process";import{closeSync as HU,mkdirSync as BU,openSync as AU}from"node:fs";import{basename as KU,dirname as GU,join as FU}from"node:path";import{fileURLToPath as DU}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as UU,isHubDaemonProcess as gf,isHubProtocolCompatible as RU,resolveClineBuildEnv as mf,withResolvedClineBuildEnv as zU}from"@cline/shared";import{createHash as mD,randomBytes as vD}from"node:crypto";import{existsSync as cD}from"node:fs";import{chmod as uD,mkdir as GZ,readFile as Sf,rm as FZ,writeFile as Cf}from"node:fs/promises";import{dirname as yf,join as DZ}from"node:path";import{resolveClineDataDir as m$,resolveClineDir as Ef}from"@cline/shared/storage";var Pf="0.0.48";var P4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Pf,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 dD="CLINE_HUB_DISCOVERY_PATH",lD="CLINE_HUB_BUILD_ID",Nf=30000,pD=15000,rD=100;function iD($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function nD($){return mD("sha256").update($).digest("hex").slice(0,12)}function aD($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function X5(){return vD(32).toString("hex")}function sD($){return new Promise((J)=>setTimeout(J,$))}function oD($){return`${$}.lock`}async function tD($){try{let J=JSON.parse(await Sf(DZ($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function wf($){await FZ($,{recursive:!0,force:!0}).catch(()=>{return})}function Y5(){return process.env[lD]?.trim()||String(P4.version)}function I1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${nD($)}`,Q=process.env[dD]?.trim()||DZ(m$(),"locks","hub","owners",`${iD(J)}.json`);return{ownerId:J,discoveryPath:Q}}function bf($=`hub-${Date.now().toString(36)}`){return I1($)}async function X0($){try{let J=JSON.parse(await Sf($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function V5($,J){await GZ(yf($),{recursive:!0}),await FZ($,{force:!0}).catch(()=>{return}),await Cf($,`${JSON.stringify(J,null,2)}
278
+ `,{encoding:"utf8",mode:384}),await uD($,384)}async function C0($){await FZ($,{force:!0}).catch(()=>{return})}async function H5($,J){let Q=oD($);await GZ(yf(Q),{recursive:!0});let Z=Date.now()+pD;while(!0)try{await GZ(Q,{recursive:!1}),await Cf(DZ(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
279
+ `,"utf8");try{return await J()}finally{await wf(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await tD(Q),X=f?Date.now()-Date.parse(f.acquiredAt):Nf+1;if(!f||!aD(f.pid)||X>Nf){await wf(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await sD(rD)}}async function x1($,J){try{let Q=await fetch(J?.authToken?UZ($):B5($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function e0($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function B5($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function UZ($){let J=new URL(B5($));return J.pathname="/status",J.toString()}function hf($){return cD($)}import{CLINE_HUB_DEV_PORT as eD,CLINE_HUB_PORT as $U,resolveClineBuildEnv as JU}from"@cline/shared";var QU="CLINE_HUB_HOST",ZU="CLINE_HUB_PORT",WU="CLINE_HUB_PATHNAME",RZ="127.0.0.1",zZ=$U,LZ="/hub";function kf($){return JU($)==="development"?eD:zZ}function _Z($={}){return($.env??process.env)[QU]?.trim()||RZ}function n2($={}){let Q=($.env??process.env)[ZU]?.trim();if(!Q)return kf($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return kf($);return Z}function OZ($={}){return($.env??process.env)[WU]?.trim()||LZ}function Y1($={},J={}){return{host:$.host??_Z(J),port:$.port??n2(J),pathname:$.pathname??OZ(J)}}import{join as jU}from"node:path";var fU="shared:cline",XU="CLINE_HUB_DISCOVERY_PATH",YU="hub-production";function If($){let J=P1($.trim());return I1(`workspace:${J||$.trim()}`)}function $1($=fU){return I1($)}function V1(){return{ownerId:YU,discoveryPath:process.env[XU]?.trim()||jU(m$(),"locks","hub","production.json")}}var LU=8000,_U=200,OU=3000,TU=100,MU=[100,250,500,1000,2000],qU="--cline-hub-daemon";function PU($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function NU(){try{let $=FU(m$(),"logs","hub-daemon.log");return BU(GU($),{recursive:!0}),{fd:AU($,"a"),logPath:$}}catch{return}}function vf(){return mf()==="production"?V1():$1()}function v$($){return RU($).compatible}function xf($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function c$($,J){try{return await x1($,{authToken:J})}catch{return}}async function wU($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await c$($))?.url)return!0;await new Promise((W)=>setTimeout(W,TU))}return!1}async function A5($,J){if(await w4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await wU($.url,OU);return await C0(J).catch(()=>{return}),Q}async function N4($,J){if(v$($))return!0;return A5($,J)}async function cf($){if(mf()!=="production")return;let J=$1();if(J.discoveryPath===$.discoveryPath)return;let Q=await X0(J.discoveryPath);if(Q?.url)await A5(Q,J.discoveryPath);else await C0(J.discoveryPath).catch(()=>{return})}function SU(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return DU(new URL(`./entry.${$}`,import.meta.url))}function CU($,J){let Q=SU(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=KU(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[qU]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...PU(J)],cwd:$,env:{...zU(process.env),CLINE_NO_INTERACTIVE:"1",[UU]:"1"}}}function yU($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function TZ($,J={}){if(gf())return;let Q=CU($,J),Z=NU();try{VU(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)HU(Z.fd)}}async function a2($,J={}){for(let Q=0;;Q++)try{TZ($,J);return}catch(Z){let W=MU[Q];if(!yU(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function K5($,J={}){if(gf())return;let Q=vf(),Z=Y1(J),W=e0(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;cf(Q).catch(()=>{return}).then(()=>X0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await A5(f,Q.discoveryPath)&&!j)return}else{let H=await c$(f.url,f.authToken);if(H?.url&&v$(H)&&await H1(H.url,{authToken:f.authToken}))return;if(H?.url)await N4({...H,authToken:f.authToken},Q.discoveryPath);else await C0(Q.discoveryPath).catch(()=>{return})}let Y=await c$(W);if(Y?.url){if(v$(Y)){if(!j||!X)return}else if(!await N4({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await a2($,V)}).catch(()=>{})}async function uf($,J={}){let Q=vf(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=Y1(J),j=e0(W.host,W.port,W.pathname),f=(K)=>{if(!Z)W$(K.url,K.authToken);return K};await cf(Q).catch(()=>{return});let X=await X0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await A5(X,Q.discoveryPath);else{let G=await c$(X.url,K);if(G?.url&&v$(G)&&await H1(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await N4({...G,authToken:K},Q.discoveryPath);else await C0(Q.discoveryPath).catch(()=>{return})}}let V=await c$(j);if(V?.url){let K=xf(V,X,j);if(v$(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await N4(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await a2($,B);let A=Date.now()+LU;while(Date.now()<A){let K=await X0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await c$(K.url,K.authToken);if(R?.url&&v$(R)&&await H1(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await c$(j);if(G?.url&&!v$(G)){let R=xf(G,K,j);if(!await N4(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,_U))}throw Error("Timed out waiting for detached hub startup.")}function G5(){return hU()==="production"?V1():$1()}function IU(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function nf($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return nf($.data);return String($)}function xU($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function df($){let J=$,Q=xU(J.reason);return new M0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:MZ,{closeCode:J.code,closeReason:Q||void 0})}function gU($,J){if($ instanceof M0)return $;if($ instanceof Error)return new M0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new M0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new M0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new M0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var mU=8000,vU=200,lf="*",pf=8000,cU="cline-hub-auth.",af=new Map,sf=new Set,uU=3000,dU=3000,lU=100,MZ="Hub connection closed",pU=250,rU=5000,rf=0.5;class M0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function NZ($){return $ instanceof M0}class s2 extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function F5($,J){return $ instanceof s2&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function of($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=wZ($.toString());return Q?af.get(Q):void 0}function iU($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function wZ($){if(!iU($))return;let J=new URL(j$($));return J.search="",J.hash="",J.toString()}function qZ($){let J=wZ($);return!!J&&sf.has(J)}function W$($,J){let Q=wZ($);if(Q){if(sf.add(Q),J?.trim())af.set(Q,J)}return $}class J1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new M0("hub_connection_closed",MZ);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),J=this.options.authToken?.trim()||of($);$.hash="";let Z=new(IU())($.toString(),J?[`${cU}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new M0("hub_connect_timeout",`Timed out connecting to hub after ${pf}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},pf);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=gU(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=df(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(nf(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=df(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=EU("hubreq_"),j=kU($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new s2($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(W,{resolve:(B)=>{if(H)clearTimeout(H);Y(B)},reject:(B)=>{if(H)clearTimeout(H);V(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===g$){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new h1(Y,X.error.message)}throw new s2($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!qZ(this.currentUrl)||!NZ($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await u$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(pU*2**this.reconnectAttempt,rU),J=Math.round($*(1-rf)+Math.random()*$*rf);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!qZ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await u$({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 M0("hub_connection_closed",MZ),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new M0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??lf}subscriptionSessionIdFromKey($){return $===lf?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function j$($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function H1($,J){let Q=new J1({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function PZ($,J){let Q=j$($),Z=await x1(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!bU(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await H1(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function nU($){let J=Date.now()+mU;while(Date.now()<J){let Q=await X0($.discoveryPath);if(Q?.url){let Z=await PZ(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return W$(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,vU))}return}async function aU($){let J=Date.now()+dU;while(Date.now()<J){if(!(await x1($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,lU))}return!1}function sU($,J){try{return j$($)===j$(J)}catch{return!1}}function oU($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function tU($,J,Q){let Z=new J1({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:uU});return!oU(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function S4($={}){if($.endpoint?.trim()){let W=await PZ($.endpoint);return W.status==="compatible"?W.url:void 0}let J=G5(),Q=await X0(J.discoveryPath);if(!Q?.url)return;let Z=await PZ(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return W$(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await C0(J.discoveryPath).catch(()=>{return});return}async function u$($={}){let J=await S4($);if(J&&await H1(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=G5();return await a2($.workspaceRoot??process.cwd()),await nU(Q)}async function w4($,J){let Q=new URL($),Z=J?.trim()||of(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function SZ($=G5()){let J=await X0($.discoveryPath);if(!J?.url)return!1;try{if(await w4(J.url,J.authToken))return!0}catch{}return!1}async function D5($){if(!qZ($.url))return;let J=G5(),Q=await X0(J.discoveryPath);if(!Q?.url||!sU(Q.url,$.url))return;if(!await tU(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await SZ())return;if(!await aU(Q.url))return;return await C0(J.discoveryPath).catch(()=>{return}),await u$({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as eU}from"@cline/shared";function $R($,J){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${J} (${Q} event before socket open).`:`Failed to connect to hub at ${J}.`)}var JR="cline-hub-auth.";function QR($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function ZR($,J){let Q=new URL($),Z=new URL(J);return Q.search="",Q.hash="",Z.search="",Z.hash="",Q.toString()===Z.toString()}function tf(){return eU()==="production"?V1():$1()}async function WR($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=tf(),Z=await X0(Q.discoveryPath);if(Z?.url&&ZR($.toString(),Z.url))return Z.authToken;return}async function CZ($={}){let J=Y1($);if(!QR($)){let Q=tf(),Z=await X0(Q.discoveryPath);if(Z?.url)return Z.url}return e0(J.host,J.port,J.pathname)}async function U5($){return await new Promise((J,Q)=>{(async()=>{let Z=new URL($),W=await WR(Z);Z.hash="";let j=new WebSocket(Z.toString(),W?[`${JR}${W}`]:void 0),f=new Map,X=0;j.addEventListener("open",()=>{J({send(Y){let V=Y.requestId??`hub-client-${++X}`;return new Promise((H,B)=>{f.set(V,{resolve:H,reject:B});let A={kind:"command",envelope:{...Y,requestId:V}};j.send(JSON.stringify(A))})},close(){j.close()}})}),j.addEventListener("message",(Y)=>{let V=JSON.parse(String(Y.data));if(V.kind==="reply"&&V.envelope.requestId){let H=f.get(V.envelope.requestId);if(H)f.delete(V.envelope.requestId),H.resolve(V.envelope)}}),j.addEventListener("close",()=>{for(let Y of f.values())Y.reject(Error("Hub connection closed"));f.clear()}),j.addEventListener("error",(Y)=>{Q($R(Y,$))})})().catch(Q)})}async function ef($){try{return(await U5($)).close(),!0}catch{return!1}}async function $X($,J){let Q=await CZ($),Z=await U5(Q);try{return await Z.send({version:J.version??"v1",clientId:J.clientId??"hub-client",...J})}finally{Z.close()}}function yZ($){return $?JSON.parse(JSON.stringify($)):{}}function R5($){let J=$?.session&&typeof $.session==="object"?$.session:void 0;if(!J)return;let Q=J.metadata&&typeof J.metadata==="object"?yZ(J.metadata):void 0;return{sessionId:typeof J.sessionId==="string"?J.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function JX($,J){return $.error?.message??`hub command failed: ${J}`}function jR($){let J=yZ($);if(typeof J.error==="string"&&J.error.trim())return{...J,error:J.error.trim()};let Q=J.result&&typeof J.result==="object"?J.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...J,error:Q.text.trim()};let Z=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof Z?.message==="string"&&Z.message.trim())return{...J,error:Z.message.trim()};return J}function QX($){let J=$?.sessionId;return typeof J==="string"&&J.trim()?J.trim():void 0}function fR($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))throw Error("hub checkpoint restore returned no checkpoint");let Q=J;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function XR($){let J=yZ($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||QX(J)||"",eventType:"schedule.execution.completed",payload:J};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||QX(J)||"",eventType:"schedule.execution.failed",payload:J};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:J};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:J};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:J};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:J};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:J};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:J};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:J};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:J};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:jR($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:J};default:return}}class EZ{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new J1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let J=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Q=R5(J.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,J,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:J.prompt,mode:J.config.mode,attachments:J.attachments,delivery:J.delivery,timeoutSeconds:J.config.timeoutSeconds},$,Q)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(k1(Q))return;throw Q}return R5(J.payload)}async readMessages($){let J=$.trim();if(!J)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw Error(JX(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async restore($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Z=$.config,W=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,sessionConfig:{providerId:Z.provider,modelId:Z.model,apiKey:Z.apiKey,cwd:Z.cwd??Z.workspaceRoot,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Z.mode??"act",rules:Z.rules,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},metadata:{source:Z.source??"cli",provider:Z.provider,model:Z.model,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,prompt:void 0,interactive:Z.interactive!==!1},runtimeOptions:{mode:Z.mode,systemPrompt:Z.systemPrompt,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,autoApproveTools:Z.autoApproveTools,configExtensions:Z.configExtensions},modelSelection:{provider:Z.provider,model:Z.model,apiKey:Z.apiKey},toolPolicies:Z.toolPolicies}:{}},J);if(!W.ok)throw Error(JX(W,"session.restore"));let j=R5(W.payload);if(Q&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let f=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,X=fR(W.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...f?{messages:f}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let J=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(J.payload?.sessions)?J.payload?.sessions:[]).map((Z)=>R5({session:Z})).filter((Z)=>Boolean(Z?.sessionId))}async deleteSession($,J=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:J})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,J){let Q=new Set(($.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),Z=this.client.subscribe((W)=>{let j=XR(W);if(!j)return;if(Q.size>0&&!Q.has(j.sessionId))return;J.onEvent?.(j)});return this.ensureMetadataApplied().catch((W)=>{J.onError?.(W instanceof Error?W:Error(String(W)))}),Z}streamTeamProgress($,J){let Q=this.client.subscribe((Z)=>{if(Z.event!=="team.progress"||!Z.payload)return;J.onProjection?.(Z.payload)});return this.ensureMetadataApplied().catch((Z)=>{J.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list");return Array.isArray(J.payload?.schedules)?J.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,J){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...J})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,J){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:J});return Array.isArray(Q.payload?.executions)?Q.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(J.payload?.upcoming)?J.payload?.upcoming:[]}}class bZ{client;constructor($){this.client=new J1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let J=await this.client.command("session.list",{limit:$});return Array.isArray(J.payload?.sessions)?J.payload.sessions:[]}subscribeUI($){return this.client.subscribe((J)=>{switch(J.event){case"ui.notify":$.onNotify?.(J.payload);break;case"ui.show_window":$.onShowWindow?.(J.payload);break;case"hub.client.registered":$.onClientRegistered?.(J.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(J.payload??{});break;case"session.created":$.onSessionCreated?.(J.payload??{});break;case"session.updated":$.onSessionUpdated?.(J.payload??{});break;case"session.detached":$.onSessionDetached?.(J.payload??{});break}})}}import{normalizeProviderId as bE}from"@cline/llms";var sK={};w(sK,{LocalRuntimeHost:()=>L1});import{readdirSync as ME}from"node:fs";import{homedir as qE}from"node:os";import{isAbsolute as PE,join as Mj,resolve as qj}from"node:path";import{captureSdkError as y2,createSessionId as NE,isLikelyAuthError as wE,normalizeUserInput as SE}from"@cline/shared";import{setHomeDirIfUnset as CE}from"@cline/shared/storage";var yX={};w(yX,{saveProviderOAuthCredentials:()=>p$,resolveProviderApiKeyFromSettings:()=>pZ,loginAndSaveProviderOAuthCredentials:()=>x4,isOAuthProvider:()=>l$,getProviderOAuthCredentialsFromSettings:()=>g4,getProviderAuthStorageId:()=>lZ,getProviderAuthHandler:()=>Z0,getPersistedProviderApiKey:()=>Q8,formatProviderOAuthApiKey:()=>rZ});import{getClineEnvironmentConfig as SX}from"@cline/shared";O0();var AX={};w(AX,{startClineDeviceAuth:()=>mZ,refreshClineToken:()=>O5,loginClineOAuth:()=>C4,getValidClineCredentials:()=>y4,completeClineDeviceAuth:()=>vZ});import{getClineEnvironmentConfig as hZ}from"@cline/shared";var ZX={};w(ZX,{startLocalOAuthServer:()=>Q1});function YR(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function Q1($){let J=await import("node:http"),Q=$.host??"127.0.0.1",Z=$.timeoutMs??300000,W=$.successHtml??VR,j=YR(),f=!1,X=null,Y=null,V=null,H=(K)=>{if(f)return;f=!0,j.resolve(K)},B=()=>{if(X)clearTimeout(X),X=null;let K=V;if(V=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:K})).catch(()=>{})},A=async()=>{return X=setTimeout(()=>{B(),H(null)},Z),j.promise};for(let K of $.ports){let G=J.createServer((D,U)=>{try{let F=new URL(D.url||"",`http://${Q}:${K}`);if(F.pathname!==$.callbackPath){U.statusCode=404,U.end("Not found");return}let O={url:F,code:F.searchParams.get("code")??void 0,state:F.searchParams.get("state")??void 0,provider:F.searchParams.get("provider")??void 0,error:F.searchParams.get("error")??void 0};if(O.error){U.statusCode=400,U.end(`Authentication failed: ${O.error}`),B(),H(O);return}if(!O.code){U.statusCode=400,U.end("Missing authorization code");return}if($.expectedState&&O.state!==$.expectedState){U.statusCode=400,U.end("State mismatch");return}U.statusCode=200,U.setHeader("Content-Type","text/html; charset=utf-8"),U.end(W),B(),H(O)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((D)=>{let U=(F)=>{G.off("error",U),D({bound:!1,error:F})};G.once("error",U),G.listen(K,Q,()=>{G.off("error",U),Y=G,D({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw B(),R.error}if(R.bound){V=K;let D=`http://${Q}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:K,callbackUrl:D})).catch(()=>{});return{callbackUrl:D,waitForCallback:A,cancelWait:()=>{B(),H(null)},close:()=>{B(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var VR=`<!DOCTYPE html>
280
280
  <html lang="en">
281
281
  <head>
282
282
  <meta charset="utf-8">
@@ -317,22 +317,22 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
317
317
  </div>
318
318
  <script>setTimeout(() => window.close(), 3000);</script>
319
319
  </body>
320
- </html>`;function xj($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function CR($){let J=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function yR($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),xj(f)}async function H6(){let $=yR(),f=xj(await CR($));return{verifier:$,challenge:f}}function B6($){return $.endsWith("/")?$.slice(0,-1):$}function d$($,f){return new URL(f,`${B6($)}/`).toString()}function tf($,f={}){let J=$.trim();if(!J)return{};try{let Q=new URL(J);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:f.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[Q,Z]=J.split("#",2);return{code:Q||void 0,state:Z||void 0}}if(J.includes("code=")){let Q=new URLSearchParams(J);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:f.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function SR($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function M0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=SR(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function sf($){try{let f=JSON.parse($),J=f.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function of($,f){return Date.now()>=$.expires-f}async function ef($){if(!$.onManualCodeInput){let W=await $.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let f,J,Q=$.onManualCodeInput().then((W)=>{f=W,$.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return tf(f,$.parseOptions);if(await Q,J)throw J;if(f)return tf(f,$.parseOptions);return{}}var K6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},cj={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},zQ="https://api.workos.com",ER="/auth",gj=Array.from({length:11},($,f)=>48801+f),hR=300000,bR=30000,$2=30000,kR=300,IR=5;class W$ extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function xR($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function OQ($,f,J={}){let Q=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:xR($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function MQ($){if(!$)return{};return typeof $==="function"?await $():$}function mj($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function vj($){await new Promise((f)=>setTimeout(f,$))}function TQ($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function uj($,f){let J=await fetch(d$(zQ,cj.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??$2)}),Q=await J.json().catch(()=>({}));if(!J.ok)throw new W$(`Device authorization failed: ${J.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:J.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:mj(Q.expires_in,kR),pollIntervalSeconds:mj(Q.interval,IR)}}async function dj($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let Q=await fetch(d$($.workosApiBaseUrl,cj.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await Q.json().catch(()=>({}));if(Q.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await vj(J*1000);break}case"slow_down":{J+=1,await vj(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new W$(Z.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:Z.error});default:throw new W$(`WorkOS token polling failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function lj($,f,J){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(d$(f.apiBaseUrl,K6.register),{method:"POST",headers:{"Content-Type":"application/json",...await MQ(f.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(f.requestTimeoutMs??$2)});if(!Z.ok){let j=await Z.text().catch(()=>""),X=sf(j);throw new W$(`Token registration failed: ${Z.status}${X.message?` - ${X.message}`:""}`,{status:Z.status,errorCode:X.code})}let W=await Z.json();return OQ(TQ(W,"Invalid token exchange response"),J??f.provider)}async function gR($,f,J,Q){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:Q??J.provider},W=await fetch(d$(J.apiBaseUrl,K6.token),{method:"POST",headers:{"Content-Type":"application/json",...await MQ(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??$2)});if(!W.ok){let X=await W.text().catch(()=>""),Y=sf(X);throw new W$(`Token exchange failed: ${W.status}${Y.message?` - ${Y.message}`:""}`,{status:W.status,errorCode:Y.code})}let j=await W.json();return OQ(TQ(j,"Invalid token exchange response"),Q??J.provider)}async function M8($){N1($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:gj,Q=$.callbackPath??ER,Z=f?null:await $1({ports:J,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??gj[0]}${Q}`;try{let j;if(f){let X=_Q().workOsClientId,Y=await uj(X,$);$.callbacks.onAuth({url:Y.verificationUriComplete??Y.verificationUri,instructions:`Enter this code in your browser: ${Y.userCode}`});let A=await dj({clientId:X,deviceCode:Y.deviceCode,expiresInSeconds:Y.expiresInSeconds,initialPollIntervalSeconds:Y.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??$2,workosApiBaseUrl:zQ,onProgress:$.callbacks.onProgress});j=await lj(A,$,$.provider)}else{let X=new URL(d$($.apiBaseUrl,K6.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",W),X.searchParams.set("redirect_uri",W),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let Y,A=$.provider,V=await ef({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(V.error)throw Error(`OAuth error: ${V.error}`);if(Y=V.code,A=V.provider??A,!Y){let H=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=tf(H,{includeProvider:!0});Y=B.code,A=B.provider??A}if(!Y)throw Error("Missing authorization code");j=await gR(Y,W,$,A)}return q1($.telemetry,$.provider??"cline"),C1($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw w1($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function NQ($){return await uj(_Q().workOsClientId,$)}async function qQ($){let f=$.provider??"cline";N1($.telemetry,f);try{let J=await dj({clientId:_Q().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??$2,workosApiBaseUrl:zQ}),Q=await lj(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return q1($.telemetry,f),C1($.telemetry,{id:Q.accountId,email:Q.email,provider:f}),Q}catch(J){throw w1($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function G6($,f){let J=await fetch(d$(f.apiBaseUrl,K6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await MQ(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??$2)});if(!J.ok){let W=await J.text().catch(()=>""),j=sf(W);throw new W$(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let Q=await J.json(),Z=$.metadata?.provider??f.provider;return OQ(TQ(Q,"Invalid token refresh response"),Z,$)}async function T8($,f,J){if(!$)return null;let Q=J?.refreshBufferMs??hR,Z=J?.retryableTokenGraceMs??bR;if(J?.forceRefresh!==!0&&!of($,Q))return $;try{return await G6($,f)}catch(j){if(j instanceof W$&&j.isLikelyInvalidGrant())return f$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}_0();var ij={};q(ij,{refreshOpenAICodexToken:()=>P6,loginOpenAICodex:()=>N8,getValidOpenAICodexCredentials:()=>q8,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as mR}from"nanoid";var e={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class F6 extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function vR($,f,J=e.redirectUri){let Q=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let Z=await Q.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function cR($){try{let f=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!f.ok){let Q=await f.text().catch(()=>""),Z=sf(Q);throw new F6(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch(f){if(f instanceof F6)throw f;return{type:"failed"}}}async function uR($="pi"){let{verifier:f,challenge:J}=await H6(),Q=mR(32),Z=new URL(e.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",e.clientId),Z.searchParams.set("redirect_uri",e.redirectUri),Z.searchParams.set("scope",e.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",Q),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:Q,url:Z.toString()}}function dR(){try{let $=new URL(e.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):e.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:e.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function lR($,f){let J=f?M0(f):M0($),Q=J?J:M0($),W=Q?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.organizations;if(Array.isArray(j)&&j.length>0){let Y=j[0];if(typeof Y?.id==="string"&&Y.id.length>0)return Y.id}let X=Q?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function rj($,f){let J=lR($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function N8($){N1($.telemetry,"openai-codex");let f=dR(),{verifier:J,state:Q,url:Z}=await uR($.originator),W=await $1({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:Q});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let X=await ef({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Q)throw Error("State mismatch");if(j=X.code,!j){let V=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),H=tf(V,{allowHashCodeState:!0});if(H.state&&H.state!==Q)throw Error("State mismatch");j=H.code}if(!j)throw Error("Missing authorization code");let Y=await vR(j,J,f.redirectUri);if(Y.type!=="success")throw Error("Token exchange failed");let A=rj(Y);return q1($.telemetry,"openai-codex"),C1($.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(X){throw w1($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{W.close()}}async function P6($,f){let J=await cR($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=rj(J,f);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function q8($,f){if(!$)return null;let J=f?.refreshBufferMs??e.refreshBufferMs,Q=f?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!of($,J))return $;try{return await P6($.refresh,$)}catch(W){if(W instanceof F6&&W.isLikelyInvalidGrant())return f$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}_0();var XX={};q(XX,{refreshOcaToken:()=>L6,loginOcaOAuth:()=>C8,getValidOcaCredentials:()=>y8,OCI_HEADER_OPC_REQUEST_ID:()=>pR,DEFAULT_INTERNAL_OCA_BASE_URL:()=>R6,DEFAULT_INTERNAL_IDCS_URL:()=>tj,DEFAULT_INTERNAL_IDCS_SCOPES:()=>sj,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>aj,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>D6,DEFAULT_EXTERNAL_IDCS_URL:()=>ej,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>$X,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>oj});import{nanoid as nj}from"nanoid";class wQ{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),Q=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+Q})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var aj="a8331954c0cf48ba99b5dd223a14c6ea",tj="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",sj="openid offline_access",R6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",oj="c1aba3deed5740659981a752714eba33",ej="https://login-ext.identity.oraclecloud.com",$X="openid offline_access",D6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",pR="opc-request-id",rR="/auth/oca",iR=Array.from({length:11},($,f)=>48801+f),nR=300000,aR=30000,fX=30000,tR=600000;class U6 extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var j$={internal:{clientId:aj,idcsUrl:tj,scopes:sj,baseUrl:R6},external:{clientId:oj,idcsUrl:ej,scopes:$X,baseUrl:D6}},w8=new Map,sR=86400000,oR=300000,eR=32,CQ=new wQ(sR,eR);function JX($){if(typeof $==="function")return $();return $??"internal"}function QX($){return{internal:{clientId:$?.internal?.clientId??j$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??j$.internal.idcsUrl,scopes:$?.internal?.scopes??j$.internal.scopes,baseUrl:$?.internal?.baseUrl??j$.internal.baseUrl},external:{clientId:$?.external?.clientId??j$.external.clientId,idcsUrl:$?.external?.idcsUrl??j$.external.idcsUrl,scopes:$?.external?.scopes??j$.external.scopes,baseUrl:$?.external?.baseUrl??j$.external.baseUrl}}}function $D($=Date.now()){let f=$-tR;for(let[J,Q]of w8.entries())if(Q.createdAt<f)w8.delete(J)}function fD($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=M0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=M0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function ZX($,f,J){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=M0($.id_token),j=M0(Q),X=W?.sub??j?.sub,Y=W?.email??j?.email;return{access:Q,refresh:Z,expires:fD($,Q,$.id_token),accountId:X??J?.accountId,email:Y??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:X,idToken:$.id_token}}}async function WX($,f){let J=B6($),Q=CQ.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!W.ok){let Y=`${J}/oauth2/v1/token`;return CQ.set(J,Y,Date.now(),oR),Y}let X=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return CQ.set(J,X),X}function jX($){return{code:$.error,message:$.error_description}}async function JD($){let f=w8.get($.state);if(!f)throw Error("No PKCE verifier found for this state");w8.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,Q=await WX(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await W.json();if(!W.ok){let Y=jX(j);throw new U6(`Token exchange failed: ${W.status}${Y.message?` - ${Y.message}`:""}`,{status:W.status,errorCode:Y.code})}let X=M0(j.id_token);if(!j.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return ZX(j,$.mode)}function QD($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${B6(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function C8($){N1($.telemetry,"oca");let f=QX($.config),J=JX($.mode),Q=$.callbackPorts?.length?$.callbackPorts:iR,Z=$.callbackPath??rR,W=$.requestTimeoutMs??fX,j=await $1({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=j.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let Y=nj(16),A=nj(16),{verifier:V,challenge:H}=await H6();$D(),w8.set(Y,{verifier:V,nonce:A,mode:J,redirectUri:X,createdAt:Date.now()});let B=QD({callbackUrl:X,mode:J,state:Y,nonce:A,challenge:H,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await ef({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==Y)throw Error("State mismatch");let P=await JD({code:G,state:R,mode:J,config:f,requestTimeoutMs:W});return q1($.telemetry,"oca"),C1($.telemetry,{id:P.accountId,email:P.email,provider:"oca"}),P}catch(K){throw w1($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function L6($,f={}){let J=QX(f.config),Q=f.requestTimeoutMs??fX,Z=$.metadata?.mode,W=Z==="internal"||Z==="external"?Z:JX(f.mode),j=W==="external"?J.external:J.internal,X=await WX(j.idcsUrl,Q),Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),A=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,signal:AbortSignal.timeout(Q)}),V=await A.json();if(!A.ok){let H=jX(V);throw new U6(`Token refresh failed: ${A.status}${H.message?` - ${H.message}`:""}`,{status:A.status,errorCode:H.code})}return ZX(V,W,$)}async function y8($,f,J){if(!$)return null;let Q=f?.refreshBufferMs??J?.refreshBufferMs??nR,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??aR;if(f?.forceRefresh!==!0&&!of($,Q))return $;try{return await L6($,J)}catch(j){if(j instanceof U6&&j.isLikelyInvalidGrant())return f$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}var _6="workos:";function ZD($){let f=$.trim();return f.toLowerCase().startsWith(_6)?f:`${_6}${f}`}function WD($){let f=$.trim();return f.toLowerCase().startsWith(_6)?f.slice(_6.length):f}function jD($){let J=M0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function XD($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=jD(f);if(Q)return Q;return Date.now()-1}function YD($,f){let J=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=f?.normalizeAccessToken?.(J)??J;if(!Z)return null;return{access:Z,refresh:Q,expires:XD($,Z),accountId:$.auth?.accountId}}function AD($){let f=$.formatAccessToken?.($.credentials.access)??$.credentials.access,J={...$.settings?.auth??{},accessToken:f,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:J};if($.save!==!1)$.manager.saveProviderSettings(Q,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return Q}function yQ($){let f=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:f,getApiKey(J){let Q=J?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(J){return AD({...J,storageProviderId:f,formatAccessToken:$.formatAccessToken})},isConfigured(J){return!!J?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}var VD=[yQ({providerId:"cline",formatAccessToken:ZD,normalizeStoredAccessToken:WD,login:({settings:$,callbacks:f,telemetry:J})=>M8({apiBaseUrl:$?.baseUrl?.trim()||YX().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:f,telemetry:J}),refresh:({settings:$,credentials:f,forceRefresh:J,telemetry:Q})=>T8(f,{apiBaseUrl:$.baseUrl?.trim()||YX().apiBaseUrl,telemetry:Q},{forceRefresh:J})}),yQ({providerId:"oca",login:({settings:$,callbacks:f,telemetry:J})=>C8({mode:$?.oca?.mode,callbacks:f,telemetry:J}),refresh:({settings:$,credentials:f,forceRefresh:J,telemetry:Q})=>y8(f,{forceRefresh:J,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),yQ({providerId:"openai-codex",login:({callbacks:$,telemetry:f})=>N8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:f}),refresh:({credentials:$,forceRefresh:f,telemetry:J})=>q8($,{forceRefresh:f,telemetry:J})})],HD=new Map(VD.map(($)=>[$.providerId,$]));function B0($){return HD.get($.trim().toLowerCase())}function l$($){return B0($)!==void 0}function SQ($){return B0($)?.storageProviderId}function EQ($,f){let J=B0(f),Q=J?.storageProviderId??f,Z=$.getProviderSettings(Q);return J?.getApiKey(Z)??z6(f,Z)}async function S8($,f,J){let Q=B0(f);if(!Q)throw Error(`Provider "${f}" does not support OAuth login`);let Z=$.getProviderSettings(Q.storageProviderId),W=await Q.login({settings:Z,callbacks:J.callbacks,telemetry:J.telemetry});return Q.saveCredentials({manager:$,settings:Z,credentials:W})}function E8($,f){let J=B0($);if(!J)return null;return YD(f,{normalizeAccessToken:J.normalizeStoredAccessToken})}function p$($){let f=B0($.providerId);if(!f)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return f.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function z6($,f){let J=B0($);if(J)return J.getApiKey(f);return f?.auth?.accessToken?.trim()||f?.apiKey?.trim()||f?.auth?.apiKey?.trim()||void 0}function hQ($,f){let J=B0($);if(!J)return f.access;return J.getApiKey({provider:J.storageProviderId,auth:{accessToken:f.access}})??f.access}_0();var kX={};q(kX,{createContextCompactionPrepareTurn:()=>g8});import{createHandlerAsync as PD}from"@cline/llms";import{estimateTokens as bQ}from"@cline/shared";var BX=200000,kQ=0.9,KX=16384,IQ=20000,VX=1024,HX=2000,GX=2000,FX=8;function X$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
321
- ...[truncated ${$.length-f} chars]`}function BD($){let f=xQ($);if(typeof f==="string")return f;return f.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
322
- ${J.content}
323
- </file>`;case"image":return`[image:${J.mediaType}]`;default:return""}}).join(`
324
- `)}function xQ($){if(typeof $==="string")return X$($,HX);return $.map((f)=>{switch(f.type){case"text":return{...f,text:X$(f.text,HX)};case"file":return{...f,content:X$(f.content,GX)};case"image":return f;default:return f}})}function KD($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function PX($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let f=[];for(let J of $.content)switch(J.type){case"text":f.push(`[${$.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":f.push(`[Bot thinking]: ${X$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${KD(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${BD(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${X$(J.content,GX)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
325
- `)}function RX($){return $.map(PX).join(`
326
-
327
- `).trim()}function DX(){let $=new WeakMap;return(f)=>{let J=f,Q=$.get(J);if(typeof Q==="number")return Q;let Z;try{Z=JSON.stringify(f)}catch{Z=PX(f)}let W=bQ(Z.length);return $.set(J,W),W}}function k8($){return $.metadata?.kind==="compaction_summary"}function gQ($){if(!k8($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function GD($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function I8($){return $.role==="user"&&!GD($)&&!k8($)}function UX($){for(let f=0;f<$.length;f+=1)if(I8($[f]))return f;return-1}function O6($){for(let f=$.length-1;f>=0;f-=1)if(I8($[f]))return f;return 0}function LX($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function _X($){for(let f=$.length-1;f>=0;f-=1)if(k8($[f]))return f;return-1}function zX($,f,J){let Q=O6($);if(Q<=0)return 0;let Z=0,W=$.length;for(let X=$.length-1;X>=0;X-=1)if(Z+=J($[X]),W=X,Z>=f)break;if(W<=0)return 0;let j=Math.min(W,Q);while(j>0&&!I8($[j]))j-=1;return j}function b8($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>b8(f));if($&&typeof $==="object"){let f=$,J=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...b8(f[Q]));if(Array.isArray(f.files)){for(let Q of f.files)if(Q&&typeof Q==="object")J.push(...b8(Q.path))}if(Array.isArray(f.file_paths))J.push(...b8(f.file_paths));return J}return[]}function h8($,f){let J=new Set($);for(let Q of f){let Z=Q.trim();if(!Z)continue;J.add(Z)}return[...J].sort((Q,Z)=>Q.localeCompare(Z))}function OX($){let f=[],J=[];for(let Q of $){let Z=gQ(Q);if(Z){f=h8(f,Z.details.readFiles),J=h8(J,Z.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let W of Q.content){if(W.type==="file"){f=h8(f,[W.path]);continue}if(W.type!=="tool_use")continue;let j=b8(W.input);if(W.name==="read_files"){f=h8(f,j);continue}if(W.name==="editor"||W.name==="apply_patch")J=h8(J,j)}}return{readFiles:f,modifiedFiles:J}}function FD($){let f=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
328
- `):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((Q)=>`- ${Q}`).join(`
320
+ </html>`;function WX($){let J="";for(let Q=0;Q<$.length;Q+=1)J+=String.fromCharCode($[Q]??0);return btoa(J).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function HR($){let Q=new TextEncoder().encode($),Z=await crypto.subtle.digest("SHA-256",Q);return new Uint8Array(Z)}function BR($=32){let J=new Uint8Array($);return crypto.getRandomValues(J),WX(J)}async function z5(){let $=BR(),J=WX(await HR($));return{verifier:$,challenge:J}}function L5($){return $.endsWith("/")?$.slice(0,-1):$}function d$($,J){return new URL(J,`${L5($)}/`).toString()}function o2($,J={}){let Q=$.trim();if(!Q)return{};try{let Z=new URL(Q);return{code:Z.searchParams.get("code")??void 0,state:Z.searchParams.get("state")??void 0,provider:J.includeProvider?Z.searchParams.get("provider")??void 0:void 0}}catch{}if(J.allowHashCodeState&&Q.includes("#")){let[Z,W]=Q.split("#",2);return{code:Z||void 0,state:W||void 0}}if(Q.includes("code=")){let Z=new URLSearchParams(Q);return{code:Z.get("code")??void 0,state:Z.get("state")??void 0,provider:J.includeProvider?Z.get("provider")??void 0:void 0}}return{code:Q}}function AR($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function q0($){if(!$)return null;try{let J=$.split(".");if(J.length!==3)return null;let Q=J[1];if(!Q)return null;let Z=Q.replace(/-/g,"+").replace(/_/g,"/"),W=Z.padEnd(Z.length+(4-Z.length%4)%4,"="),j=AR(W);if(!j)return null;return JSON.parse(j)}catch{return null}}function t2($){try{let J=JSON.parse($),Q=J.error,Z=typeof Q==="string"?Q:Q&&typeof Q==="object"&&typeof Q.type==="string"?Q.type:void 0,W=typeof J.error_description==="string"?J.error_description:typeof J.message==="string"?J.message:Q&&typeof Q==="object"&&typeof Q.message==="string"?Q.message:void 0;return{code:Z,message:W}}catch{return{}}}function e2($,J){return Date.now()>=$.expires-J}async function $8($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let J,Q,Z=$.onManualCodeInput().then((j)=>{J=j,$.cancelWait()}).catch((j)=>{Q=j instanceof Error?j:Error(String(j)),$.cancelWait()}),W=await $.waitForCallback();if(Q)throw Q;if(W?.code||W?.error)return{code:W.code,state:W.state,provider:W.provider,error:W.error};if(J)return o2(J,$.parseOptions);if(await Z,Q)throw Q;if(J)return o2(J,$.parseOptions);return{}}var _5={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},YX={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},kZ="https://api.workos.com",KR="/auth",jX=Array.from({length:11},($,J)=>48801+J),GR=300000,FR=30000,J8=30000,DR=300,UR=5;class f$ extends Error{status;errorCode;constructor($,J){super($);this.name="ClineOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function RR($){let J=Date.parse($);if(Number.isNaN(J))throw Error(`Invalid expiresAt value: ${$}`);return J}function IZ($,J,Q={}){let Z=$.userInfo.clineUserId??Q.accountId,W=$.refreshToken??Q.refresh;if(!W)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:W,expires:RR($.expiresAt),accountId:Z??void 0,email:$.userInfo.email||Q.email,metadata:{provider:J,tokenType:$.tokenType,userInfo:$.userInfo}}}async function xZ($){if(!$)return{};return typeof $==="function"?await $():$}function fX($,J){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return J;return Math.floor($)}async function XX($){await new Promise((J)=>setTimeout(J,$))}function gZ($,J){if(!$.success||!$.data?.accessToken)throw Error(J);return $.data}async function VX($,J){let Q=await fetch(d$(kZ,YX.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(J?.requestTimeoutMs??J8)}),Z=await Q.json().catch(()=>({}));if(!Q.ok)throw new f$(`Device authorization failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error});if(!Z.device_code||!Z.user_code||!Z.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Z.device_code,userCode:Z.user_code,verificationUri:Z.verification_uri,verificationUriComplete:Z.verification_uri_complete,expiresInSeconds:fX(Z.expires_in,DR),pollIntervalSeconds:fX(Z.interval,UR)}}async function HX($){let J=Date.now()+$.expiresInSeconds*1000,Q=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=J){let Z=await fetch(d$($.workosApiBaseUrl,YX.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),W=await Z.json().catch(()=>({}));if(Z.ok){if(!W.access_token||!W.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:W.access_token,refreshToken:W.refresh_token,tokenType:W.token_type??"Bearer"}}switch(W.error){case"authorization_pending":{await XX(Q*1000);break}case"slow_down":{Q+=1,await XX(Q*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new f$(W.error_description||"WorkOS authorization failed",{status:Z.status,errorCode:W.error});default:throw new f$(`WorkOS token polling failed: ${Z.status}${W.error_description?` - ${W.error_description}`:""}`,{status:Z.status,errorCode:W.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function BX($,J,Q){let Z={accessToken:$.accessToken,refreshToken:$.refreshToken},W=await fetch(d$(J.apiBaseUrl,_5.register),{method:"POST",headers:{"Content-Type":"application/json",...await xZ(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??J8)});if(!W.ok){let f=await W.text().catch(()=>""),X=t2(f);throw new f$(`Token registration failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return IZ(gZ(j,"Invalid token exchange response"),Q??J.provider)}async function zR($,J,Q,Z){let W={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:J,provider:Z??Q.provider},j=await fetch(d$(Q.apiBaseUrl,_5.token),{method:"POST",headers:{"Content-Type":"application/json",...await xZ(Q.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(Q.requestTimeoutMs??J8)});if(!j.ok){let X=await j.text().catch(()=>""),Y=t2(X);throw new f$(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let f=await j.json();return IZ(gZ(f,"Invalid token exchange response"),Z??Q.provider)}async function C4($){N1($.telemetry,$.provider??"cline");let J=$.useWorkOSDeviceAuth??!0,Q=$.callbackPorts?.length?$.callbackPorts:jX,Z=$.callbackPath??KR,W=J?null:await Q1({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=W?.callbackUrl||`http://127.0.0.1:${Q[0]??jX[0]}${Z}`;try{let f;if(J){let X=hZ().workOsClientId,Y=await VX(X,$);$.callbacks.onAuth({url:Y.verificationUriComplete??Y.verificationUri,instructions:`Enter this code in your browser: ${Y.userCode}`});let V=await HX({clientId:X,deviceCode:Y.deviceCode,expiresInSeconds:Y.expiresInSeconds,initialPollIntervalSeconds:Y.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??J8,workosApiBaseUrl:kZ,onProgress:$.callbacks.onProgress});f=await BX(V,$,$.provider)}else{let X=new URL(d$($.apiBaseUrl,_5.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",j),X.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let Y,V=$.provider,H=await $8({waitForCallback:W?.waitForCallback??(async()=>null),cancelWait:W?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(Y=H.code,V=H.provider??V,!Y){let B=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=o2(B,{includeProvider:!0});Y=A.code,V=A.provider??V}if(!Y)throw Error("Missing authorization code");f=await zR(Y,j,$,V)}return w1($.telemetry,$.provider??"cline"),C1($.telemetry,{id:f.accountId,email:f.email,provider:$.provider??"cline"}),f}catch(f){throw S1($.telemetry,$.provider??"cline",f instanceof Error?f.message:String(f)),f}finally{W?.close()}}async function mZ($){return await VX(hZ().workOsClientId,$)}async function vZ($){let J=$.provider??"cline";N1($.telemetry,J);try{let Q=await HX({clientId:hZ().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??J8,workosApiBaseUrl:kZ}),Z=await BX(Q,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return w1($.telemetry,J),C1($.telemetry,{id:Z.accountId,email:Z.email,provider:J}),Z}catch(Q){throw S1($.telemetry,J,Q instanceof Error?Q.message:String(Q)),Q}}async function O5($,J){let Q=await fetch(d$(J.apiBaseUrl,_5.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await xZ(J.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(J.requestTimeoutMs??J8)});if(!Q.ok){let j=await Q.text().catch(()=>""),f=t2(j);throw new f$(`Token refresh failed: ${Q.status}${f.message?` - ${f.message}`:""}`,{status:Q.status,errorCode:f.code})}let Z=await Q.json(),W=$.metadata?.provider??J.provider;return IZ(gZ(Z,"Invalid token refresh response"),W,$)}async function y4($,J,Q){if(!$)return null;let Z=Q?.refreshBufferMs??GR,W=Q?.retryableTokenGraceMs??FR;if(Q?.forceRefresh!==!0&&!e2($,Z))return $;try{return await O5($,J)}catch(f){if(f instanceof f$&&f.isLikelyInvalidGrant())return Q$(J.telemetry,J.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}O0();var GX={};w(GX,{refreshOpenAICodexToken:()=>M5,loginOpenAICodex:()=>E4,getValidOpenAICodexCredentials:()=>b4,OPENAI_CODEX_OAUTH_CONFIG:()=>$0});import{nanoid as LR}from"nanoid";var $0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class T5 extends Error{status;errorCode;constructor($,J){super($);this.name="OpenAICodexOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function _R($,J,Q=$0.redirectUri){let Z=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:$0.clientId,code:$,code_verifier:J,redirect_uri:Q}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!Z.ok)return{type:"failed"};let W=await Z.json();if(!W.access_token||!W.refresh_token||typeof W.expires_in!=="number")return{type:"failed"};return{type:"success",access:W.access_token,refresh:W.refresh_token,expires:Date.now()+W.expires_in*1000,email:W.email,idToken:W.id_token}}async function OR($){try{let J=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:$0.clientId}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!J.ok){let Z=await J.text().catch(()=>""),W=t2(Z);throw new T5(`Token refresh failed: ${J.status}${W.message?` - ${W.message}`:""}`,{status:J.status,errorCode:W.code})}let Q=await J.json();if(!Q.access_token||!Q.refresh_token||typeof Q.expires_in!=="number")return{type:"failed"};return{type:"success",access:Q.access_token,refresh:Q.refresh_token,expires:Date.now()+Q.expires_in*1000,email:Q.email,idToken:Q.id_token}}catch(J){if(J instanceof T5)throw J;return{type:"failed"}}}async function TR($="pi"){let{verifier:J,challenge:Q}=await z5(),Z=LR(32),W=new URL($0.authorizationEndpoint);return W.searchParams.set("response_type","code"),W.searchParams.set("client_id",$0.clientId),W.searchParams.set("redirect_uri",$0.redirectUri),W.searchParams.set("scope",$0.scopes),W.searchParams.set("code_challenge",Q),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("state",Z),W.searchParams.set("id_token_add_organizations","true"),W.searchParams.set("codex_cli_simplified_flow","true"),W.searchParams.set("originator",$),{verifier:J,state:Z,url:W.toString()}}function MR(){try{let $=new URL($0.redirectUri),J=$.port.length>0?Number.parseInt($.port,10):$0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(J)?J:$0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:$0.callbackPort,callbackPath:"/auth/callback",redirectUri:$0.redirectUri}}}function qR($,J){let Q=J?q0(J):q0($),Z=Q?Q:q0($),j=Z?.[$0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let f=Z?.organizations;if(Array.isArray(f)&&f.length>0){let Y=f[0];if(typeof Y?.id==="string"&&Y.id.length>0)return Y.id}let X=Z?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function KX($,J){let Q=qR($.access,$.idToken)??J?.accountId;if(!Q)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||J?.refresh||"",expires:$.expires,accountId:Q,email:$.email??J?.email,metadata:{...J?.metadata??{},provider:"openai-codex"}}}async function E4($){N1($.telemetry,"openai-codex");let J=MR(),{verifier:Q,state:Z,url:W}=await TR($.originator),j=await Q1({host:J.host,ports:[J.port],callbackPath:J.callbackPath,expectedState:Z});$.onAuth({url:W,instructions:"Continue the authentication process in your browser."});let f;try{let X=await $8({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Z)throw Error("State mismatch");if(f=X.code,!f){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=o2(H,{allowHashCodeState:!0});if(B.state&&B.state!==Z)throw Error("State mismatch");f=B.code}if(!f)throw Error("Missing authorization code");let Y=await _R(f,Q,J.redirectUri);if(Y.type!=="success")throw Error("Token exchange failed");let V=KX(Y);return w1($.telemetry,"openai-codex"),C1($.telemetry,{id:V.accountId,email:V.email,provider:"openai-codex"}),V}catch(X){throw S1($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{j.close()}}async function M5($,J){let Q=await OR($);if(Q.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Z=KX(Q,J);if(!Z.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Z}async function b4($,J){if(!$)return null;let Q=J?.refreshBufferMs??$0.refreshBufferMs,Z=J?.retryableTokenGraceMs??$0.retryableTokenGraceMs;if(J?.forceRefresh!==!0&&!e2($,Q))return $;try{return await M5($.refresh,$)}catch(j){if(j instanceof T5&&j.isLikelyInvalidGrant())return Q$(J?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}O0();var wX={};w(wX,{refreshOcaToken:()=>w5,loginOcaOAuth:()=>k4,getValidOcaCredentials:()=>I4,OCI_HEADER_OPC_REQUEST_ID:()=>PR,DEFAULT_INTERNAL_OCA_BASE_URL:()=>q5,DEFAULT_INTERNAL_IDCS_URL:()=>UX,DEFAULT_INTERNAL_IDCS_SCOPES:()=>RX,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>DX,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>P5,DEFAULT_EXTERNAL_IDCS_URL:()=>LX,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>_X,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>zX});import{nanoid as FX}from"nanoid";class cZ{ttlMs;maxEntries;entries=new Map;constructor($,J){this.ttlMs=$;this.maxEntries=J}get($,J=Date.now()){this.pruneExpired(J);let Q=this.entries.get($);if(!Q)return;return this.entries.delete($),this.entries.set($,Q),Q.value}set($,J,Q=Date.now(),Z=this.ttlMs){this.pruneExpired(Q),this.entries.delete($);while(this.entries.size>=this.maxEntries){let W=this.entries.keys().next().value;if(W===void 0)break;this.entries.delete(W)}this.entries.set($,{value:J,expiresAt:Q+Z})}pruneExpired($){for(let[J,Q]of this.entries)if(Q.expiresAt<=$)this.entries.delete(J)}}var DX="a8331954c0cf48ba99b5dd223a14c6ea",UX="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",RX="openid offline_access",q5="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",zX="c1aba3deed5740659981a752714eba33",LX="https://login-ext.identity.oraclecloud.com",_X="openid offline_access",P5="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",PR="opc-request-id",NR="/auth/oca",wR=Array.from({length:11},($,J)=>48801+J),SR=300000,CR=30000,OX=30000,yR=600000;class N5 extends Error{status;errorCode;constructor($,J){super($);this.name="OcaOAuthTokenError",this.status=J?.status,this.errorCode=J?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var X$={internal:{clientId:DX,idcsUrl:UX,scopes:RX,baseUrl:q5},external:{clientId:zX,idcsUrl:LX,scopes:_X,baseUrl:P5}},h4=new Map,ER=86400000,bR=300000,hR=32,uZ=new cZ(ER,hR);function TX($){if(typeof $==="function")return $();return $??"internal"}function MX($){return{internal:{clientId:$?.internal?.clientId??X$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??X$.internal.idcsUrl,scopes:$?.internal?.scopes??X$.internal.scopes,baseUrl:$?.internal?.baseUrl??X$.internal.baseUrl},external:{clientId:$?.external?.clientId??X$.external.clientId,idcsUrl:$?.external?.idcsUrl??X$.external.idcsUrl,scopes:$?.external?.scopes??X$.external.scopes,baseUrl:$?.external?.baseUrl??X$.external.baseUrl}}}function kR($=Date.now()){let J=$-yR;for(let[Q,Z]of h4.entries())if(Z.createdAt<J)h4.delete(Q)}function IR($,J,Q){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let W=q0(J)?.exp;if(typeof W==="number"&&W>0)return W*1000;let f=q0(Q)?.exp;if(typeof f==="number"&&f>0)return f*1000;return Date.now()+3600000}function qX($,J,Q){let Z=$.access_token;if(!Z)throw Error("Token response did not include an access token");let W=$.refresh_token??Q?.refresh;if(!W)throw Error("Token response did not include a refresh token");let j=q0($.id_token),f=q0(Z),X=j?.sub??f?.sub,Y=j?.email??f?.email;return{access:Z,refresh:W,expires:IR($,Z,$.id_token),accountId:X??Q?.accountId,email:Y??Q?.email,metadata:{...Q?.metadata??{},provider:"oca",mode:J,subject:X,idToken:$.id_token}}}async function PX($,J){let Q=L5($),Z=uZ.get(Q);if(Z)return Z;let W=`${Q}/.well-known/openid-configuration`,j=await fetch(W,{method:"GET",signal:AbortSignal.timeout(J)});if(!j.ok){let Y=`${Q}/oauth2/v1/token`;return uZ.set(Q,Y,Date.now(),bR),Y}let X=(await j.json()).token_endpoint||`${Q}/oauth2/v1/token`;return uZ.set(Q,X),X}function NX($){return{code:$.error,message:$.error_description}}async function xR($){let J=h4.get($.state);if(!J)throw Error("No PKCE verifier found for this state");h4.delete($.state);let Q=$.mode==="external"?$.config.external:$.config.internal,Z=await PX(Q.idcsUrl,$.requestTimeoutMs),W=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:J.redirectUri,client_id:Q.clientId,code_verifier:J.verifier}),j=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,signal:AbortSignal.timeout($.requestTimeoutMs)}),f=await j.json();if(!j.ok){let Y=NX(f);throw new N5(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let X=q0(f.id_token);if(!f.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==J.nonce)throw Error("OIDC nonce verification failed");return qX(f,$.mode)}function gR($){let J=$.mode==="external"?$.config.external:$.config.internal,Q=new URL(`${L5(J.idcsUrl)}/oauth2/v1/authorize`);return Q.searchParams.set("client_id",J.clientId),Q.searchParams.set("response_type","code"),Q.searchParams.set("scope",J.scopes),Q.searchParams.set("code_challenge",$.challenge),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",$.callbackUrl),Q.searchParams.set("state",$.state),Q.searchParams.set("nonce",$.nonce),Q.toString()}async function k4($){N1($.telemetry,"oca");let J=MX($.config),Q=TX($.mode),Z=$.callbackPorts?.length?$.callbackPorts:wR,W=$.callbackPath??NR,j=$.requestTimeoutMs??OX,f=await Q1({ports:Z,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=f.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let Y=FX(16),V=FX(16),{verifier:H,challenge:B}=await z5();kR(),h4.set(Y,{verifier:H,nonce:V,mode:Q,redirectUri:X,createdAt:Date.now()});let A=gR({callbackUrl:X,mode:Q,state:Y,nonce:V,challenge:B,config:J});$.callbacks.onAuth({url:A,instructions:"Continue the authentication process in your browser."});try{let K=await $8({waitForCallback:f.waitForCallback,cancelWait:f.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==Y)throw Error("State mismatch");let D=await xR({code:G,state:R,mode:Q,config:J,requestTimeoutMs:j});return w1($.telemetry,"oca"),C1($.telemetry,{id:D.accountId,email:D.email,provider:"oca"}),D}catch(K){throw S1($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{f.close()}}async function w5($,J={}){let Q=MX(J.config),Z=J.requestTimeoutMs??OX,W=$.metadata?.mode,j=W==="internal"||W==="external"?W:TX(J.mode),f=j==="external"?Q.external:Q.internal,X=await PX(f.idcsUrl,Z),Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:f.clientId}),V=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,signal:AbortSignal.timeout(Z)}),H=await V.json();if(!V.ok){let B=NX(H);throw new N5(`Token refresh failed: ${V.status}${B.message?` - ${B.message}`:""}`,{status:V.status,errorCode:B.code})}return qX(H,j,$)}async function I4($,J,Q){if(!$)return null;let Z=J?.refreshBufferMs??Q?.refreshBufferMs??SR,W=J?.retryableTokenGraceMs??Q?.retryableTokenGraceMs??CR;if(J?.forceRefresh!==!0&&!e2($,Z))return $;try{return await w5($,Q)}catch(f){if(f instanceof N5&&f.isLikelyInvalidGrant())return Q$(Q?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}var S5="workos:";function mR($){let J=$.trim();return J.toLowerCase().startsWith(S5)?J:`${S5}${J}`}function vR($){let J=$.trim();return J.toLowerCase().startsWith(S5)?J.slice(S5.length):J}function cR($){let Q=q0($)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return null}function uR($,J){let Q=$.auth?.expiresAt;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>0)return Q;let Z=cR(J);if(Z)return Z;return Date.now()-1}function dR($,J){let Q=$.auth?.accessToken?.trim(),Z=$.auth?.refreshToken?.trim();if(!Q||!Z)return null;let W=J?.normalizeAccessToken?.(Q)??Q;if(!W)return null;return{access:W,refresh:Z,expires:uR($,W),accountId:$.auth?.accountId}}function lR($){let J=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Q={...$.settings?.auth??{},accessToken:J,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Z={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Q};if($.save!==!1)$.manager.saveProviderSettings(Z,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return Z}function dZ($){let J=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:J,getApiKey(Q){let Z=Q?.auth?.accessToken?.trim();if(Z)return $.formatAccessToken?.(Z)??Z;return Q?.apiKey?.trim()||Q?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Q){return lR({...Q,storageProviderId:J,formatAccessToken:$.formatAccessToken})},isConfigured(Q){return!!Q?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function CX($){return dZ({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:mR,normalizeStoredAccessToken:vR,login:({settings:J,callbacks:Q,telemetry:Z})=>C4({apiBaseUrl:J?.baseUrl?.trim()||SX().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q,telemetry:Z}),refresh:({settings:J,credentials:Q,forceRefresh:Z,telemetry:W})=>y4(Q,{apiBaseUrl:J.baseUrl?.trim()||SX().apiBaseUrl,telemetry:W},{forceRefresh:Z})})}var pR=[CX({providerId:"cline"}),CX({providerId:"cline-pass",storageProviderId:"cline"}),dZ({providerId:"oca",login:({settings:$,callbacks:J,telemetry:Q})=>k4({mode:$?.oca?.mode,callbacks:J,telemetry:Q}),refresh:({settings:$,credentials:J,forceRefresh:Q,telemetry:Z})=>I4(J,{forceRefresh:Q,telemetry:Z},{mode:$.oca?.mode,telemetry:Z})}),dZ({providerId:"openai-codex",login:({callbacks:$,telemetry:J})=>E4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:J}),refresh:({credentials:$,forceRefresh:J,telemetry:Q})=>b4($,{forceRefresh:J,telemetry:Q})})],rR=new Map(pR.map(($)=>[$.providerId,$]));function Z0($){return rR.get($.trim().toLowerCase())}function l$($){return Z0($)!==void 0}function lZ($){return Z0($)?.storageProviderId}function pZ($,J){let Q=Z0(J),Z=Q?.storageProviderId??J,W=$.getProviderSettings(Z);return Q?.getApiKey(W)??Q8(J,W)}async function x4($,J,Q){let Z=Z0(J);if(!Z)throw Error(`Provider "${J}" does not support OAuth login`);let W=$.getProviderSettings(Z.storageProviderId),j=await Z.login({settings:W,callbacks:Q.callbacks,telemetry:Q.telemetry});return Z.saveCredentials({manager:$,settings:W,credentials:j})}function g4($,J){let Q=Z0($);if(!Q)return null;return dR(J,{normalizeAccessToken:Q.normalizeStoredAccessToken})}function p$($){let J=Z0($.providerId);if(!J)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return J.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function Q8($,J){let Q=Z0($);if(Q)return Q.getApiKey(J);return J?.auth?.accessToken?.trim()||J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0}function rZ($,J){let Q=Z0($);if(!Q)return J.access;return Q.getApiKey({provider:Q.storageProviderId,auth:{accessToken:J.access}})??J.access}O0();var ZY={};w(ZY,{createContextCompactionPrepareTurn:()=>l4});import{createHandlerAsync as oR}from"@cline/llms";import{estimateTokens as iZ}from"@cline/shared";var hX=200000,nZ=0.9,kX=16384,aZ=20000,EX=1024,bX=2000,IX=2000,xX=8;function Y$($,J){if($.length<=J)return $;return`${$.slice(0,J)}
321
+ ...[truncated ${$.length-J} chars]`}function iR($){let J=sZ($);if(typeof J==="string")return J;return J.map((Q)=>{switch(Q.type){case"text":return Q.text;case"file":return`<file path="${Q.path}">
322
+ ${Q.content}
323
+ </file>`;case"image":return`[image:${Q.mediaType}]`;default:return""}}).join(`
324
+ `)}function sZ($){if(typeof $==="string")return Y$($,bX);return $.map((J)=>{switch(J.type){case"text":return{...J,text:Y$(J.text,bX)};case"file":return{...J,content:Y$(J.content,IX)};case"image":return J;default:return J}})}function nR($){return Object.entries($).map(([J,Q])=>`${J}=${JSON.stringify(Q)}`).join(", ")}function gX($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let J=[];for(let Q of $.content)switch(Q.type){case"text":J.push(`[${$.role==="user"?"User":"Bot"}]: ${Q.text}`);break;case"thinking":J.push(`[Bot thinking]: ${Y$(Q.thinking,2000)}`);break;case"redacted_thinking":J.push("[Bot thinking]: [redacted]");break;case"tool_use":J.push(`[Bot tool calls]: ${Q.name}(${nR(Q.input)})`);break;case"tool_result":J.push(`[Tool result]: ${iR(Q.content)}`);break;case"file":J.push(`[${$.role==="user"?"User":"Bot"} file ${Q.path}]: ${Y$(Q.content,IX)}`);break;case"image":J.push(`[${$.role==="user"?"User":"Bot"} image]: ${Q.mediaType}`);break}return J.join(`
325
+ `)}function mX($){return $.map(gX).join(`
326
+
327
+ `).trim()}function vX(){let $=new WeakMap;return(J)=>{let Q=J,Z=$.get(Q);if(typeof Z==="number")return Z;let W;try{W=JSON.stringify(J)}catch{W=gX(J)}let j=iZ(W.length);return $.set(Q,j),j}}function c4($){return $.metadata?.kind==="compaction_summary"}function oZ($){if(!c4($))return;let J=$.metadata;if(!J)return;let Q=J.details;return{kind:"compaction_summary",summary:String(J.summary??""),details:{readFiles:Array.isArray(Q?.readFiles)?Q.readFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[],modifiedFiles:Array.isArray(Q?.modifiedFiles)?Q.modifiedFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[]},tokensBefore:Number(J.tokensBefore??0),generatedAt:Number(J.generatedAt??0)}}function aR($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((J)=>J.type==="tool_result")}function u4($){return $.role==="user"&&!aR($)&&!c4($)}function cX($){for(let J=0;J<$.length;J+=1)if(u4($[J]))return J;return-1}function C5($){for(let J=$.length-1;J>=0;J-=1)if(u4($[J]))return J;return 0}function uX($){for(let J=$.length-1;J>=0;J-=1)if($[J].role==="assistant")return J;return-1}function dX($){for(let J=$.length-1;J>=0;J-=1)if(c4($[J]))return J;return-1}function lX($,J,Q){let Z=C5($);if(Z<=0)return 0;let W=0,j=$.length;for(let X=$.length-1;X>=0;X-=1)if(W+=Q($[X]),j=X,W>=J)break;if(j<=0)return 0;let f=Math.min(j,Z);while(f>0&&!u4($[f]))f-=1;return f}function v4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((J)=>v4(J));if($&&typeof $==="object"){let J=$,Q=[];for(let Z of["path","file_path","target_file","new_file_path","old_file_path"])Q.push(...v4(J[Z]));if(Array.isArray(J.files)){for(let Z of J.files)if(Z&&typeof Z==="object")Q.push(...v4(Z.path))}if(Array.isArray(J.file_paths))Q.push(...v4(J.file_paths));return Q}return[]}function m4($,J){let Q=new Set($);for(let Z of J){let W=Z.trim();if(!W)continue;Q.add(W)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function pX($){let J=[],Q=[];for(let Z of $){let W=oZ(Z);if(W){J=m4(J,W.details.readFiles),Q=m4(Q,W.details.modifiedFiles);continue}if(!Array.isArray(Z.content))continue;for(let j of Z.content){if(j.type==="file"){J=m4(J,[j.path]);continue}if(j.type!=="tool_use")continue;let f=v4(j.input);if(j.name==="read_files"){J=m4(J,f);continue}if(j.name==="editor"||j.name==="apply_patch")Q=m4(Q,f)}}return{readFiles:J,modifiedFiles:Q}}function sR($){let J=$.readFiles.length>0?$.readFiles.map((Z)=>`- ${Z}`).join(`
328
+ `):"- none",Q=$.modifiedFiles.length>0?$.modifiedFiles.map((Z)=>`- ${Z}`).join(`
329
329
  `):"- none";return`## Files
330
330
  Read:
331
- ${f}
331
+ ${J}
332
332
  Modified:
333
- ${J}`}function MX($,f){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
333
+ ${Q}`}function rX($,J){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
334
334
 
335
- ${FD(f)}`.trim()}function TX($){let f=[`Summarize this session for continuation. Be concise and factual.
335
+ ${sR(J)}`.trim()}function iX($){let J=[`Summarize this session for continuation. Be concise and factual.
336
336
 
337
337
  ## Goal
338
338
  One sentence: what is being built or fixed.
@@ -350,15 +350,23 @@ Immediate next steps.
350
350
 
351
351
  ## Files
352
352
  Read: ${$.fileOps.readFiles.join(", ")||"none"}
353
- Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.trim())f.push(`Previous summary:
354
- ${$.previousSummary.trim()}`);return f.push(`Conversation:
355
- ${$.conversationText||"(empty)"}`),f.join(`
353
+ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.trim())J.push(`Previous summary:
354
+ ${$.previousSummary.trim()}`);return J.push(`Conversation:
355
+ ${$.conversationText||"(empty)"}`),J.join(`
356
356
 
357
- `)}function NX($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:W,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??VX,thinking:!1}};if(!f)return J($.activeProviderConfig);let Q=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...Q??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.headers??Q?.headers,knownModels:f.knownModels??Q?.knownModels,maxOutputTokens:f.maxOutputTokens??VX})}function qX($){return{role:"user",content:`Context summary:
357
+ `)}function nX($){let J=$.summarizer,Q=(W)=>{if(W.providerId==="openai-codex"){let{maxOutputTokens:j,...f}=W;return{...f,thinking:!1}}return{...W,maxOutputTokens:W.maxOutputTokens??EX,thinking:!1}};if(!J)return Q($.activeProviderConfig);let Z=J.providerConfig?.providerId===J.providerId?J.providerConfig:void 0;return Q({...Z??{},providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey??Z?.apiKey,baseUrl:J.baseUrl??Z?.baseUrl,headers:J.headers??Z?.headers,knownModels:J.knownModels??Z?.knownModels,maxOutputTokens:J.maxOutputTokens??EX})}function aX($){return{role:"user",content:`Context summary:
358
358
 
359
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function RD($){let f=await PD($.providerConfig),J="";for await(let Q of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function DD($){try{return JSON.stringify($).length}catch{return String($).length}}async function wX($){let f=$.context.messages;if(f.length<2)return;let J=zX(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let Q=f.slice(0,J),Z=_X(Q),W=Z>=0?gQ(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let X=OX(Q),Y=RX(j),A=TX({previousSummary:W,conversationText:Y,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:W?.length??0,conversationTextChars:Y.length,summaryRequestChars:A.length,summaryRequestEstimatedTokens:bQ(A.length),newMessagesJsonChars:DD(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let V=await RD({providerConfig:NX({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:A,logger:$.logger});if(!V.trim())return;let H=MX(V,X),B=f.reduce((R,P)=>R+$.estimateMessageTokens(P),0),K=[qX({summary:H,fileOps:X,tokensBefore:B}),...f.slice(J)],G=K.reduce((R,P)=>R+$.estimateMessageTokens(P),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function SX($){if(k8($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:xQ(J.content)}:J)}}function x8($,f){return $.reduce((J,Q)=>J+f(Q),0)}function CX($,f){let J=Math.max(1,f),Q=Math.max(16,J*4);if(typeof $.content==="string"){let j=X$($.content,Q).trim();return{...$,content:j||"..."}}let Z=Q,W=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let X=X$(j.text,Z).trim();return Z-=X.length,{...j,text:X||"..."}});return{...$,content:W}}function UD($,f){let J=UX($),Q=O6($),Z=LX($),W=[];for(let j=0;j<$.length;j+=1){let X=SX($[j]);if(!X)continue;W.push({index:j,message:X,estimatedTokens:f(X),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function yX($,f,J,Q){let Z=$[f];Z.message=J,Z.estimatedTokens=Q(J)}function LD($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function _D($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function EX($){return new Set([...LD($.message),..._D($.message)])}function zD($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let Q of EX($[J])){let Z=f.get(Q);if(Z)Z.add(J);else f.set(Q,new Set([J]))}return f}function OD($,f){let J=zD($),Q=new Set,Z=[f];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of EX($[W]))for(let X of J.get(j)??[])if(!Q.has(X))Z.push(X)}return Q}function M6($,f,J,Q){let Z=x8($.map((W)=>W.message),Q);for(let W=0;W<$.length&&Z>J;){if(!f($[W])){W+=1;continue}let j=OD($,W);Z-=Array.from(j).reduce((X,Y)=>X+$[Y].estimatedTokens,0);for(let X of Array.from(j).sort((Y,A)=>A-Y))$.splice(X,1)}}function MD($,f,J){let Q=x8($.map((W)=>W.message),J);if(Q<=f)return;for(let W=$.length-1;W>=0&&Q>f;W-=1){let j=$[W];if(j.isFirstUser)continue;let X=Math.max(FX,j.estimatedTokens-(Q-f));if(X>=j.estimatedTokens)continue;yX($,W,CX(j.message,X),J),Q=x8($.map((Y)=>Y.message),J)}if(Q<=f)return;let Z=$.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,$[Z].estimatedTokens-(Q-f));yX($,Z,CX($[Z].message,W),J)}}function TD($,f){return JSON.stringify($)!==JSON.stringify(f)}function ND($){let f=O6($);if(f<0||f===0&&!I8($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function hX($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:Q}=ND($.context.messages);if(J.length===0)return;let Z=UD(J,$.estimateMessageTokens);if(Z.length===0)return;M6(Z,(Y)=>Y.message.role==="assistant"&&!Y.isLastAssistant,f,$.estimateMessageTokens),M6(Z,(Y)=>Y.message.role==="user"&&!Y.isFirstUser&&!Y.isLastUser,f,$.estimateMessageTokens),M6(Z,(Y)=>Y.message.role==="assistant"&&Y.isLastAssistant,f,$.estimateMessageTokens),M6(Z,(Y)=>Y.message.role==="user"&&Y.isLastUser&&!Y.isFirstUser,f,$.estimateMessageTokens),MD(Z,f,$.estimateMessageTokens);let W=[...Z.map((Y)=>Y.message),...Q];if(!TD($.context.messages,W))return;let j=x8([...J.map((Y)=>SX(Y)??Y),...Q],$.estimateMessageTokens),X=x8(W,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:W.length,messagesRemoved:$.context.messages.length-W.length,tokensBefore:j,tokensAfter:X,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:W}}function bX($){try{return JSON.stringify($).length}catch{return String($).length}}function qD($){let f=0,J=0,Q=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=bX(W.content);f+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var wD={basic:({context:$,estimateMessageTokens:f,logger:J})=>hX({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>wX({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??IQ,$.triggerTokens):J?.preserveRecentTokens??IQ,estimateMessageTokens:Z,logger:W})};function CD($){if(typeof $.config.reserveTokens==="number"){let Q=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-Q);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min($.maxInputTokens-KX,$.maxInputTokens*kQ));return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}let f=$.config.thresholdRatio??kQ,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function yD($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),Q=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}function g8($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=DX(),W=J?.strategy??"basic",j=wD[W],X=f.mode??"auto",Y=J?.compact?"custom":W;return async(A)=>{let V=A.apiMessages.reduce((U,w)=>U+Z(w),0),H=J?.maxInputTokens??A.model.info?.maxInputTokens??A.model.info?.contextWindow??BX;if(typeof H!=="number"||!Number.isFinite(H)||H<=0)return;let B=CD({inputTokens:V,maxInputTokens:H,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:W,iteration:A.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:V,maxInputTokens:H,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:A.messages.length,apiMessageCount:A.apiMessages.length,apiMessagesJsonChars:bX(A.apiMessages),...qD(A.apiMessages)}),X==="auto"&&!B.shouldCompact)return;let K=X==="manual"?yD({inputTokens:V,maxInputTokens:H,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,G={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId,iteration:A.iteration,messages:A.messages,model:A.model,maxInputTokens:H,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:H>0?V/H:0},R=X==="manual"?"manual_compaction":"auto_compaction";A.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:A.iteration,triggerTokens:K.triggerTokens,maxInputTokens:H});let P=A.messages.length,F=Date.now(),D=J?.compact?await J.compact(G):await j({context:G,providerConfig:{...Q,abortSignal:A.abortSignal},compaction:J,mode:X,estimateMessageTokens:Z,logger:$.logger}),z=Date.now()-F,T=$.sessionId??A.conversationId,L={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId??void 0};if(D?.messages){let U=D.messages.reduce((w,h)=>w+Z(h),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:H,inputTokens:V,afterTokens:U,tokensSaved:V-U,utilizationBefore:`${(V/H*100).toFixed(1)}%`,utilizationAfter:`${(U/H*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:P,messagesAfter:D.messages.length,messagesRemoved:P-D.messages.length}),lJ($.telemetry,{ulid:T,strategy:Y,mode:X,messagesBefore:P,messagesAfter:D.messages.length,messagesRemoved:P-D.messages.length,tokensBefore:V,tokensAfter:U,tokensSaved:V-U,triggerTokens:K.triggerTokens,maxInputTokens:H,thresholdRatio:K.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...L})}else pJ($.telemetry,{ulid:T,strategy:Y,mode:X,reason:"no_result",tokensBefore:V,triggerTokens:K.triggerTokens,maxInputTokens:H,thresholdRatio:K.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...L});return D}}var tY={};q(tY,{zodToJsonSchema:()=>Q_,validateWithZod:()=>J_,resolveToolRoutingConfig:()=>j2,resolveToolPresetName:()=>c1,resolveCoreSelectedToolIds:()=>x6,getCoreHeadlessToolNames:()=>J4,getCoreDefaultEnabledToolIds:()=>I6,getCoreBuiltinToolCatalog:()=>ff,getCoreAcpToolNames:()=>g6,createWindowsShellTool:()=>iQ,createWebFetchTool:()=>nQ,createWebFetchExecutor:()=>$4,createToolPoliciesWithPreset:()=>C6,createSubmitAndExitTool:()=>oQ,createSkillsTool:()=>n$,createSearchTool:()=>pQ,createSearchExecutor:()=>e8,createReadFilesTool:()=>lQ,createFileReadExecutor:()=>o8,createEditorTool:()=>tQ,createEditorExecutor:()=>t8,createDefaultToolsWithPreset:()=>y6,createDefaultTools:()=>V$,createDefaultExecutors:()=>Z2,createBuiltinTools:()=>Jf,createBashTool:()=>rQ,createBashExecutor:()=>a8,createAskQuestionTool:()=>sQ,createApplyPatchTool:()=>aQ,createApplyPatchExecutor:()=>n8,WebFetchRequestSchema:()=>cQ,ToolPresets:()=>v0,TEAM_TOOL_NAMES:()=>Y2,SubmitInputSchema:()=>i8,SkillsInputSchema:()=>p8,SearchCodebaseInputSchema:()=>c8,RunCommandsInputSchema:()=>f2,ReadFilesInputSchema:()=>v8,ReadFileRequestSchema:()=>x1,FetchWebContentInputSchema:()=>u8,EditFileInputSchema:()=>d8,DefaultToolNames:()=>H0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>W2,AskQuestionInputSchema:()=>r8,ApplyPatchInputSchema:()=>l8,ALL_DEFAULT_TOOL_NAMES:()=>o1});import{validateWithZod as J_,zodToJsonSchema as Q_}from"@cline/shared";_0();import{createTool as g1,validateWithZod as m1,zodToJsonSchema as H1}from"@cline/shared";var IX="__clineInternalTelemetry";function xX($){let f=$?.__clineInternalTelemetry;return f&&typeof f==="object"&&"capture"in f&&typeof f.capture==="function"?f:void 0}import{validateWithZod as SD}from"@cline/shared";import{z as _}from"zod";var Y$=6000,m8=_.string().describe("The absolute file path of a text file to read content from"),gX=_.object({start_line:_.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:_.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),x1=_.object({path:m8,start_line:gX.shape.start_line,end_line:gX.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),v8=_.object({files:_.array(x1).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),mX=_.union([v8,x1,_.array(x1),_.array(_.string()),_.string(),_.object({files:_.array(_.union([m8,x1]))}),_.object({files:x1}),_.object({files:m8}),_.object({file_paths:_.array(m8)}),_.object({file_paths:_.string()}),_.object({paths:_.array(_.union([m8,x1]))}),_.object({paths:x1}),_.object({paths:_.string()})]),c8=_.object({queries:_.array(_.string()).describe("Array of regex search queries to execute")}),vX=_.union([c8,_.array(_.string()),_.string(),_.object({queries:_.string()})]),r$=_.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${Y$*2} characters) to avoid timeouts.`),f2=_.object({commands:_.array(r$).describe("Array of shell commands to execute")}),cX=_.union([f2,_.object({commands:r$}),_.object({command:r$}),_.object({cmd:r$}),_.array(_.string()),_.string()]),mQ=_.object({command:_.string().min(1).describe("The executable to run directly without shell parsing."),args:_.array(_.string()).optional().describe("Optional argv list passed directly to the executable.")}),uX=_.union([r$,mQ]),vQ=_.object({commands:_.array(uX).describe("Array of commands to execute. Prefer structured { command, args } entries for portability; plain strings are still supported and are interpreted by the active shell.")}),dX=_.union([f2,vQ,_.object({commands:uX}),_.array(mQ),mQ,_.object({command:r$}),_.object({cmd:r$}),_.array(_.string()),_.string()]),cQ=_.object({url:_.string().describe("The URL to fetch"),prompt:_.string().min(2).describe("Analysis prompt for the fetched content")}),u8=_.object({requests:_.array(cQ).describe("Array of the URLs for the web fetch requests")}),d8=_.object({path:_.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:_.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${Y$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:_.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${Y$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:_.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."),l8=_.object({input:_.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),lX=_.union([l8,_.string()]),p8=_.object({skill:_.string().min(1).describe("Name of the skill to execute."),args:_.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),r8=_.object({question:_.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:_.array(_.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),i8=_.object({summary:_.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:_.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
359
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function tR($){let J=await oR($.providerConfig),Q="";for await(let Z of J.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Z.type==="text"){Q+=Z.text;continue}if(Z.type==="done"&&!Z.success&&Z.error)throw Error(Z.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Q.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Q.trim()}function eR($){try{return JSON.stringify($).length}catch{return String($).length}}async function sX($){let J=$.context.messages;if(J.length<2)return;let Q=lX(J,$.preserveRecentTokens,$.estimateMessageTokens);if(Q<=0||Q>=J.length)return;let Z=J.slice(0,Q),W=dX(Z),j=W>=0?oZ(Z[W])?.summary:void 0,f=W>=0?Z.slice(W+1):Z;if(f.length===0)return;let X=pX(Z),Y=mX(f),V=iX({previousSummary:j,conversationText:Y,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Z.length,newMessagesToFold:f.length,preservedMessages:J.length-Q,previousSummaryChars:j?.length??0,conversationTextChars:Y.length,summaryRequestChars:V.length,summaryRequestEstimatedTokens:iZ(V.length),newMessagesJsonChars:eR(f),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let H=await tR({providerConfig:nX({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:V,logger:$.logger});if(!H.trim())return;let B=rX(H,X),A=J.reduce((R,D)=>R+$.estimateMessageTokens(D),0),K=[aX({summary:B,fileOps:X,tokensBefore:A}),...J.slice(Q)],G=K.reduce((R,D)=>R+$.estimateMessageTokens(D),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:J.length,messagesAfter:K.length,messagesSummarized:Q,messagesPreserved:J.length-Q,tokensBefore:A,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function eX($){if(c4($))return;if(typeof $.content==="string"){let Q=$.content.trim();return Q?{...$,content:Q}:void 0}let J=$.content.filter((Q)=>Q.type!=="text"||Q.text.trim());if(J.length===0)return;return{...$,content:J.map((Q)=>Q.type==="text"?{...Q,text:Q.text.trim()}:Q.type==="tool_result"?{...Q,content:sZ(Q.content)}:Q)}}function d4($,J){return $.reduce((Q,Z)=>Q+J(Z),0)}function oX($,J){let Q=Math.max(1,J),Z=Math.max(16,Q*4);if(typeof $.content==="string"){let f=Y$($.content,Z).trim();return{...$,content:f||"..."}}let W=Z,j=$.content.map((f)=>{if(f.type!=="text"||W<=0)return f;let X=Y$(f.text,W).trim();return W-=X.length,{...f,text:X||"..."}});return{...$,content:j}}function $z($,J){let Q=cX($),Z=C5($),W=uX($),j=[];for(let f=0;f<$.length;f+=1){let X=eX($[f]);if(!X)continue;j.push({index:f,message:X,estimatedTokens:J(X),isFirstUser:f===Q,isLastUser:f===Z,isLastAssistant:f===W})}return j}function tX($,J,Q,Z){let W=$[J];W.message=Q,W.estimatedTokens=Z(Q)}function Jz($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_use")J.add(Q.id);return J}function Qz($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_result")J.add(Q.tool_use_id);return J}function $Y($){return new Set([...Jz($.message),...Qz($.message)])}function Zz($){let J=new Map;for(let Q=0;Q<$.length;Q+=1)for(let Z of $Y($[Q])){let W=J.get(Z);if(W)W.add(Q);else J.set(Z,new Set([Q]))}return J}function Wz($,J){let Q=Zz($),Z=new Set,W=[J];while(W.length>0){let j=W.shift();if(j===void 0||Z.has(j))continue;Z.add(j);for(let f of $Y($[j]))for(let X of Q.get(f)??[])if(!Z.has(X))W.push(X)}return Z}function y5($,J,Q,Z){let W=d4($.map((j)=>j.message),Z);for(let j=0;j<$.length&&W>Q;){if(!J($[j])){j+=1;continue}let f=Wz($,j);W-=Array.from(f).reduce((X,Y)=>X+$[Y].estimatedTokens,0);for(let X of Array.from(f).sort((Y,V)=>V-Y))$.splice(X,1)}}function jz($,J,Q){let Z=d4($.map((j)=>j.message),Q);if(Z<=J)return;for(let j=$.length-1;j>=0&&Z>J;j-=1){let f=$[j];if(f.isFirstUser)continue;let X=Math.max(xX,f.estimatedTokens-(Z-J));if(X>=f.estimatedTokens)continue;tX($,j,oX(f.message,X),Q),Z=d4($.map((Y)=>Y.message),Q)}if(Z<=J)return;let W=$.findIndex((j)=>j.isFirstUser);if(W>=0){let j=Math.max(1,$[W].estimatedTokens-(Z-J));tX($,W,oX($[W].message,j),Q)}}function fz($,J){return JSON.stringify($)!==JSON.stringify(J)}function Xz($){let J=C5($);if(J<0||J===0&&!u4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,J),protectedTail:$.slice(J)}}function JY($){let J=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:Q,protectedTail:Z}=Xz($.context.messages);if(Q.length===0)return;let W=$z(Q,$.estimateMessageTokens);if(W.length===0)return;y5(W,(Y)=>Y.message.role==="assistant"&&!Y.isLastAssistant,J,$.estimateMessageTokens),y5(W,(Y)=>Y.message.role==="user"&&!Y.isFirstUser&&!Y.isLastUser,J,$.estimateMessageTokens),y5(W,(Y)=>Y.message.role==="assistant"&&Y.isLastAssistant,J,$.estimateMessageTokens),y5(W,(Y)=>Y.message.role==="user"&&Y.isLastUser&&!Y.isFirstUser,J,$.estimateMessageTokens),jz(W,J,$.estimateMessageTokens);let j=[...W.map((Y)=>Y.message),...Z];if(!fz($.context.messages,j))return;let f=d4([...Q.map((Y)=>eX(Y)??Y),...Z],$.estimateMessageTokens),X=d4(j,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:j.length,messagesRemoved:$.context.messages.length-j.length,tokensBefore:f,tokensAfter:X,targetTokens:J,maxInputTokens:$.context.maxInputTokens}),{messages:j}}function QY($){try{return JSON.stringify($).length}catch{return String($).length}}function Yz($){let J=0,Q=0,Z=0;for(let W of $){if(!Array.isArray(W.content))continue;for(let j of W.content){if(j.type!=="tool_result")continue;let f=QY(j.content);J+=1,Q+=f,Z=Math.max(Z,f)}}return{toolResultCount:J,toolResultSerializedChars:Q,maxToolResultSerializedChars:Z}}var Vz={basic:({context:$,estimateMessageTokens:J,logger:Q})=>JY({context:$,estimateMessageTokens:J,logger:Q}),agentic:({context:$,providerConfig:J,compaction:Q,mode:Z,estimateMessageTokens:W,logger:j})=>sX({context:$,providerConfig:J,summarizer:Q?.summarizer,preserveRecentTokens:Z==="manual"?Math.min(Q?.preserveRecentTokens??aZ,$.triggerTokens):Q?.preserveRecentTokens??aZ,estimateMessageTokens:W,logger:j})};function Hz($){if(typeof $.config.reserveTokens==="number"){let Z=Math.max(0,$.config.reserveTokens),W=Math.max(0,$.maxInputTokens-Z);return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Z=Math.max(0,Math.min($.maxInputTokens-kX,$.maxInputTokens*nZ));return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}let J=$.config.thresholdRatio??nZ,Q=$.maxInputTokens*J;return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:J}}function Bz($){let J=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Q=Math.min(0.95,Math.max(0.05,J)),Z=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*Q)));return{triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}function l4($,J={}){let Q=$.compaction;if(Q?.enabled!==!0)return;let Z=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},W=vX(),j=Q?.strategy??"basic",f=Vz[j],X=J.mode??"auto",Y=Q?.compact?"custom":j;return async(V)=>{let H=V.apiMessages.reduce((z,P)=>z+W(P),0),B=Q?.maxInputTokens??V.model.info?.maxInputTokens??V.model.info?.contextWindow??hX;if(typeof B!=="number"||!Number.isFinite(B)||B<=0)return;let A=Hz({inputTokens:H,maxInputTokens:B,config:{reserveTokens:Q?.reserveTokens,thresholdRatio:Q?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:j,iteration:V.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:H,maxInputTokens:B,triggerTokens:A.triggerTokens,thresholdRatio:A.thresholdRatio,shouldCompact:A.shouldCompact,messageCount:V.messages.length,apiMessageCount:V.apiMessages.length,apiMessagesJsonChars:QY(V.apiMessages),...Yz(V.apiMessages)}),X==="auto"&&!A.shouldCompact)return;let K=X==="manual"?Bz({inputTokens:H,maxInputTokens:B,autoTriggerTokens:A.triggerTokens,manualTargetRatio:J.manualTargetRatio}):A,G={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId,iteration:V.iteration,messages:V.messages,model:V.model,maxInputTokens:B,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:B>0?H/B:0},R=X==="manual"?"manual_compaction":"auto_compaction";V.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:V.iteration,triggerTokens:K.triggerTokens,maxInputTokens:B});let D=V.messages.length,U=Date.now(),F=Q?.compact?await Q.compact(G):await f({context:G,providerConfig:{...Z,abortSignal:V.abortSignal},compaction:Q,mode:X,estimateMessageTokens:W,logger:$.logger}),O=Date.now()-U,T=$.sessionId??V.conversationId,L={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId??void 0};if(F?.messages){let z=F.messages.reduce((P,S)=>P+W(S),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:B,inputTokens:H,afterTokens:z,tokensSaved:H-z,utilizationBefore:`${(H/B*100).toFixed(1)}%`,utilizationAfter:`${(z/B*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length}),tJ($.telemetry,{ulid:T,strategy:Y,mode:X,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length,tokensBefore:H,tokensAfter:z,tokensSaved:H-z,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L})}else eJ($.telemetry,{ulid:T,strategy:Y,mode:X,reason:"no_result",tokensBefore:H,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L});return F}}var qV={};w(qV,{zodToJsonSchema:()=>t_,validateWithZod:()=>o_,resolveToolRoutingConfig:()=>H8,resolveToolPresetName:()=>u1,resolveCoreSelectedToolIds:()=>r5,getCoreHeadlessToolNames:()=>H6,getCoreDefaultEnabledToolIds:()=>p5,getCoreBuiltinToolCatalog:()=>J2,getCoreAcpToolNames:()=>i5,createWindowsShellTool:()=>X7,createWebFetchTool:()=>Y7,createWebFetchExecutor:()=>X6,createToolPoliciesWithPreset:()=>g5,createSubmitAndExitTool:()=>A7,createSkillsTool:()=>n$,createSearchTool:()=>j7,createSearchExecutor:()=>f6,createReadFilesTool:()=>W7,createFileReadExecutor:()=>j6,createEditorTool:()=>H7,createEditorExecutor:()=>W6,createDefaultToolsWithPreset:()=>m5,createDefaultTools:()=>B$,createDefaultExecutors:()=>Y8,createBuiltinTools:()=>Q2,createBashTool:()=>f7,createBashExecutor:()=>Q6,createAskQuestionTool:()=>B7,createApplyPatchTool:()=>V7,createApplyPatchExecutor:()=>Z6,WebFetchRequestSchema:()=>$7,ToolPresets:()=>c0,TEAM_TOOL_NAMES:()=>A8,SubmitInputSchema:()=>e4,SkillsInputSchema:()=>o4,SearchCodebaseInputSchema:()=>i4,RunCommandsInputSchema:()=>Z8,ReadFilesInputSchema:()=>r4,ReadFileRequestSchema:()=>g1,FetchWebContentInputSchema:()=>n4,EditFileInputSchema:()=>a4,DefaultToolNames:()=>K0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>V8,AskQuestionInputSchema:()=>t4,ApplyPatchInputSchema:()=>s4,ALL_DEFAULT_TOOL_NAMES:()=>e1});import{validateWithZod as o_,zodToJsonSchema as t_}from"@cline/shared";O0();import{createTool as m1,validateWithZod as v1,zodToJsonSchema as A1}from"@cline/shared";var WY="__clineInternalTelemetry";function jY($){let J=$?.__clineInternalTelemetry;return J&&typeof J==="object"&&"capture"in J&&typeof J.capture==="function"?J:void 0}import{spawn as DY}from"node:child_process";import{StringDecoder as Gz}from"node:string_decoder";import{getDefaultShell as Fz,getShellArgs as Dz}from"@cline/shared";import{validateWithZod as Az}from"@cline/shared";import{z as _}from"zod";var V$=6000,p4=_.string().describe("The absolute file path of a text file to read content from"),fY=_.object({start_line:_.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:_.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),g1=_.object({path:p4,start_line:fY.shape.start_line,end_line:fY.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),r4=_.object({files:_.array(g1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),XY=_.union([r4,g1,_.array(g1),_.array(_.string()),_.string(),_.object({files:_.array(_.union([p4,g1]))}),_.object({files:g1}),_.object({files:p4}),_.object({file_paths:_.array(p4)}),_.object({file_paths:_.string()}),_.object({paths:_.array(_.union([p4,g1]))}),_.object({paths:g1}),_.object({paths:_.string()})]),i4=_.object({queries:_.array(_.string()).describe("Array of regex search queries to execute")}),YY=_.union([i4,_.array(_.string()),_.string(),_.object({queries:_.string()})]),r$=_.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${V$*2} characters) to avoid timeouts.`),Z8=_.object({commands:_.array(r$).describe("Array of shell commands to execute")}),VY=_.union([Z8,_.object({commands:r$}),_.object({command:r$}),_.object({cmd:r$}),_.array(_.string()),_.string()]),tZ=_.object({command:_.string().min(1).describe("The executable to run directly without shell parsing."),args:_.array(_.string()).optional().describe("Optional argv list passed directly to the executable.")}),HY=_.union([r$,tZ]),eZ=_.object({commands:_.array(HY).describe("Array of commands to execute. Prefer structured { command, args } entries for portability; plain strings are still supported and are interpreted by the active shell.")}),BY=_.union([Z8,eZ,_.object({commands:HY}),_.array(tZ),tZ,_.object({command:r$}),_.object({cmd:r$}),_.array(_.string()),_.string()]),$7=_.object({url:_.string().describe("The URL to fetch"),prompt:_.string().min(2).describe("Analysis prompt for the fetched content")}),n4=_.object({requests:_.array($7).describe("Array of the URLs for the web fetch requests")}),a4=_.object({path:_.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:_.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${V$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:_.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${V$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:_.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),s4=_.object({input:_.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),AY=_.union([s4,_.string()]),o4=_.object({skill:_.string().min(1).describe("Name of the skill to execute."),args:_.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),t4=_.object({question:_.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:_.array(_.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),e4=_.object({summary:_.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:_.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
360
360
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
361
- 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 A$($){if($ instanceof Error)return $.message;return String($)}function pX($){if(typeof $.old_text==="string"&&$.old_text.length>Y$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${Y$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>Y$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${Y$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class i$ extends Error{timeoutMs;constructor($,f){super($);this.name="TimeoutError",this.timeoutMs=f}}function V1($,f,J){return Promise.race([$,new Promise((Q,Z)=>{setTimeout(()=>Z(new i$(J,f)),f)})])}function T6($){let{path:f,start_line:J,end_line:Q}=$;if(J==null&&Q==null)return f;return`${f}:${J??1}-${Q??"EOF"}`}function rX($){let{start_line:f,end_line:J}=$;if(f==null||J==null||f<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${f}, end_line: ${J})`}function iX($){let f=SD(dX,$);if(typeof f==="string")return[f];if(Array.isArray(f))return f;if("commands"in f)return Array.isArray(f.commands)?f.commands:[f.commands];if("command"in f)return"args"in f?[f]:[f.command];if("cmd"in f)return[f.cmd];return[f]}function ED($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${J.join(" ")}`}var uQ=200;function dQ($){let f=ED($);if(f.length<=uQ)return f;let J=f.length-uQ;return`${f.slice(0,uQ)} ... [command truncated: ${J} more chars; full command is in the tool call input]`}function nX($,f){let J=$.metadata?.[f];return typeof J==="string"?J:void 0}function aX($,f){r3(xX($.metadata),{tool_name:"run_commands",effective_timeout_ms:f.effectiveTimeoutMs,timeout_source:f.timeoutSource,command_count:f.commandCount,duration_ms:f.durationMs,ulid:$.sessionId,mode:nX($,"mode"),source:nX($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function lQ($,f={}){let J=f.fileReadTimeoutMs??1e4;return g1({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. ",inputSchema:H1(v8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Q,Z)=>{let W=m1(mX,Q),j;if(typeof W==="string")j=[{path:W}];else if(Array.isArray(W))j=W.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in W)j=(Array.isArray(W.files)?W.files:[W.files]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("file_paths"in W)j=(Array.isArray(W.file_paths)?W.file_paths:[W.file_paths]).map((Y)=>({path:Y}));else if("paths"in W)j=(Array.isArray(W.paths)?W.paths:[W.paths]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else j=[W];return Promise.all(j.map(async(X)=>{let Y=rX(X);if(Y)return{query:T6(X),result:"",error:`Invalid file range: ${Y}`,success:!1};try{let A=await V1($(X,Z),J,`File read timed out after ${J}ms`);return{query:T6(X),result:A,success:!0}}catch(A){let V=A$(A);return{query:T6(X),result:"",error:`Error reading file: ${V}`,success:!1}}}))}})}function pQ($,f={}){let J=f.searchTimeoutMs??30000,Q=f.cwd??process.cwd();return g1({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:H1(c8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=m1(vX,Z),X=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(X.map(async(Y)=>{try{let A=await V1($(Y,Q,W),J,`Search timed out after ${J}ms`),V=A.length>0&&!A.includes("No results found");return{query:Y,result:A,success:V}}catch(A){let V=A$(A);return{query:Y,result:"",error:`Search failed: ${V}`,success:!1}}}))}})}function rQ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return g1({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.",inputSchema:H1(f2),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=m1(cX,W),Y;if(typeof X==="string")Y=[X];else if(Array.isArray(X))Y=X;else if("commands"in X)Y=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)Y=[X.command];else Y=[X.cmd];return Promise.all(Y.map(async(A)=>{let V=Date.now(),H=dQ(A);try{let B=await V1($(A,Z,j),J,`Command timed out after ${J}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof i$)aX(j,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Q,commandCount:Y.length,durationMs:Date.now()-V});let K=A$(B);return{query:H,result:"",error:`Command failed: ${K}`,success:!1}}}))}})}function iQ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return g1({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:H1(vQ),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=iX(W);return Promise.all(X.map(async(Y)=>{let A=Date.now(),V=dQ(Y);try{let H=await V1($(Y,Z,j),J,`Command timed out after ${J}ms`);return{query:V,result:H,success:!0}}catch(H){if(H instanceof i$)aX(j,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:Q,commandCount:X.length,durationMs:Date.now()-A});let B=A$(H);return{query:V,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function nQ($,f={}){let J=f.webFetchTimeoutMs??30000;return g1({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:H1(u8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(Q,Z)=>{let W=m1(u8,Q);return Promise.all(W.requests.map(async(j)=>{try{let X=await V1($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:X,success:!0}}catch(X){let Y=A$(X);return{query:j.url,result:"",error:`Error fetching web content: ${Y}`,success:!1}}}))}})}var hD=`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:
361
+ 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 H$($){if($ instanceof Error)return $.message;return String($)}function KY($){if(typeof $.old_text==="string"&&$.old_text.length>V$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${V$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>V$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${V$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class i$ extends Error{timeoutMs;constructor($,J){super($);this.name="TimeoutError",this.timeoutMs=J}}function B1($,J,Q){return Promise.race([$,new Promise((Z,W)=>{setTimeout(()=>W(new i$(Q,J)),J)})])}function E5($){let{path:J,start_line:Q,end_line:Z}=$;if(Q==null&&Z==null)return J;return`${J}:${Q??1}-${Z??"EOF"}`}function GY($){let{start_line:J,end_line:Q}=$;if(J==null||Q==null||J<=Q)return null;return`start_line must be less than or equal to end_line (received start_line: ${J}, end_line: ${Q})`}function FY($){let J=Az(BY,$);if(typeof J==="string")return[J];if(Array.isArray(J))return J;if("commands"in J)return Array.isArray(J.commands)?J.commands:[J.commands];if("command"in J)return"args"in J?[J]:[J.command];if("cmd"in J)return[J.cmd];return[J]}function Kz($){if(typeof $==="string")return $;let J=$.args??[];if(J.length===0)return $.command;let Q=J.map((Z)=>/[\s"]/u.test(Z)?JSON.stringify(Z):Z);return`${$.command} ${Q.join(" ")}`}var J7=200;function Q7($){let J=Kz($);if(J.length<=J7)return J;let Q=J.length-J7;return`${J.slice(0,J7)} ... [command truncated: ${Q} more chars; full command is in the tool call input]`}var $6=48000,W8=2000,Z7=2000,b5=48000,j8=48000;class J6 extends Error{exitCode;output;constructor($,J){super(`Command exited with code ${$}`);this.exitCode=$;this.output=J;this.name="CommandExitError"}}function UY($){let J=Math.ceil($/2),Q=Math.max(1,$-J),Z=new Gz("utf8"),W="",j="",f=0,X=(Y)=>{if(!Y)return;f+=Y.length;let V=J-W.length;if(V>0){W+=Y.slice(0,V),j=(j+Y.slice(V)).slice(-Q);return}j=(j+Y).slice(-Q)};return{append(Y){X(Z.write(Y))},snapshot(){return X(Z.end()),{text:W+j,totalChars:f,dropped:f>W.length+j.length}}}}function RY($,J,Q){let Z=Math.ceil(J/2),W=Math.max(1,J-Z);return`${$.slice(0,Z)}
362
+ [... output truncated: ${Q} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
363
+ `+$.slice(-W)}function Uz($,J,Q,Z,W){return new Promise((j,f)=>{let X=process.platform==="win32",Y=DY($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X,windowsHide:!0}),V=Y.pid,H=UY(Z),B=UY(Z),A=!1,K=!1,G=(T)=>{if(K)return;K=!0,T()},R=()=>{if(!V)return;if(X){DY("taskkill",["/pid",String(V),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-V,"SIGKILL")}catch{Y.kill("SIGKILL")}},D=(T)=>{A=!0,R(),G(()=>f(T))},U=setTimeout(()=>D(new i$(`Command timed out after ${Q}ms`,Q)),Q),F=()=>D(Error("Command was aborted"));if(J.signal)J.signal.addEventListener("abort",F);let O=()=>{clearTimeout(U),J.signal?.removeEventListener("abort",F)};Y.stdout?.on("data",(T)=>{H.append(T)}),Y.stderr?.on("data",(T)=>{B.append(T)}),Y.on("close",(T)=>{if(O(),A)return;let L=H.snapshot(),z=B.snapshot();if(T!==0){let P=T??1,S=W?L.text+(z.text?`
364
+ [stderr]
365
+ ${z.text}`:""):L.text,b=L.dropped||W&&z.dropped,u=W?L.totalChars+z.totalChars:L.totalChars;if(b||S.length>Z)S=RY(S,Z,u);let o=S.length>0?`[Command exited with code ${P}]
366
+ ${S}`:`[Command exited with code ${P}]`;G(()=>f(new J6(P,o)))}else{let P=W?L.text+(z.text?`
367
+ [stderr]
368
+ ${z.text}`:""):L.text;if(L.dropped||W&&z.dropped||P.length>Z){let b=W?L.totalChars+z.totalChars:L.totalChars;P=RY(P,Z,b)}G(()=>j(P))}}),Y.on("error",(T)=>{O(),G(()=>f(Error(`Failed to execute command: ${T.message}`)))})})}function Q6($={}){let{shell:J=Fz(process.platform),timeoutMs:Q=30000,env:Z={},combineOutput:W=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??$6;return(f,X,Y)=>{let V=typeof f!=="string";return Uz({executable:V?f.command:J,args:V?f.args??[]:Dz(J,f),cwd:X,env:Z},Y,Q,j,W)}}function zY($,J){let Q=$.metadata?.[J];return typeof Q==="string"?Q:void 0}function LY($,J){Af(jY($.metadata),{tool_name:"run_commands",effective_timeout_ms:J.effectiveTimeoutMs,timeout_source:J.timeoutSource,command_count:J.commandCount,duration_ms:J.durationMs,ulid:$.sessionId,mode:zY($,"mode"),source:zY($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function Rz($){let J=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return J?.[1]??J?.[2]??J?.[3]}function zz($){let J=[];for(let Q=0;Q<$.length;Q+=1){let Z=$[Q],W=Rz(Z);if(!W){J.push(Z);continue}let j=$.findIndex((X,Y)=>Y>Q&&X.trim()===W);if(j===-1){J.push(Z);continue}let f=[Z];while(Q<j){Q+=1;let X=$[Q];f.push(X)}J.push(f.join(`
369
+ `))}return J}function W7($,J={}){let Q=J.fileReadTimeoutMs??1e4;return m1({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${W8} lines / ~${Math.round(b5/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:A1(r4),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=v1(XY,Z),f;if(typeof j==="string")f=[{path:j}];else if(Array.isArray(j))f=j.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in j)f=(Array.isArray(j.files)?j.files:[j.files]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("file_paths"in j)f=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((Y)=>({path:Y}));else if("paths"in j)f=(Array.isArray(j.paths)?j.paths:[j.paths]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else f=[j];return Promise.all(f.map(async(X)=>{let Y=GY(X);if(Y)return{query:E5(X),result:"",error:`Invalid file range: ${Y}`,success:!1};try{let V=await B1($(X,W),Q,`File read timed out after ${Q}ms`);return{query:E5(X),result:V,success:!0}}catch(V){let H=H$(V);return{query:E5(X),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function j7($,J={}){let Q=J.searchTimeoutMs??30000,Z=J.cwd??process.cwd();return m1({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(j8/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:A1(i4),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(W,j)=>{let f=v1(YY,W),X=Array.isArray(f)?f:typeof f==="object"?Array.isArray(f.queries)?f.queries:[f.queries]:[f];return Promise.all(X.map(async(Y)=>{try{let V=await B1($(Y,Z,j),Q,`Search timed out after ${Q}ms`);return{query:Y,result:V,success:!0}}catch(V){let H=H$(V);return{query:Y,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}function f7($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return m1({name:"run_commands",description:`Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands only when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. Output beyond ~${Math.round($6/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:A1(Z8),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=v1(VY,j),Y;if(typeof X==="string")Y=[X];else if(Array.isArray(X))Y=X;else if("commands"in X)Y=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)Y=[X.command];else Y=[X.cmd];return Y=zz(Y),Promise.all(Y.map(async(V)=>{let H=Date.now(),B=Q7(V);try{let A=await B1($(V,W,f),Q,`Command timed out after ${Q}ms`);return{query:B,result:A,success:!0}}catch(A){if(A instanceof i$)LY(f,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:Z,commandCount:Y.length,durationMs:Date.now()-H});if(A instanceof J6)return{query:B,result:A.output,error:A.message,success:!1};let K=H$(A);return{query:B,result:"",error:`Command failed: ${K}`,success:!1}}}))}})}function X7($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return m1({name:"run_commands",description:`Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Output beyond ~${Math.round($6/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped. Include multiple commands when they are independent and safe to run concurrently.`,inputSchema:A1(eZ),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=FY(j);return Promise.all(X.map(async(Y)=>{let V=Date.now(),H=Q7(Y);try{let B=await B1($(Y,W,f),Q,`Command timed out after ${Q}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof i$)LY(f,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Z,commandCount:X.length,durationMs:Date.now()-V});if(B instanceof J6)return{query:H,result:B.output,error:B.message,success:!1};let A=H$(B);return{query:H,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function Y7($,J={}){let Q=J.webFetchTimeoutMs??30000;return m1({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:A1(n4),timeoutMs:Q*2,retryable:!0,maxRetries:2,execute:async(Z,W)=>{let j=v1(n4,Z);return Promise.all(j.requests.map(async(f)=>{try{let X=await B1($(f.url,f.prompt,W),Q,`Web fetch timed out after ${Q}ms`);return{query:f.url,result:X,success:!0}}catch(X){let Y=H$(X);return{query:f.url,result:"",error:`Error fetching web content: ${Y}`,success:!1}}}))}})}var Lz=`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:
362
370
 
363
371
  *** Begin Patch
364
372
  *** Update File: path/to/file.ts
@@ -394,121 +402,121 @@ Example:
394
402
  </div>
395
403
  );
396
404
  }
397
- *** End Patch`;function aQ($,f={}){let J=f.applyPatchTimeoutMs??30000,Q=f.cwd??process.cwd();return g1({name:"apply_patch",description:hD,inputSchema:H1(l8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=m1(lX,Z),X=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await V1($({input:X},Q,W),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(Y){return{query:"apply_patch",result:"",error:`apply_patch failed: ${A$(Y)}`,success:!1}}}})}function tQ($,f={}){let J=f.editorTimeoutMs??30000,Q=f.cwd??process.cwd();return g1({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:H1(d8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=m1(d8,Z),X=j.insert_line==null?"edit":"insert",Y=pX(j);if(Y)return{query:`${X}:${j.path}`,result:"",error:Y,success:!1};try{let A=await V1($(j,Q,W),J,`Editor operation timed out after ${J}ms`);return{query:`${X}:${j.path}`,result:A,success:!0}}catch(A){let V=A$(A);return{query:`${X}:${j.path}`,result:"",error:`Editor operation failed: ${V}`,success:!1}}}})}function n$($,f={}){let J=f.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=g1({name:"skills",description:Q,inputSchema:H1(p8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=m1(p8,W);return V1($(X.skill,X.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let W=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(W&&W.length>0)return`${Q} Available skills: ${W.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),Z}function sQ($){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:H1(r8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let Q=m1(r8,f);return $(Q.question,Q.options,J)}}}function oQ($,f={}){let J=f.submitTimeoutMs??15000;return g1({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:H1(i8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let W=m1(i8,Q);return V1($(W.summary,W.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function V$($){let{executors:f,enableReadFiles:J=!0,enableSearch:Q=!0,enableBash:Z=!0,enableWebFetch:W=!0,enableApplyPatch:j=!1,enableEditor:X=!0,enableSkills:Y=!0,enableAskQuestion:A=!0,enableSubmitAndExit:V=!1,...H}=$,B=[];if(J&&f.readFile)B.push(lQ(f.readFile,H));if(Q&&f.search)B.push(pQ(f.search,H));if(Z&&f.bash)if(process.platform==="win32")B.push(iQ(f.bash,H));else B.push(rQ(f.bash,H));if(W&&f.webFetch)B.push(nQ(f.webFetch,H));if(X&&f.editor)B.push(tQ(f.editor,H));else if(j&&f.applyPatch)B.push(aQ(f.applyPatch,H));if(Y&&f.skills)B.push(n$(f.skills,H));let K=V?f.submit:void 0;if(A&&f.askQuestion&&!K)B.push(sQ(f.askQuestion));if(K)B.push(oQ(K,H));return B}import*as g0 from"node:fs/promises";import*as m0 from"node:path";var u={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},sX=["%%bash","apply_patch","EOF","```"];class W0 extends Error{constructor($){super($);this.name="DiffError"}}function x0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class eQ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,f){this.lines=$;this.currentFiles=f}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(u.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(u.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(u.UPDATE)){this.parseUpdate($.substring(u.UPDATE.length).trim());return}if($?.startsWith(u.DELETE)){this.parseDelete($.substring(u.DELETE.length).trim());return}if($?.startsWith(u.ADD)){this.parseAdd($.substring(u.ADD.length).trim());return}throw new W0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new W0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(u.MOVE)?(this.lines[this.index++]??"").substring(u.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new W0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",Q=this.parseUpdateFile(J,$);Q.movePath=f,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},Q=$.split(`
398
- `),Z=0,W=[u.END,u.UPDATE,u.DELETE,u.ADD,u.END_FILE];while(!W.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],X=j?.startsWith("@@ ")?j.substring(3):void 0;if(X!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new W0(`Invalid Line:
399
- ${this.lines[this.index]}`);if(X?.trim()){let P=x0(X.trim());for(let F=Z;F<Q.length;F++){let D=Q[F];if(D&&(x0(D)===P||x0(D.trim())===P)){if(Z=F+1,x0(D.trim())===P&&x0(D)!==P)this.fuzz++;break}}}let[A,V,H,B]=ID(this.lines,this.index),[K,G,R]=kD(Q,A,Z,B);if(K===-1){let P=A.join(`
400
- `);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:P.length>200?`${P.substring(0,200)}...`:P}),this.index=H}else{this.fuzz+=G;for(let P of V)P.origIndex+=K,J.chunks.push(P);Z=K+A.length,this.index=H}}return J}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new W0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new W0(`Add File Error: File already exists: ${$}`);this.index++;let f=[],J=[u.END,u.UPDATE,u.DELETE,u.ADD];while(this.hasMoreLines()&&!J.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new W0(`Invalid Add File line (missing '+'): ${Q}`);f.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
401
- `),chunks:[]}}}function tX($,f){let J=$.length>f.length?$:f,Q=$.length>f.length?f:$;if(J.length===0)return 1;let Z=bD(Q,J);return(J.length-Z)/J.length}function bD($,f){let J=f.length+1,Q=$.length+1,Z=Array(J*Q).fill(0),W=(X,Y)=>Z[X*Q+Y]??0,j=(X,Y,A)=>{Z[X*Q+Y]=A};for(let X=0;X<=f.length;X++)j(X,0,X);for(let X=0;X<=$.length;X++)j(0,X,X);for(let X=1;X<=f.length;X++)for(let Y=1;Y<=$.length;Y++)if(f[X-1]===$[Y-1])j(X,Y,W(X-1,Y-1));else j(X,Y,1+Math.min(W(X-1,Y-1),W(X,Y-1),W(X-1,Y)));return W(f.length,$.length)}function kD($,f,J,Q){if(f.length===0)return[J,0,1];let Z=0,W=(j)=>{let X=x0(f.join(`
402
- `));for(let A=j;A<$.length;A++){let V=x0($.slice(A,A+f.length).join(`
403
- `));if(V===X)return[A,0,1];let H=tX(V,X);if(H>Z)Z=H}for(let A=j;A<$.length;A++){let V=x0($.slice(A,A+f.length).map((B)=>B.trimEnd()).join(`
404
- `)),H=x0(f.map((B)=>B.trimEnd()).join(`
405
- `));if(V===H)return[A,1,1]}for(let A=j;A<$.length;A++){let V=x0($.slice(A,A+f.length).map((B)=>B.trim()).join(`
406
- `)),H=x0(f.map((B)=>B.trim()).join(`
407
- `));if(V===H)return[A,100,1]}let Y=0.66;for(let A=j;A<$.length;A++){let V=x0($.slice(A,A+f.length).join(`
408
- `)),H=tX(V,X);if(H>=Y)return[A,1000,H];if(H>Z)Z=H}return[-1,0,Z]};if(Q){let[j,X,Y]=W($.length-f.length);if(j!==-1)return[j,X,Y];return[j,X,Y]=W(J),[j,X+1e4,Y]}return W(J)}function ID($,f){let J=f,Q=[],Z=[],W=[],j=[],X="keep",Y=["@@",u.END,u.UPDATE,u.DELETE,u.ADD,u.END_FILE];while(J<$.length){let A=$[J];if(!A||Y.some((B)=>A.startsWith(B.trim())))break;if(A==="***")break;if(A.startsWith("***"))throw new W0(`Invalid line: ${A}`);J++;let V=X,H=A;if(H[0]==="+")X="add";else if(H[0]==="-")X="delete";else if(H[0]===" ")X="keep";else X="keep",H=` ${H}`;if(H=H.slice(1),X==="keep"&&V!==X){if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});Z=[],W=[]}if(X==="delete")Z.push(H),Q.push(H);else if(X==="add")W.push(H);else Q.push(H)}if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});if(J<$.length&&$[J]===u.END_FILE)return J++,[Q,j,J,!0];return[Q,j,J,!1]}function $Z($,f,J){let Q=m0.isAbsolute(f),Z=Q?m0.normalize(f):m0.resolve($,f);if(!J||Q)return Z;let W=m0.relative($,Z);if(W.startsWith("..")||m0.isAbsolute(W))throw new W0(`Path must stay within cwd: ${f}`);return Z}function xD($){return $.split(`
409
- `).map((f)=>f.replace(/\r$/,""))}function oX($){if($.trim()==="")return!1;return sX.some((f)=>$.startsWith(f))}function gD($){let f=0,J=$.length;while(f<J&&oX($[f]??""))f++;while(J>f&&oX($[J-1]??""))J--;return $.slice(f,J)}function mD($){let f=xD($),J=f.findIndex((j)=>j.startsWith(u.BEGIN)),Q=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(u.END)){Q=j;break}if(J!==-1||Q!==-1){if(J===-1||Q===-1||Q<J)throw new W0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,Q+1)}}let Z=gD(f);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[u.BEGIN,...Z,u.END]}}function vD($,f){let J=new Set;for(let Q of $)for(let Z of f)if(Q.startsWith(Z)){J.add(Q.substring(Z.length).trim());break}return[...J]}function cD($,f,J){if(f.length===0)return $;let Q=$.split(`
410
- `),Z=[],W=0;for(let j of f){if(j.origIndex>Q.length)throw new W0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${Q.length}`);if(W>j.origIndex)throw new W0(`${J}: currentIndex ${W} > chunk.origIndex ${j.origIndex}`);Z.push(...Q.slice(W,j.origIndex)),Z.push(...j.insLines),W=j.origIndex+j.delLines.length}return Z.push(...Q.slice(W)),Z.join(`
411
- `)}async function uD($,f,J,Q){let Z=vD($,[u.UPDATE,u.DELETE]),W={};for(let j of Z){let X=$Z(f,j,Q),Y;try{Y=await g0.readFile(X,J)}catch{throw new W0(`File not found: ${j}`)}W[j]=Y.replace(/\r\n/g,`
412
- `)}return W}function dD($,f){let J={};for(let[Q,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[Q]={type:"delete",oldContent:f[Q]};break;case"add":if(Z.newFile===void 0)throw new W0("ADD action without file content");J[Q]={type:"add",newContent:Z.newFile};break;case"update":J[Q]={type:"update",oldContent:f[Q],newContent:cD(f[Q]??"",Z.chunks,Q),movePath:Z.movePath};break}return J}async function lD($,f,J,Q){let Z=[];for(let[W,j]of Object.entries($)){let X=$Z(f,W,Q);switch(j.type){case"delete":await g0.rm(X,{force:!0}),Z.push(`${W}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new W0(`Cannot create ${W} with no content`);await g0.mkdir(m0.dirname(X),{recursive:!0}),await g0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break;case"update":{if(j.newContent===void 0)throw new W0(`UPDATE change for ${W} has no new content`);if(j.movePath){let Y=$Z(f,j.movePath,Q);await g0.mkdir(m0.dirname(Y),{recursive:!0}),await g0.writeFile(Y,j.newContent,{encoding:J}),await g0.rm(X,{force:!0}),Z.push(`${W} -> ${j.movePath}`)}else await g0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break}}}return Z}function n8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(Q,Z,W)=>{let j=mD(Q.input),X=await uD(j.lines,Z,f,J),Y=new eQ(j.lines,X),{patch:A,fuzz:V}=Y.parse(),H=dD(A,X),B=await lD(H,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of B)K.push(G);if(V>0)K.push(`Note: Patch applied with fuzz factor ${V}`);if(A.warnings&&A.warnings.length>0)for(let G of A.warnings)K.push(`Warning (${G.path}): ${G.message}`);return K.join(`
413
- `)}}import{spawn as eX}from"node:child_process";import{getDefaultShell as pD,getShellArgs as rD}from"@cline/shared";function iD($,f,J,Q,Z){return new Promise((W,j)=>{let X=process.platform==="win32",Y=eX($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X,windowsHide:!0}),A=Y.pid,V="",H="",B=0,K=!1,G=!1,R=(L)=>{if(G)return;G=!0,L()},P=()=>{if(!A)return;if(X){eX("taskkill",["/pid",String(A),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-A,"SIGKILL")}catch{Y.kill("SIGKILL")}},F=(L)=>{K=!0,P(),R(()=>j(L))},D=setTimeout(()=>F(new i$(`Command timed out after ${J}ms`,J)),J),z=()=>F(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",z);let T=()=>{clearTimeout(D),f.signal?.removeEventListener("abort",z)};Y.stdout?.on("data",(L)=>{if(B+=L.length,B<=Q)V+=L.toString()}),Y.stderr?.on("data",(L)=>{if(B+=L.length,B<=Q)H+=L.toString()}),Y.on("close",(L)=>{if(T(),K)return;let U=Z?V+(H?`
414
- [stderr]
415
- ${H}`:""):V;if(B>Q)U+=`
416
-
417
- [Output truncated: ${B} bytes total, showing first ${Q} bytes]`;if(L!==0)R(()=>j(Error(H||`Command exited with code ${L}`)));else R(()=>W(U))}),Y.on("error",(L)=>{T(),R(()=>j(Error(`Failed to execute command: ${L.message}`)))})})}function a8($={}){let{shell:f=pD(process.platform),timeoutMs:J=30000,maxOutputBytes:Q=1e6,env:Z={},combineOutput:W=!0}=$;return(j,X,Y)=>{let A=typeof j!=="string";return iD({executable:A?j.command:f,args:A?j.args??[]:rD(f,j),cwd:X,env:Z},Y,J,Q,W)}}import*as J1 from"node:fs/promises";import*as f1 from"node:path";function nD($,f,J){let Q=f1.isAbsolute(f),Z=Q?f1.normalize(f):f1.resolve($,f);if(!J)return Z;if(Q)return Z;let W=f1.relative($,Z);if(W.startsWith("..")||f1.isAbsolute(W))throw Error(`Path must stay within cwd: ${f}`);return Z}function aD($,f){if(f.length===0)return 0;return $.split(f).length-1}function tD($,f,J){let Q=$.split(`
418
- `),Z=f.split(`
419
- `),W=Math.max(Q.length,Z.length),j=["```diff"],X=0;for(let Y=0;Y<W;Y++){if(X>=J){j.push("... diff truncated ...");break}let A=Q[Y],V=Z[Y];if(A===V)continue;let H=Y+1;if(A!==void 0)j.push(`-${H}: ${A}`),X++;if(V!==void 0&&X<J)j.push(`+${H}: ${V}`),X++}return j.push("```"),j.join(`
420
- `)}async function sD($,f,J){return await J1.mkdir(f1.dirname($),{recursive:!0}),await J1.writeFile($,f,{encoding:J}),`File created successfully at: ${$}`}async function oD($){try{return await J1.access($),!0}catch{return!1}}async function eD($,f,J,Q,Z){let W=await J1.readFile($,Q),j=aD(W,f);if(j===0)throw Error(`No replacement performed: text not found in ${$}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let X=W.replace(f,J??"");await J1.writeFile($,X,{encoding:Q});let Y=tD(W,X,Z);return`Edited ${$}
421
- ${Y}`}async function $U($,f,J,Q){let W=(await J1.readFile($,Q)).split(`
422
- `),j=W.length+1;if(f<1||f>j)throw Error(`Invalid insert_line: ${f}. insert_line must be a positive one-based boundary line in the range 1-${j}. Use ${j} to append at EOF.`);let X=f-1;return W.splice(X,0,...J.split(`
423
- `)),await J1.writeFile($,W.join(`
424
- `),{encoding:Q}),`Inserted content at line ${f} in ${$}.`}function t8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:Q=200}=$;return async(Z,W,j)=>{let X=nD(W,Z.path,J);if(Z.insert_line!=null)return $U(X,Z.insert_line,Z.new_text,f);if(!await oD(X))return sD(X,Z.new_text,f);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return eD(X,Z.old_text,Z.new_text,f,Q)}}import*as s8 from"node:fs/promises";import*as H$ from"node:path";import{resolveExistingFilePath as fU}from"@cline/shared/storage";var JU=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),QU={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function o8($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:Q}={...QU,...$};return async(Z,W)=>{let{path:j,start_line:X,end_line:Y}=Z,A=H$.isAbsolute(j)?H$.normalize(j):H$.resolve(process.cwd(),j),V=fU(A)??A,H=H$.extname(V).toLowerCase(),B=JU.get(H),K=await s8.stat(V);if(!K.isFile())throw Error(`Path is not a file: ${V}`);if(K.size>f)throw Error(`File too large: ${K.size} bytes (max: ${f} bytes). Consider reading specific sections or using a different approach.`);if(B){if(W.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let z=await s8.readFile(V);return[{type:"text",text:"Successfully read image"},{type:"image",data:z.toString("base64"),mediaType:B}]}let R=(await s8.readFile(V,J)).split(`
425
- `),P=Math.max((X??1)-1,0),F=Math.min(Y??R.length,R.length),D=R.slice(P,F);if(Q){let z=String(R.length).length;return D.map((T,L)=>`${String(P+L+1).padStart(z," ")} | ${T}`).join(`
426
- `)}return D.join(`
427
- `)}}import{spawn as jY}from"node:child_process";import*as XY from"node:fs/promises";import*as w6 from"node:path";var WY={};q(WY,{prewarmFileIndex:()=>q6,getFileIndex:()=>v1,enrichPromptWithMentions:()=>Q2});import{spawn as ZU}from"node:child_process";import{readdir as WU}from"node:fs/promises";import JZ from"node:path";import{isMainThread as JY,parentPort as $Y,Worker as jU}from"node:worker_threads";var XU=15000,YU=600000,AU=1000,VU=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function fY($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var J2=new Map;function HU(){if(!JY)return!1;return!0}function BU($){if(J2.size<=1)return;for(let[f,J]of J2.entries()){if(J.pending)continue;if($-J.lastAccessedAt>YU)J2.delete(f)}}function KU($,f){return JZ.relative($,f).split(JZ.sep).join("/")}async function GU($){let J=(await new Promise((Q,Z)=>{let W=ZU("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),j="",X="";W.stdout.on("data",(Y)=>{j+=Y.toString()}),W.stderr.on("data",(Y)=>{X+=Y.toString()}),W.on("error",Z),W.on("close",(Y)=>{if(Y===0){Q(j);return}Z(Error(X||`rg exited with code ${Y}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(J)}async function QY($,f,J){let Q;try{Q=await WU(f,{withFileTypes:!0})}catch(Z){if(fY(Z))return;throw Z}for(let Z of Q){let W=JZ.join(f,Z.name);if(Z.isDirectory()){if(VU.has(Z.name))continue;try{await QY($,W,J)}catch(j){if(fY(j))continue;throw j}continue}if(Z.isFile())J.add(KU($,W))}}async function FU($){let f=new Set;return await QY($,$,f),f}async function N6($){try{return await GU($)}catch{return FU($)}}function PU(){if(JY||!$Y)return;let $=$Y;$.on("message",(f)=>{if(f.type!=="index")return;N6(f.cwd).then((J)=>{let Q={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(Q)}).catch((J)=>{let Q={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(Q)})})}class ZY{worker=new jU(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let f=++this.nextRequestId,J=new Promise((Z,W)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},AU);j.unref(),this.pending.set(f,{resolve:(X)=>{clearTimeout(j),Z(X)},reject:(X)=>{clearTimeout(j),W(X)}})}),Q={type:"index",requestId:f,cwd:$};return this.worker.postMessage(Q),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}PU();var fZ;function RU(){if(!HU())return null;if(fZ===void 0)fZ=new ZY;return fZ}async function DU($){let f=RU();if(!f)return N6($);try{let J=await f.requestIndex($);if(J===null)return N6($);return new Set(J)}catch{return N6($)}}async function v1($,f={}){let J=f.ttlMs??XU,Q=Date.now();BU(Q);let Z=J2.get($);if(Z&&J>0&&Q-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=Q,Z.files;if(Z?.pending)return Z.lastAccessedAt=Q,Z.pending;let W=DU($).then((j)=>{return J2.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return J2.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:Q,pending:W}),W}async function q6($,f={}){await v1($,{...f,ttlMs:0})}import{stat as UU}from"node:fs/promises";import a$ from"node:path";var LU=/[),.:;!?`'"]+$/,_U=/^[(`'"]+/;function zU($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let Q of f){let Z=(Q[2]??"").trim();if(Z.length===0)continue;let W=Z.replace(_U,"").replace(LU,"");if(W.length===0||W.includes("@"))continue;J.push(W)}return Array.from(new Set(J))}function OU($,f){let J=$.replace(/\\/g,"/"),Q=a$.isAbsolute(J)?a$.resolve(J):a$.resolve(f,J),Z=a$.relative(f,Q);if(Z.startsWith("..")||a$.isAbsolute(Z))return;return Z.split(a$.sep).join("/")}async function Q2($,f,J={}){let Q=zU($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:W,maxTotalBytes:j}=J,X=await v1(f,{ttlMs:J.ttlMs}),Y=[],A=[],V=[],H=0;for(let B of Q){if(Z&&V.length>=Z){A.push(B);continue}let K=OU(B,f);if(!K||!X.has(K)){A.push(B);continue}if(!W||!j){Y.push(K);continue}let G=a$.join(f,K);try{if(!(await UU(G)).isFile()){A.push(B);continue}let P=H+W;if(P>j){A.push(B);continue}H=P,Y.push(K)}catch{A.push(B)}}return{prompt:$,mentions:Q,matchedFiles:Y,ignoredMentions:A}}var MU=["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"],TU=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],t$=null;function NU(){if(t$!==null)return Promise.resolve(t$);return new Promise(($)=>{let f=jY("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});f.on("close",(J)=>{t$=J===0,$(t$)}),f.on("error",()=>{t$=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(t$===null)t$=!1,$(!1)},1000)})}function qU($,f,J,Q,Z=5000,W){return new Promise((j)=>{let X=jY("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",A=!1,V=()=>{if(!X.killed)X.kill("SIGTERM")},H=setTimeout(()=>{if(!A)A=!0,V(),j(null)},Z),B=(K)=>{if(!A)A=!0,clearTimeout(H),V(),j(K)};if(W?.aborted){V(),j(null);return}W?.addEventListener("abort",()=>{B(null)}),X.stdout.on("data",(K)=>{Y+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=Y.split(`
428
- `).filter((P)=>P.trim());for(let P of R){if(G.length>=J)break;let F=JSON.parse(P);if(F.type==="match"){let D=F.data,z=[];if(F.data.submatches&&F.data.submatches.length>0){let T=F.data.submatches[0];G.push({file:D.path.text,line:D.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:z})}}else if(F.type==="context"&&G.length>0){let D=G[G.length-1],z=F.data.line_number===D.line?">":" ";D.context.push(`${z} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}B(G.length>0?G:null)}catch{B(null)}return}B(null)}),X.on("error",()=>{B(null)})})}function wU($,f,J,Q){let Z=$.split("/"),W=Z[Z.length-1]??"";if(Z.length-1>Q)return!1;for(let Y=0;Y<Z.length-1;Y++)if(f.has(Z[Y]??""))return!1;let X=w6.posix.extname(W).slice(1).toLowerCase();return J.has(X)||!X&&!W.startsWith(".")}function e8($={}){let{includeExtensions:f=MU,excludeDirs:J=TU,maxResults:Q=100,contextLines:Z=2,maxDepth:W=20}=$,j=new Set(J),X=new Set(f.map((Y)=>Y.toLowerCase()));return async(Y,A,V)=>{if(V.signal?.aborted)throw Error("Search operation aborted");let H=await NU(),B=null;if(H)B=await qU(Y,A,Q,Z,5000,V.signal);if(B){let D=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${Y}`,""];for(let z of B)D.push(`${z.file}:${z.line}:${z.column}`),D.push(...z.context),D.push("");if(B.length>=Q)D.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return D.join(`
429
- `)}let K;try{K=new RegExp(Y,"gim")}catch(D){throw Error(`Invalid regex pattern: ${Y}. ${D instanceof Error?D.message:""}`)}let G=[],R=0,P=await v1(A);for(let D of P){if(V.signal?.aborted)throw Error("Search operation aborted");if(!wU(D,j,X,W))continue;if(G.length>=Q)break;R++;let z=w6.join(A,D);try{let L=(await XY.readFile(z,"utf-8")).split(`
430
- `);for(let U=0;U<L.length;U++){let w=L[U];K.lastIndex=0;let h=K.exec(w);while(h!==null){if(G.length>=Q)break;let I=Math.max(0,U-Z),o=Math.min(L.length-1,U+Z),V0=[];for(let $0=I;$0<=o;$0++){let t=$0===U?">":" ";V0.push(`${t} ${$0+1}: ${L[$0]}`)}if(G.push({file:D,line:U+1,column:h.index+1,match:h[0],context:V0}),h.index===K.lastIndex)K.lastIndex++;h=K.exec(w)}}}catch{}}if(G.length===0)return`No results found for pattern: ${Y}
431
- Searched ${R} files.`;let F=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Y}`,`Searched ${R} files.`,""];for(let D of G)F.push(`${D.file}:${D.line}:${D.column}`),F.push(...D.context),F.push("");if(G.length>=Q)F.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return F.join(`
432
- `)}}function CU($){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,`
433
- `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(f,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
405
+ *** End Patch`;function V7($,J={}){let Q=J.applyPatchTimeoutMs??30000,Z=J.cwd??process.cwd();return m1({name:"apply_patch",description:Lz,inputSchema:A1(s4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=v1(AY,W),X=typeof f==="string"?f:f.input;try{return{query:"apply_patch",result:await B1($({input:X},Z,j),Q,`apply_patch timed out after ${Q}ms`),success:!0}}catch(Y){return{query:"apply_patch",result:"",error:`apply_patch failed: ${H$(Y)}`,success:!1}}}})}function H7($,J={}){let Q=J.editorTimeoutMs??30000,Z=J.cwd??process.cwd();return m1({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:A1(a4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=v1(a4,W),X=f.insert_line==null?"edit":"insert",Y=KY(f);if(Y)return{query:`${X}:${f.path}`,result:"",error:Y,success:!1};try{let V=await B1($(f,Z,j),Q,`Editor operation timed out after ${Q}ms`);return{query:`${X}:${f.path}`,result:V,success:!0}}catch(V){let H=H$(V);return{query:`${X}:${f.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function n$($,J={}){let Q=J.skillsTimeoutMs??15000,Z='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',W=m1({name:"skills",description:Z,inputSchema:A1(o4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=v1(o4,j);return B1($(X.skill,X.args||void 0,f),Q,`Skills operation timed out after ${Q}ms`)}});return Object.defineProperty(W,"description",{get(){let j=$.configuredSkills?.filter((f)=>!f.disabled).map((f)=>f.name);if(j&&j.length>0)return`${Z} Available skills: ${j.join(", ")}.`;return Z},enumerable:!0,configurable:!0}),W}function B7($){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:A1(t4),retryable:!1,maxRetries:0,execute:async(J,Q)=>{let Z=v1(t4,J);return $(Z.question,Z.options,Q)}}}function A7($,J={}){let Q=J.submitTimeoutMs??15000;return m1({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:A1(e4),lifecycle:{completesRun:!0},timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=v1(e4,Z);return B1($(j.summary,j.verified,W),Q,`submit_and_exit timed out after ${Q}ms`)}})}function B$($){let{executors:J,enableReadFiles:Q=!0,enableSearch:Z=!0,enableBash:W=!0,enableWebFetch:j=!0,enableApplyPatch:f=!1,enableEditor:X=!0,enableSkills:Y=!0,enableAskQuestion:V=!0,enableSubmitAndExit:H=!1,...B}=$,A=[];if(Q&&J.readFile)A.push(W7(J.readFile,B));if(Z&&J.search)A.push(j7(J.search,B));if(W&&J.bash)if(process.platform==="win32")A.push(X7(J.bash,B));else A.push(f7(J.bash,B));if(j&&J.webFetch)A.push(Y7(J.webFetch,B));if(X&&J.editor)A.push(H7(J.editor,B));else if(f&&J.applyPatch)A.push(V7(J.applyPatch,B));if(Y&&J.skills)A.push(n$(J.skills,B));let K=H?J.submit:void 0;if(V&&J.askQuestion&&!K)A.push(B7(J.askQuestion));if(K)A.push(A7(K,B));return A}import*as m0 from"node:fs/promises";import*as v0 from"node:path";var d={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},OY=["%%bash","apply_patch","EOF","```"];class W0 extends Error{constructor($){super($);this.name="DiffError"}}function g0($){let J={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Q)=>J[Q]??Q).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class K7{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,J){this.lines=$;this.currentFiles=J}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(d.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(d.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(d.UPDATE)){this.parseUpdate($.substring(d.UPDATE.length).trim());return}if($?.startsWith(d.DELETE)){this.parseDelete($.substring(d.DELETE.length).trim());return}if($?.startsWith(d.ADD)){this.parseAdd($.substring(d.ADD.length).trim());return}throw new W0(`Unknown line while parsing: ${$}`)}checkDuplicate($,J){if($ in this.patch.actions)throw new W0(`Duplicate ${J} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let J=this.lines[this.index]?.startsWith(d.MOVE)?(this.lines[this.index++]??"").substring(d.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new W0(`Update File Error: Missing File: ${$}`);let Q=this.currentFiles[$]??"",Z=this.parseUpdateFile(Q,$);Z.movePath=J,this.patch.actions[$]=Z,this.currentPath=void 0}parseUpdateFile($,J){let Q={type:"update",chunks:[]},Z=$.split(`
406
+ `),W=0,j=[d.END,d.UPDATE,d.DELETE,d.ADD,d.END_FILE];while(!j.some((f)=>this.lines[this.index]?.startsWith(f.trim()))){let f=this.lines[this.index],X=f?.startsWith("@@ ")?f.substring(3):void 0;if(X!==void 0||(f==="@@"?f:void 0)!==void 0)this.index++;else if(W!==0)throw new W0(`Invalid Line:
407
+ ${this.lines[this.index]}`);if(X?.trim()){let D=g0(X.trim());for(let U=W;U<Z.length;U++){let F=Z[U];if(F&&(g0(F)===D||g0(F.trim())===D)){if(W=U+1,g0(F.trim())===D&&g0(F)!==D)this.fuzz++;break}}}let[V,H,B,A]=Tz(this.lines,this.index),[K,G,R]=Oz(Z,V,W,A);if(K===-1){let D=V.join(`
408
+ `);this.addWarning({path:this.currentPath||J,chunkIndex:Q.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:D.length>200?`${D.substring(0,200)}...`:D}),this.index=B}else{this.fuzz+=G;for(let D of H)D.origIndex+=K,Q.chunks.push(D);W=K+V.length,this.index=B}}return Q}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new W0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new W0(`Add File Error: File already exists: ${$}`);this.index++;let J=[],Q=[d.END,d.UPDATE,d.DELETE,d.ADD];while(this.hasMoreLines()&&!Q.some((Z)=>this.lines[this.index]?.startsWith(Z.trim()))){let Z=this.lines[this.index++];if(Z===void 0)break;if(!Z.startsWith("+"))throw new W0(`Invalid Add File line (missing '+'): ${Z}`);J.push(Z.substring(1))}this.patch.actions[$]={type:"add",newFile:J.join(`
409
+ `),chunks:[]}}}function _Y($,J){let Q=$.length>J.length?$:J,Z=$.length>J.length?J:$;if(Q.length===0)return 1;let W=_z(Z,Q);return(Q.length-W)/Q.length}function _z($,J){let Q=J.length+1,Z=$.length+1,W=Array(Q*Z).fill(0),j=(X,Y)=>W[X*Z+Y]??0,f=(X,Y,V)=>{W[X*Z+Y]=V};for(let X=0;X<=J.length;X++)f(X,0,X);for(let X=0;X<=$.length;X++)f(0,X,X);for(let X=1;X<=J.length;X++)for(let Y=1;Y<=$.length;Y++)if(J[X-1]===$[Y-1])f(X,Y,j(X-1,Y-1));else f(X,Y,1+Math.min(j(X-1,Y-1),j(X,Y-1),j(X-1,Y)));return j(J.length,$.length)}function Oz($,J,Q,Z){if(J.length===0)return[Q,0,1];let W=0,j=(f)=>{let X=g0(J.join(`
410
+ `));for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).join(`
411
+ `));if(H===X)return[V,0,1];let B=_Y(H,X);if(B>W)W=B}for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).map((A)=>A.trimEnd()).join(`
412
+ `)),B=g0(J.map((A)=>A.trimEnd()).join(`
413
+ `));if(H===B)return[V,1,1]}for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).map((A)=>A.trim()).join(`
414
+ `)),B=g0(J.map((A)=>A.trim()).join(`
415
+ `));if(H===B)return[V,100,1]}let Y=0.66;for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).join(`
416
+ `)),B=_Y(H,X);if(B>=Y)return[V,1000,B];if(B>W)W=B}return[-1,0,W]};if(Z){let[f,X,Y]=j($.length-J.length);if(f!==-1)return[f,X,Y];return[f,X,Y]=j(Q),[f,X+1e4,Y]}return j(Q)}function Tz($,J){let Q=J,Z=[],W=[],j=[],f=[],X="keep",Y=["@@",d.END,d.UPDATE,d.DELETE,d.ADD,d.END_FILE];while(Q<$.length){let V=$[Q];if(!V||Y.some((A)=>V.startsWith(A.trim())))break;if(V==="***")break;if(V.startsWith("***"))throw new W0(`Invalid line: ${V}`);Q++;let H=X,B=V;if(B[0]==="+")X="add";else if(B[0]==="-")X="delete";else if(B[0]===" ")X="keep";else X="keep",B=` ${B}`;if(B=B.slice(1),X==="keep"&&H!==X){if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});W=[],j=[]}if(X==="delete")W.push(B),Z.push(B);else if(X==="add")j.push(B);else Z.push(B)}if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});if(Q<$.length&&$[Q]===d.END_FILE)return Q++,[Z,f,Q,!0];return[Z,f,Q,!1]}function G7($,J,Q){let Z=v0.isAbsolute(J),W=Z?v0.normalize(J):v0.resolve($,J);if(!Q||Z)return W;let j=v0.relative($,W);if(j.startsWith("..")||v0.isAbsolute(j))throw new W0(`Path must stay within cwd: ${J}`);return W}function Mz($){return $.split(`
417
+ `).map((J)=>J.replace(/\r$/,""))}function TY($){if($.trim()==="")return!1;return OY.some((J)=>$.startsWith(J))}function qz($){let J=0,Q=$.length;while(J<Q&&TY($[J]??""))J++;while(Q>J&&TY($[Q-1]??""))Q--;return $.slice(J,Q)}function Pz($){let J=Mz($),Q=J.findIndex((f)=>f.startsWith(d.BEGIN)),Z=-1;for(let f=J.length-1;f>=0;f--)if(J[f]?.startsWith(d.END)){Z=f;break}if(Q!==-1||Z!==-1){if(Q===-1||Z===-1||Z<Q)throw new W0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:J.slice(Q,Z+1)}}let W=qz(J);while(W.length>0&&W[0]==="")W.shift();while(W.length>0&&W[W.length-1]==="")W.pop();return{lines:[d.BEGIN,...W,d.END]}}function Nz($,J){let Q=new Set;for(let Z of $)for(let W of J)if(Z.startsWith(W)){Q.add(Z.substring(W.length).trim());break}return[...Q]}function wz($,J,Q){if(J.length===0)return $;let Z=$.split(`
418
+ `),W=[],j=0;for(let f of J){if(f.origIndex>Z.length)throw new W0(`${Q}: chunk.origIndex ${f.origIndex} > lines.length ${Z.length}`);if(j>f.origIndex)throw new W0(`${Q}: currentIndex ${j} > chunk.origIndex ${f.origIndex}`);W.push(...Z.slice(j,f.origIndex)),W.push(...f.insLines),j=f.origIndex+f.delLines.length}return W.push(...Z.slice(j)),W.join(`
419
+ `)}async function Sz($,J,Q,Z){let W=Nz($,[d.UPDATE,d.DELETE]),j={};for(let f of W){let X=G7(J,f,Z),Y;try{Y=await m0.readFile(X,Q)}catch{throw new W0(`File not found: ${f}`)}j[f]=Y.replace(/\r\n/g,`
420
+ `)}return j}function Cz($,J){let Q={};for(let[Z,W]of Object.entries($.actions))switch(W.type){case"delete":Q[Z]={type:"delete",oldContent:J[Z]};break;case"add":if(W.newFile===void 0)throw new W0("ADD action without file content");Q[Z]={type:"add",newContent:W.newFile};break;case"update":Q[Z]={type:"update",oldContent:J[Z],newContent:wz(J[Z]??"",W.chunks,Z),movePath:W.movePath};break}return Q}function yz($){let J=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Q of $){let Z=Q.chunkIndex===void 0?"unknown":String(Q.chunkIndex+1);if(J.push(`${Q.path}: hunk ${Z}: ${Q.message}`),Q.context)J.push(`Context:
421
+ ${Q.context}`)}return J.join(`
422
+ `)}async function Ez($,J,Q,Z){let W=[];for(let[j,f]of Object.entries($)){let X=G7(J,j,Z);switch(f.type){case"delete":await m0.rm(X,{force:!0}),W.push(`${j}: [deleted]`);break;case"add":if(f.newContent===void 0)throw new W0(`Cannot create ${j} with no content`);await m0.mkdir(v0.dirname(X),{recursive:!0}),await m0.writeFile(X,f.newContent,{encoding:Q}),W.push(j);break;case"update":{if(f.newContent===void 0)throw new W0(`UPDATE change for ${j} has no new content`);if(f.movePath){let Y=G7(J,f.movePath,Z);await m0.mkdir(v0.dirname(Y),{recursive:!0}),await m0.writeFile(Y,f.newContent,{encoding:Q}),await m0.rm(X,{force:!0}),W.push(`${j} -> ${f.movePath}`)}else await m0.writeFile(X,f.newContent,{encoding:Q}),W.push(j);break}}}return W}function Z6($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0}=$;return async(Z,W,j)=>{let f=Pz(Z.input),X=await Sz(f.lines,W,J,Q),Y=new K7(f.lines,X),{patch:V,fuzz:H}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new W0(yz(V.warnings));let B=Cz(V,X),A=await Ez(B,W,J,Q),K=["Successfully applied patch to the following files:"];for(let G of A)K.push(G);if(H>0)K.push(`Note: Patch applied with fuzz factor ${H}`);return K.join(`
423
+ `)}}import*as W1 from"node:fs/promises";import*as Z1 from"node:path";function bz($,J,Q){let Z=Z1.isAbsolute(J),W=Z?Z1.normalize(J):Z1.resolve($,J);if(!Q)return W;if(Z)return W;let j=Z1.relative($,W);if(j.startsWith("..")||Z1.isAbsolute(j))throw Error(`Path must stay within cwd: ${J}`);return W}function hz($,J){if(J.length===0)return 0;return $.split(J).length-1}function kz($,J,Q){let Z=$.split(`
424
+ `),W=J.split(`
425
+ `),j=Math.max(Z.length,W.length),f=["```diff"],X=0;for(let Y=0;Y<j;Y++){if(X>=Q){f.push("... diff truncated ...");break}let V=Z[Y],H=W[Y];if(V===H)continue;let B=Y+1;if(V!==void 0)f.push(`-${B}: ${V}`),X++;if(H!==void 0&&X<Q)f.push(`+${B}: ${H}`),X++}return f.push("```"),f.join(`
426
+ `)}async function Iz($,J,Q){return await W1.mkdir(Z1.dirname($),{recursive:!0}),await W1.writeFile($,J,{encoding:Q}),`File created successfully at: ${$}`}async function xz($){try{return await W1.access($),!0}catch{return!1}}async function gz($,J,Q,Z,W){let j=await W1.readFile($,Z),f=hz(j,J);if(f===0)throw Error(`No replacement performed: text not found in ${$}.`);if(f>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let X=j.replace(J,Q??"");await W1.writeFile($,X,{encoding:Z});let Y=kz(j,X,W);return`Edited ${$}
427
+ ${Y}`}async function mz($,J,Q,Z){let j=(await W1.readFile($,Z)).split(`
428
+ `),f=j.length+1;if(J<1||J>f)throw Error(`Invalid insert_line: ${J}. insert_line must be a positive one-based boundary line in the range 1-${f}. Use ${f} to append at EOF.`);let X=J-1;return j.splice(X,0,...Q.split(`
429
+ `)),await W1.writeFile($,j.join(`
430
+ `),{encoding:Z}),`Inserted content at line ${J} in ${$}.`}function W6($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0,maxDiffLines:Z=200}=$;return async(W,j,f)=>{let X=bz(j,W.path,Q);if(W.insert_line!=null)return mz(X,W.insert_line,W.new_text,J);if(!await xz(X))return Iz(X,W.new_text,J);if(W.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return gz(X,W.old_text,W.new_text,J,Z)}}import{createReadStream as vz}from"node:fs";import*as h5 from"node:fs/promises";import*as A$ from"node:path";import{createInterface as cz}from"node:readline";import{resolveExistingFilePath as uz}from"@cline/shared/storage";var dz=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),lz={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},MY=1e8,pz=50000;function qY($){let{reason:J}=$;if(J instanceof Error)return J;if(J!==void 0)return Error(String(J));return Error("File read was aborted")}async function rz($,J,Q,Z,W,j){if(j?.aborted)throw qY(j);let f=Math.max(Z??1,1),X=W??Number.POSITIVE_INFINITY,Y=Number.isFinite(X),V=Y?X:f+pz-1,H=[],B=0,A=0,K=!1,G=!1,R=Number.isFinite(X)?Math.min(X,f+W8-1):f+W8-1,D=Q?String(R).length+3:0,U=vz($,{encoding:J}),F=cz({input:U,crlfDelay:Number.POSITIVE_INFINITY}),O=j?()=>U.destroy(qY(j)):void 0;if(j&&O)j.addEventListener("abort",O,{once:!0});try{for await(let b of F){if(A+=1,A>X){A=X;break}if(!Y&&K&&A>=V){G=!0;break}if(A<f||K)continue;if(H.length>=W8){K=!0;continue}let u=b;if(u.length>Z7)u=`${u.slice(0,Z7)} [line truncated]`;let o=B+u.length+D+1;if(o>b5&&H.length>0){K=!0;continue}H.push({lineNumber:A,text:u}),B=o}}finally{if(j&&O)j.removeEventListener("abort",O);F.close(),U.destroy()}let T=String(H[H.length-1]?.lineNumber??A).length,L=H.map(({lineNumber:b,text:u})=>Q?`${String(b).padStart(T," ")} | ${u}`:u).join(`
431
+ `),z=H[H.length-1]?.lineNumber;if(z===void 0)return L;let P=Math.min(X,A);if(z>=P)return L;let S=G?`${A}+ lines`:P;return`${L}
432
+
433
+ [Showing lines ${f}-${z} of ${S}. Use start_line/end_line to read other sections.]`}function j6($={}){let{maxFileSizeBytes:J,encoding:Q,includeLineNumbers:Z}={...lz,...$};return async(W,j)=>{let{path:f,start_line:X,end_line:Y}=W,V=A$.isAbsolute(f)?A$.normalize(f):A$.resolve(process.cwd(),f),H=uz(V)??V,B=A$.extname(H).toLowerCase(),A=dz.get(B),K=await h5.stat(H);if(!K.isFile())throw Error(`Path is not a file: ${H}`);if(A){if(K.size>J)throw Error(`Image file too large: ${K.size} bytes (max: ${J} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let G=await h5.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:G.toString("base64"),mediaType:A}]}if(K.size>MY)throw Error(`Text file too large to stream safely: ${K.size} bytes (max: ${MY} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return rz(H,Q,Z,X,Y,j.signal)}}import{spawn as bY}from"node:child_process";import*as hY from"node:fs/promises";import*as x5 from"node:path";var yY={};w(yY,{prewarmFileIndex:()=>I5,getFileIndex:()=>c1,enrichPromptWithMentions:()=>X8});import{spawn as iz}from"node:child_process";import{readdir as nz}from"node:fs/promises";import D7 from"node:path";import{isMainThread as wY,parentPort as PY,Worker as az}from"node:worker_threads";var sz=15000,oz=600000,tz=1000,ez=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function NY($){let J=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return J==="EACCES"||J==="EPERM"||J==="ENOENT"}var f8=new Map;function $L(){if(!wY)return!1;return!0}function JL($){if(f8.size<=1)return;for(let[J,Q]of f8.entries()){if(Q.pending)continue;if($-Q.lastAccessedAt>oz)f8.delete(J)}}function QL($,J){return D7.relative($,J).split(D7.sep).join("/")}async function ZL($){let Q=(await new Promise((Z,W)=>{let j=iz("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),f="",X="";j.stdout.on("data",(Y)=>{f+=Y.toString()}),j.stderr.on("data",(Y)=>{X+=Y.toString()}),j.on("error",W),j.on("close",(Y)=>{if(Y===0){Z(f);return}W(Error(X||`rg exited with code ${Y}`))})})).split(/\r?\n/).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>Z.replace(/\\/g,"/"));return new Set(Q)}async function SY($,J,Q){let Z;try{Z=await nz(J,{withFileTypes:!0})}catch(W){if(NY(W))return;throw W}for(let W of Z){let j=D7.join(J,W.name);if(W.isDirectory()){if(ez.has(W.name))continue;try{await SY($,j,Q)}catch(f){if(NY(f))continue;throw f}continue}if(W.isFile())Q.add(QL($,j))}}async function WL($){let J=new Set;return await SY($,$,J),J}async function k5($){try{return await ZL($)}catch{return WL($)}}function jL(){if(wY||!PY)return;let $=PY;$.on("message",(J)=>{if(J.type!=="index")return;k5(J.cwd).then((Q)=>{let Z={type:"indexResult",requestId:J.requestId,files:Array.from(Q)};$.postMessage(Z)}).catch((Q)=>{let Z={type:"indexResult",requestId:J.requestId,error:Q instanceof Error?Q.message:"Failed to build file index"};$.postMessage(Z)})})}class CY{worker=new az(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let J=this.pending.get($.requestId);if(!J)return;if(this.pending.delete($.requestId),$.error){J.reject(Error($.error));return}J.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let J=++this.nextRequestId,Q=new Promise((W,j)=>{let f=setTimeout(()=>{this.pending.delete(J),W(null)},tz);f.unref(),this.pending.set(J,{resolve:(X)=>{clearTimeout(f),W(X)},reject:(X)=>{clearTimeout(f),j(X)}})}),Z={type:"index",requestId:J,cwd:$};return this.worker.postMessage(Z),Q}flushPending($){for(let[J,Q]of this.pending.entries())Q.reject($),this.pending.delete(J)}}jL();var F7;function fL(){if(!$L())return null;if(F7===void 0)F7=new CY;return F7}async function XL($){let J=fL();if(!J)return k5($);try{let Q=await J.requestIndex($);if(Q===null)return k5($);return new Set(Q)}catch{return k5($)}}async function c1($,J={}){let Q=J.ttlMs??sz,Z=Date.now();JL(Z);let W=f8.get($);if(W&&Q>0&&Z-W.lastBuiltAt<=Q&&W.files.size>0)return W.lastAccessedAt=Z,W.files;if(W?.pending)return W.lastAccessedAt=Z,W.pending;let j=XL($).then((f)=>{return f8.set($,{files:f,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),f});return f8.set($,{files:W?.files??new Set,lastBuiltAt:W?.lastBuiltAt??0,lastAccessedAt:Z,pending:j}),j}async function I5($,J={}){await c1($,{...J,ttlMs:0})}import{stat as YL}from"node:fs/promises";import a$ from"node:path";var VL=/[),.:;!?`'"]+$/,HL=/^[(`'"]+/;function BL($){let J=$.matchAll(/(^|[\s])@([^\s]+)/g),Q=[];for(let Z of J){let W=(Z[2]??"").trim();if(W.length===0)continue;let j=W.replace(HL,"").replace(VL,"");if(j.length===0||j.includes("@"))continue;Q.push(j)}return Array.from(new Set(Q))}function AL($,J){let Q=$.replace(/\\/g,"/"),Z=a$.isAbsolute(Q)?a$.resolve(Q):a$.resolve(J,Q),W=a$.relative(J,Z);if(W.startsWith("..")||a$.isAbsolute(W))return;return W.split(a$.sep).join("/")}async function X8($,J,Q={}){let Z=BL($);if(Z.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:W,maxFileBytes:j,maxTotalBytes:f}=Q,X=await c1(J,{ttlMs:Q.ttlMs}),Y=[],V=[],H=[],B=0;for(let A of Z){if(W&&H.length>=W){V.push(A);continue}let K=AL(A,J);if(!K||!X.has(K)){V.push(A);continue}if(!j||!f){Y.push(K);continue}let G=a$.join(J,K);try{if(!(await YL(G)).isFile()){V.push(A);continue}let D=B+j;if(D>f){V.push(A);continue}B=D,Y.push(K)}catch{V.push(A)}}return{prompt:$,mentions:Z,matchedFiles:Y,ignoredMentions:V}}var KL=["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"],GL=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],s$=null;function FL(){if(s$!==null)return Promise.resolve(s$);return new Promise(($)=>{let J=bY("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});J.on("close",(Q)=>{s$=Q===0,$(s$)}),J.on("error",()=>{s$=!1,$(!1)}),setTimeout(()=>{if(!J.killed)J.kill("SIGTERM");if(s$===null)s$=!1,$(!1)},1000)})}function DL($,J,Q,Z,W=5000,j){return new Promise((f)=>{let X=bY("rg",["--json",`--context=${Z}`,"--max-count=1","-i",$],{cwd:J,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V=!1,H=()=>{if(!X.killed)X.kill("SIGTERM")},B=setTimeout(()=>{if(!V)V=!0,H(),f(null)},W),A=(K)=>{if(!V)V=!0,clearTimeout(B),H(),f(K)};if(j?.aborted){H(),f(null);return}j?.addEventListener("abort",()=>{A(null)}),X.stdout.on("data",(K)=>{Y+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=Y.split(`
434
+ `).filter((D)=>D.trim());for(let D of R){if(G.length>=Q)break;let U=JSON.parse(D);if(U.type==="match"){let F=U.data,O=[];if(U.data.submatches&&U.data.submatches.length>0){let T=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:O})}}else if(U.type==="context"&&G.length>0){let F=G[G.length-1],O=U.data.line_number===F.line?">":" ";F.context.push(`${O} ${U.data.line_number}: ${U.data.lines?.text??U.data.line?.text??""}`)}}A(G.length>0?G:null)}catch{A(null)}return}A(null)}),X.on("error",()=>{A(null)})})}function UL($,J,Q,Z){let W=$.split("/"),j=W[W.length-1]??"";if(W.length-1>Z)return!1;for(let Y=0;Y<W.length-1;Y++)if(J.has(W[Y]??""))return!1;let X=x5.posix.extname(j).slice(1).toLowerCase();return Q.has(X)||!X&&!j.startsWith(".")}function f6($={}){let{includeExtensions:J=KL,excludeDirs:Q=GL,maxResults:Z=100,contextLines:W=2,maxDepth:j=20}=$,f=new Set(Q),X=new Set(J.map((Y)=>Y.toLowerCase()));return async(Y,V,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let B=await FL(),A=null;if(B)A=await DL(Y,V,Z,W,5000,H.signal);if(A){let F=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${Y}`,""];for(let O of A)F.push(`${O.file}:${O.line}:${O.column}`),F.push(...O.context),F.push("");if(A.length>=Z)F.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return EY(F.join(`
435
+ `))}let K;try{K=new RegExp(Y,"gim")}catch(F){throw Error(`Invalid regex pattern: ${Y}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,D=await c1(V);for(let F of D){if(H.signal?.aborted)throw Error("Search operation aborted");if(!UL(F,f,X,j))continue;if(G.length>=Z)break;R++;let O=x5.join(V,F);try{let L=(await hY.readFile(O,"utf-8")).split(`
436
+ `);for(let z=0;z<L.length;z++){let P=L[z];K.lastIndex=0;let S=K.exec(P);while(S!==null){if(G.length>=Z)break;let b=Math.max(0,z-W),u=Math.min(L.length-1,z+W),o=[];for(let J0=b;J0<=u;J0++){let t=J0===z?">":" ";o.push(`${t} ${J0+1}: ${L[J0]}`)}if(G.push({file:F,line:z+1,column:S.index+1,match:S[0],context:o}),S.index===K.lastIndex)K.lastIndex++;S=K.exec(P)}}}catch{}}if(G.length===0)return`No results found for pattern: ${Y}
437
+ Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Y}`,`Searched ${R} files.`,""];for(let F of G)U.push(`${F.file}:${F.line}:${F.column}`),U.push(...F.context),U.push("");if(G.length>=Z)U.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return EY(U.join(`
438
+ `))}}function EY($){if($.length<=j8)return $;let J=Math.ceil(j8/2),Q=Math.max(1,j8-J);return`${$.slice(0,J)}
439
+ [... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
440
+ `+$.slice(-Q)}function RL($){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,`
441
+ `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(J,Q)=>String.fromCharCode(parseInt(Q,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
434
442
  `).replace(/\n{3,}/g,`
435
443
 
436
- `).trim()}function $4($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:W=!0}=$;return async(j,X,Y)=>{let A;try{A=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(A.protocol))throw Error(`Invalid protocol: ${A.protocol}. Only http and https are supported.`);let V=new AbortController,H=setTimeout(()=>V.abort(),f),B;if(Y.signal)B=()=>V.abort(),Y.signal.addEventListener("abort",B);try{let K=await fetch(j,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:W?"follow":"manual",signal:V.signal});if(clearTimeout(H),!W&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let P=[],F=0;while(!0){let{done:w,value:h}=await R.read();if(w)break;if(F+=h.length,F>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);P.push(h)}let D=new Uint8Array(F),z=0;for(let w of P)D.set(w,z),z+=w.length;let T=new TextDecoder("utf-8").decode(D),L;if(G.includes("text/html")||G.includes("application/xhtml"))L=CU(T);else if(G.includes("application/json"))try{let w=JSON.parse(T);L=JSON.stringify(w,null,2)}catch{L=T}else L=T;let U=[`URL: ${j}`,`Content-Type: ${G}`,`Size: ${F} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)U.push(`
437
- [Content truncated: showing first 50000 of ${L.length} characters]`);return U.push("","--- Analysis Request ---",`Prompt: ${X}`),U.join(`
438
- `)}catch(K){if(clearTimeout(H),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(Y.signal&&B)Y.signal.removeEventListener("abort",B)}}}function Z2($={}){return{readFile:o8($.fileRead),search:e8($.search),bash:a8($.bash),webFetch:$4($.webFetch),applyPatch:n8($.applyPatch),editor:t8($.editor)}}var yU={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"},W2=[{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 YY($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((Q)=>J.includes(Q.toLowerCase()))}function SU($,f,J,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return YY(f,$.providerIdIncludes)&&YY(J,$.modelIdIncludes)}function j2($,f,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!SU(j,$,f,J))continue;for(let X of j.disableTools??[])Z.set(X,!1);for(let X of j.enableTools??[])Z.set(X,!0)}let W={};for(let[j,X]of Z.entries())W[yU[j]]=X;return W}var v0={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 c1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function C6($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let Q of o1)J[Q]=f;return J}function y6($,f){let J=v0[$],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return V$({...W,...f})}import{createTool as hL,zodToJsonSchema as bL}from"@cline/shared";import{z as PZ}from"zod";import{createAgentRuntime as ML}from"@cline/agents";import{createContributionRegistry as TL}from"@cline/shared";import{createGateway as cU,createHandlerAsync as uU,hasRegisteredHandler as dU,MODEL_COLLECTIONS_BY_PROVIDER_ID as lU,normalizeProviderId as pU}from"@cline/llms";import{EMPTY_CONTENT_TEXT as EU}from"@cline/shared";function hU($){let f=kU($.content),J=[],Q=$.id??gU(),Z=0,W=[],j=()=>{if(W.length===0)return;let X=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:X,role:$.role,content:W.map(IU),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:AY($.metrics)}),W=[]};if(f.length===0)return J.push({id:Q,role:$.role,content:[{type:"text",text:EU}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:AY($.metrics)}),J;for(let X of f){if(X.type!=="tool_result"){W.push(X);continue}j(),J.push({id:`${Q}_tool_${X.tool_use_id}`,role:"tool",content:[HY(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function S6($){return $.flatMap(hU)}function bU($){let f=$.content.map(BY).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:xU($.metrics)}}function X2($){return $.map(bU)}function E6($){let f=[];for(let J of $){let Q=J.content.map(BY).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=f[f.length-1];if(Z==="user"&&Q.length>0&&Q.every((j)=>j.type==="tool_result")&&W?.role==="user"&&Array.isArray(W.content)&&W.content.every((j)=>j.type==="tool_result")){W.content.push(...Q);continue}f.push({role:Z,content:Q})}return f}function kU($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function IU($){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 HY($)}}function HY($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function BY($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let f=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:f?.thoughtSignature??f?.signature}}case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function AY($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function xU($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var VY=0;function gU(){return VY+=1,`msg_${Date.now().toString(36)}_${VY.toString(36)}`}function mU($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let f=$.tool_call.function,J=f.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??f.id,toolName:f.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:vU($),error:$.error}];default:return[]}}function vU($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function KY($){return{async*stream(f){let J=!1,Q=!1;try{let Z=typeof $==="function"?await $():$;Z.setAbortSignal?.(f.signal);let W=E6(f.messages),j=f.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of Z.createMessage(f.systemPrompt??"",W,j))for(let Y of mU(X)){if(Y.type==="finish")J=!0;else if(Y.type==="tool-call-delta")Q=!0;yield Y}if(!J)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:f.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function rU($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function iU($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function nU($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(iU($))Object.assign(f,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(f,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return rU(f)}function QZ($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return lU[$.providerId]?.models??void 0}function aU($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function tU($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:aU(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function GY($,f,J){let Q=$.providerConfig,Z=Q?.providerId===$.providerId?Q:void 0,W={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:QZ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};if(dU(pU(W.providerId)))return KY(()=>uU(W));return cU({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,options:nU(W),models:W.knownModels?Object.entries(W.knownModels).map(([j,X])=>tU(j,X)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as FY}from"@cline/shared";var sU=50000,oU=6000000,PY=8000,eU=new Set(["read","read_files","search","search_codebase","bash","run_commands","fetch_web_content"]),$L=new Set(["read","read_files"]),s$="[outdated - see the latest file content]",RY="Tool execution was interrupted before a result was produced.",fL=($)=>`
444
+ `).trim()}function X6($={}){let{timeoutMs:J=30000,maxResponseBytes:Q=5000000,userAgent:Z="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:W={},followRedirects:j=!0}=$;return async(f,X,Y)=>{let V;try{V=new URL(f)}catch{throw Error(`Invalid URL: ${f}`)}if(!["http:","https:"].includes(V.protocol))throw Error(`Invalid protocol: ${V.protocol}. Only http and https are supported.`);let H=new AbortController,B=setTimeout(()=>H.abort(),J),A;if(Y.signal)A=()=>H.abort(),Y.signal.addEventListener("abort",A);try{let K=await fetch(f,{method:"GET",headers:{"User-Agent":Z,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...W},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(B),!j&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let D=[],U=0;while(!0){let{done:P,value:S}=await R.read();if(P)break;if(U+=S.length,U>Q)throw R.cancel(),Error(`Response too large: exceeded ${Q} bytes`);D.push(S)}let F=new Uint8Array(U),O=0;for(let P of D)F.set(P,O),O+=P.length;let T=new TextDecoder("utf-8").decode(F),L;if(G.includes("text/html")||G.includes("application/xhtml"))L=RL(T);else if(G.includes("application/json"))try{let P=JSON.parse(T);L=JSON.stringify(P,null,2)}catch{L=T}else L=T;let z=[`URL: ${f}`,`Content-Type: ${G}`,`Size: ${U} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)z.push(`
445
+ [Content truncated: showing first 50000 of ${L.length} characters]`);return z.push("","--- Analysis Request ---",`Prompt: ${X}`),z.join(`
446
+ `)}catch(K){if(clearTimeout(B),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${J}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(Y.signal&&A)Y.signal.removeEventListener("abort",A)}}}function Y8($={}){return{readFile:j6($.fileRead),search:f6($.search),bash:Q6($.bash),webFetch:X6($.webFetch),applyPatch:Z6($.applyPatch),editor:W6($.editor)}}var zL={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"},V8=[{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 kY($,J){if(!J||J.length===0)return!0;let Q=$.toLowerCase();return J.some((Z)=>Q.includes(Z.toLowerCase()))}function LL($,J,Q,Z){if($.mode&&$.mode!=="any"&&$.mode!==Z)return!1;return kY(J,$.providerIdIncludes)&&kY(Q,$.modelIdIncludes)}function H8($,J,Q,Z){if(!Z||Z.length===0)return{};let W=new Map;for(let f of Z){if(!LL(f,$,J,Q))continue;for(let X of f.disableTools??[])W.set(X,!1);for(let X of f.enableTools??[])W.set(X,!0)}let j={};for(let[f,X]of W.entries())j[zL[f]]=X;return j}var c0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function u1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function g5($){if($!=="yolo")return{};let J={enabled:!0,autoApprove:!0},Q={"*":J};for(let Z of e1)Q[Z]=J;return Q}function m5($,J){let Q=c0[$],{enableSpawnAgent:Z,enableAgentTeams:W,...j}=Q;return B$({...j,...J})}import{createTool as w_,zodToJsonSchema as S_}from"@cline/shared";import{z as C7}from"zod";t0();import{createAgentRuntime as D_}from"@cline/agents";import{createContributionRegistry as U_,mergeModelOptions as aY}from"@cline/shared";import{createGateway as CL,createHandlerAsync as yL,hasRegisteredHandler as EL,MODEL_COLLECTIONS_BY_PROVIDER_ID as bL,normalizeProviderId as hL}from"@cline/llms";import{EMPTY_CONTENT_TEXT as _L}from"@cline/shared";function OL($){let J=ML($.content),Q=[],Z=$.id??NL(),W=0,j=[],f=()=>{if(j.length===0)return;let X=W===0?Z:`${Z}_part_${W}`;W+=1,Q.push({id:X,role:$.role,content:j.map(qL),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:IY($.metrics)}),j=[]};if(J.length===0)return Q.push({id:Z,role:$.role,content:[{type:"text",text:_L}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:IY($.metrics)}),Q;for(let X of J){if(X.type!=="tool_result"){j.push(X);continue}f(),Q.push({id:`${Z}_tool_${X.tool_use_id}`,role:"tool",content:[gY(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return f(),Q}function v5($){return $.flatMap(OL)}function TL($){let J=$.content.map(mY).filter((Q)=>Q!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:J,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:PL($.metrics)}}function B8($){return $.map(TL)}function c5($){let J=[];for(let Q of $){let Z=Q.content.map(mY).filter((f)=>f!==void 0),W=Q.role==="tool"?"user":Q.role,j=J[J.length-1];if(W==="user"&&Z.length>0&&Z.every((f)=>f.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((f)=>f.type==="tool_result")){j.content.push(...Z);continue}J.push({role:W,content:Z})}return J}function ML($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function qL($){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 gY($)}}function gY($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function mY($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let J=$.metadata;return{type:"thinking",thinking:$.text,signature:J?.signature,details:J?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let J=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:J?.thoughtSignature??J?.signature}}case"tool-result":{let J=$.output,Q=typeof J==="string"?J:Array.isArray(J)?J:JSON.stringify(J);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Q,is_error:$.isError}}}}function IY($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function PL($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var xY=0;function NL(){return xY+=1,`msg_${Date.now().toString(36)}_${xY.toString(36)}`}function wL($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let J=$.tool_call.function,Q=J.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??J.id,toolName:J.name,inputText:typeof Q==="string"?Q:void 0,input:typeof Q==="string"?void 0:Q,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:SL($),error:$.error}];default:return[]}}function SL($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function vY($){return{async*stream(J){let Q=!1,Z=!1;try{let W=typeof $==="function"?await $():$;W.setAbortSignal?.(J.signal);let j=c5(J.messages),f=J.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of W.createMessage(J.systemPrompt??"",j,f))for(let Y of wL(X)){if(Y.type==="finish")Q=!0;else if(Y.type==="tool-call-delta")Z=!0;yield Y}if(!Q)yield{type:"finish",reason:Z?"tool-calls":"stop"}}catch(W){if(!Q)yield{type:"finish",reason:J.signal?.aborted?"aborted":"error",error:W instanceof Error?W.message:String(W)}}}}}function kL($){let J=Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0));return Object.keys(J).length>0?J:void 0}function IL($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function xL($){let J={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(IL($))Object.assign(J,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(J,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Q=$.gcp?.region??$.region;Object.assign(J,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Q,region:Q})}return kL(J)}function U7($){let J=$.providerConfig;if(J?.knownModels)return J.knownModels;if($.knownModels)return $.knownModels;return bL[$.providerId]?.models??void 0}function gL($){if(!$?.length)return;let J=new Set;for(let Q of $)switch(Q){case"tools":case"reasoning":case"prompt-cache":case"images":J.add(Q);break;case"structured_output":J.add("structured-output");break;default:J.add("text")}return J.add("text"),[...J]}function mL($,J){return{id:$,name:J.name??$,description:J.description,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxOutputTokens:J.maxTokens,capabilities:gL(J.capabilities),metadata:{family:J.family,pricing:J.pricing,status:J.status,releaseDate:J.releaseDate}}}function cY($,J,Q){let Z=$.providerConfig,W=Z?.providerId===$.providerId?Z:void 0,j={...W??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.headers??W?.headers,knownModels:U7($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:J,extensionContext:$.extensionContext};if(EL(hL(j.providerId)))return vY(()=>yL(j));return CL({providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,options:xL(j),models:j.knownModels?Object.entries(j.knownModels).map(([f,X])=>mL(f,X)):void 0}],logger:J,telemetry:Q??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens})}import{createMediaBudgetState as vL,IMAGE_OMITTED_PLACEHOLDER as uY,normalizeUserInput as dY,resolveMediaBudget as cL,validateAndReserveImageMedia as uL}from"@cline/shared";var dL=50000,lL=6000000,lY=8000,pL=new Set(["read","read_files","search","search_codebase","bash","run_commands","fetch_web_content"]),rL=new Set(["read","read_files"]),o$="[outdated - see the latest file content]",pY="Tool execution was interrupted before a result was produced.",iL=($)=>`
439
447
 
440
448
  ...[truncated ${$} chars]...
441
449
 
442
- `,JL=($)=>`
450
+ `,nL=($)=>`
443
451
 
444
452
  ...[truncated ${$} chars to fit provider request budget]...
445
453
 
446
- `;class YZ{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=sU,f=eU,J=oU){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((Q)=>{if(!Array.isArray(Q.content)){if(Q.role==="user"&&typeof Q.content==="string"){let j=FY(Q.content);if(j!==Q.content)return{...Q,content:j}}return Q}let Z=!1,W=Q.content.map((j)=>{let X=this.transformBlock(j,Q.role);if(X!==j)Z=!0;return X});return Z?{...Q,content:W}:Q});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=FY($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),Q=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===$.content?$:{...$,content:Q}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let Q=$[J];if(!Array.isArray(Q.content))continue;for(let Z=0;Z<Q.content.length;Z++){let W=Q.content[Z];if(W.type==="file")this.latestFullContentOwnerByPathCache.set(W.path,`file:${J}:${Z}`);else if(W.type==="tool_use"){let j=W.name.toLowerCase();if(this.toolNameByIdCache.set(W.id,j),this.isReadTool(j)){let X=this.extractLocatorsFromReadToolInput(W.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(W.id,X)}}else if(W.type==="tool_result"){let j=this.toolNameByIdCache.get(W.tool_use_id);if(!this.isReadTool(j)||W.is_error===!0)continue;let X=this.getReadLocators(W);for(let Y of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(Y),W.tool_use_id),this.isFullFileRead(Y))this.latestFullContentOwnerByPathCache.set(Y.path,W.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(X)=>{let Y=J.at(-1);if(this.shouldMergeUserAfterToolResults(Y,X)){J[J.length-1]={...Y,content:[...Y.content,...this.contentBlocksForUserMerge(X.content)]},Z=!0;return}J.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(j(this.appendMissingToolResults(X,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(X.content)){let Y=X.content.filter((V)=>V.type==="tool_result"),A=X.content.filter((V)=>V.type!=="tool_result");if(Y.length>0){let V=this.appendMissingToolResults({...X,role:"user",content:Y},Q);if(j(V),Q.size>0)Q.clear();Z=!0}if(A.length>0||Y.length===0){if(Y.length===0)W();let V=Y.length>0?{...X,content:A}:X;if(j(V),V.role==="assistant")this.trackMissingToolCalls(V,f,Q)}continue}W(),j(X)}return W(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content)if(Q.type==="tool_result")f.add(Q.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||f.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${RY} Tool: ${$}.`:RY}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],Q=this.extractLocatorFromReadRequest(f);if(Q)J.push(Q);if(Array.isArray(f.files))for(let Z of f.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let Q of $){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((W)=>this.toReadLocatorKey(W))),Q=new Set(f.map((W)=>W.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??s$;let Z=0;for(let W of $)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return $.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:s$}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:s$}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:s$};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let Q=Array.isArray(J)?J:[J],Z=0;for(let W of Q){if(!W||typeof W!=="object")continue;let j=W,X=this.extractLocatorFromResultEntry(j);if(!X)continue;if(!f.has(this.toReadLocatorKey(X)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(Q)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=s$;else if(typeof Q.content==="string")Q.content=s$;else Q.result=s$;return Q}isReadTool($){return!!$&&$L.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let J=this.truncateMiddle(f.content);return J===f.content?f:{...f,content:J}}if(f.type==="text"){let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}}if(h6(f))return this.truncateNestedStrings(f);return f})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let f=!1,J=$.map((Q)=>{let Z=this.truncateNestedStrings(Q);if(Z!==Q)f=!0;return Z});return f?J:$}if($!==null&&typeof $==="object"){if(AZ($))return $;let f=!1,J={};for(let[Q,Z]of Object.entries($)){let W=this.truncateNestedStrings(Z);if(W!==Z)f=!0;J[Q]=W}return f?J:$}return $}truncateMiddle($){return ZZ($,this.maxToolResultChars,fL)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>ZL(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if(f<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=PY)continue;let j=f-this.maxTotalTextBytes,X=Math.max(PY,W-j),Y=QL(Z.get(),X,JL);Z.set(Y),f-=W-P0(Y)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=P0(J.content);continue}for(let Q of J.content)if(Q.type==="text")f+=P0(Q.text);else if(Q.type==="thinking")f+=P0(Q.thinking);else if(Q.type==="file")f+=P0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")f+=P0(Q.content);else for(let Z of Q.content)if(Z.type==="text")f+=P0(Z.text);else if(Z.type==="file")f+=P0(Z.content);else if(h6(Z))f+=WZ(Z)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof Q.content==="string"){f.push({byteLength:P0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")f.push({byteLength:P0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")f.push({byteLength:P0(W.content),get:()=>W.content,set:(j)=>{W.content=j}});else if(h6(W))jZ(W,f)}}return f.sort((J,Q)=>Q.byteLength-J.byteLength)}}function P0($){return Buffer.byteLength($,"utf8")}function ZZ($,f,J){if($.length<=f)return $;let Q=J($.length-f),Z=Math.max(0,Math.floor((f-Q.length)/2)),W=Math.max(0,$.length-Z*2),j=J(W),X=Math.max(0,Math.floor((f-j.length)/2)),Y=$.slice(0,X),A=X>0?$.slice(-X):"";return`${Y}${j}${A}`}function QL($,f,J){if(P0($)<=f)return $;let Q=0,Z=$.length,W=ZZ($,0,J);while(Q<=Z){let j=Q+Z>>>1,X=ZZ($,j,J);if(P0(X)<=f)W=X,Q=j+1;else Z=j-1}return W}function ZL($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>h6(f)?XZ(f):{...f})}}function h6($){if($===null||typeof $!=="object")return!1;let f=$.type;return f!=="text"&&f!=="image"&&f!=="file"}function AZ($){return $.type==="image"}function WZ($){if(typeof $==="string")return P0($);if(Array.isArray($)){let f=0;for(let J of $)f+=WZ(J);return f}if($!==null&&typeof $==="object"){if(AZ($))return 0;let f=0;for(let J of Object.values($))f+=WZ(J);return f}return 0}function jZ($,f){if(Array.isArray($)){$.forEach((J,Q)=>{if(typeof J==="string")f.push({byteLength:P0(J),get:()=>$[Q],set:(Z)=>{$[Q]=Z}});else jZ(J,f)});return}if($!==null&&typeof $==="object"){if(AZ($))return;let J=$;for(let Q of Object.keys(J)){let Z=J[Q];if(typeof Z==="string")f.push({byteLength:P0(Z),get:()=>J[Q],set:(W)=>{J[Q]=W}});else jZ(Z,f)}}}function XZ($){if(Array.isArray($))return $.map(XZ);if($!==null&&typeof $==="object"){let f={};for(let[J,Q]of Object.entries($))f[J]=XZ(Q);return f}return $}function VZ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class HZ{messages=[];conversationId=VZ();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=VZ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=VZ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function DY($){let{agentConfig:f}=$,J=WL(f),Q=jL(f),Z=$.hooks,W=XL(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:W,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function WL($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function jL($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function XL($){if($===void 0)return;return $>=2?"parallel":"sequential"}function YL(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function AL($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function BZ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(BZ);let f={};for(let J of Object.keys($).sort())f[J]=BZ($[J]);return f}function VL($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(BZ($))}catch{return String($)}}function HL($,f,J,Q){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var UY={softThreshold:3,hardThreshold:5};class KZ{config;state=YL();constructor($){this.config={softThreshold:$?.softThreshold??UY.softThreshold,hardThreshold:$?.hardThreshold??UY.hardThreshold}}inspect($){let f=VL($.input),J=HL(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){AL(this.state)}}class GZ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await KL({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:BL({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function BL($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let Q=$.stopReason?.trim();if(Q)f.push(`Decision: ${Q}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function KL($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function GL($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function FL($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function PL($){return $.content.find((f)=>f.type==="tool-result")}function RL($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function DL($){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 FZ{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let f=[],J=GL($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let Q=FL($);if(Q!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=PL($.message),Z=Q?.output,W=DL(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,X=($.totalCost??0)-W;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:RL($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function NL($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function qL($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function wL($,f){let J=$.trim(),Q=f.map((Z)=>Z.trim()).filter(Boolean).join(`
454
+ `;class O7{maxToolResultChars;targetToolNames;maxTotalTextBytes;mediaBudget;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=dL,J=pL,Q=lL,Z={}){this.maxToolResultChars=$;this.targetToolNames=J;this.maxTotalTextBytes=Q;this.mediaBudget=Z}buildForApi($){this.reindex($);let Q=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let X=dY(W.content);if(X!==W.content)return{...W,content:X}}return W}let j=!1,f=W.content.map((X)=>{let Y=this.transformBlock(X,W.role);if(Y!==X)j=!0;return Y});return j?{...W,content:f}:W}),Z=this.applyMediaBudget(Q);return this.truncateToTotalTextBudget(Z)}transformBlock($,J){if(J==="user"&&$.type==="text"&&typeof $.text==="string"){let W=dY($.text);if(W!==$.text)return{...$,text:W};return $}if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="tool_result")return $;let Q=this.toolNameByIdCache.get($.tool_use_id),Z=$.content;if(this.isReadTool(Q)&&$.is_error!==!0){let W=this.getReadLocators($);if(W.length>0){let j=W.filter((f)=>this.isOutdatedReadLocator(f,$.tool_use_id));if(j.length>0)Z=this.replaceOutdatedReadContent(Z,j)}}if(this.shouldTruncateTool(Q))Z=this.truncateToolResultContent(Z);return Z===$.content?$:{...$,content:Z}}reindex($){let J=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!J)this.resetIndexes();for(let Q=this.indexedMessageCount;Q<$.length;Q++){let Z=$[Q];if(!Array.isArray(Z.content))continue;for(let W=0;W<Z.content.length;W++){let j=Z.content[W];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Q}:${W}`);else if(j.type==="tool_use"){let f=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,f),this.isReadTool(f)){let X=this.extractLocatorsFromReadToolInput(j.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(j.id,X)}}else if(j.type==="tool_result"){let f=this.toolNameByIdCache.get(j.tool_use_id);if(!this.isReadTool(f)||j.is_error===!0)continue;let X=this.getReadLocators(j);for(let Y of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(Y),j.tool_use_id),this.isFullFileRead(Y))this.latestFullContentOwnerByPathCache.set(Y.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let J=this.collectToolResultIds($),Q=[],Z=new Map,W=!1,j=()=>{if(Z.size===0)return;f(this.createMissingToolResultMessage(Z)),Z.clear(),W=!0},f=(X)=>{let Y=Q.at(-1);if(this.shouldMergeUserAfterToolResults(Y,X)){Q[Q.length-1]={...Y,content:[...Y.content,...this.contentBlocksForUserMerge(X.content)]},W=!0;return}Q.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(f(this.appendMissingToolResults(X,Z)),Z.size>0)Z.clear(),W=!0;continue}if(Array.isArray(X.content)){let Y=X.content.filter((H)=>H.type==="tool_result"),V=X.content.filter((H)=>H.type!=="tool_result");if(Y.length>0){let H=this.appendMissingToolResults({...X,role:"user",content:Y},Z);if(f(H),Z.size>0)Z.clear();W=!0}if(V.length>0||Y.length===0){if(Y.length===0)j();let H=Y.length>0?{...X,content:V}:X;if(f(H),H.role==="assistant")this.trackMissingToolCalls(H,J,Z)}continue}j(),f(X)}return j(),W?Q:$}appendMissingToolResults($,J){if(J.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(J)]}}shouldMergeUserAfterToolResults($,J){return $?.role==="user"&&J.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(J.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let J=new Set;for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content)if(Z.type==="tool_result")J.add(Z.tool_use_id)}return J}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((J)=>J.type==="tool_result")}trackMissingToolCalls($,J,Q){if(!Array.isArray($.content))return;for(let Z of $.content){if(Z.type!=="tool_use"||J.has(Z.id))continue;Q.set(Z.id,Z.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([J,Q])=>({type:"tool_result",tool_use_id:J,name:Q,content:[{type:"text",text:this.formatMissingToolResultText(Q)}],is_error:!0}))}formatMissingToolResultText($){return $?`${pY} Tool: ${$}.`:pY}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let J=$,Q=this.readResultLocatorCache.get(J);if(Q===void 0)Q=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(J,Q);if(Q.length>0)return Q;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let J=$,Q=[],Z=this.extractLocatorFromReadRequest(J);if(Z)Q.push(Z);if(Array.isArray(J.files))for(let W of J.files){let j=this.extractLocatorFromReadRequest(W);if(j)Q.push(j)}if(Array.isArray(J.file_paths)){for(let W of J.file_paths)if(typeof W==="string"&&W.length>0)Q.push({path:W,startLine:null,endLine:null})}return this.dedupeReadLocators(Q)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let J of $){if(J.type!=="text")continue;let Q=this.tryParseReadLocators(J.text);if(Q.length>0)return Q}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Q=[];for(let Z of $){let W=this.extractLocatorFromResultEntry(Z);if(W)Q.push(W)}return this.dedupeReadLocators(Q)}let J=this.extractLocatorFromResultEntry($);return J?[J]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(!Q)return;return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(Q)return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)};if(typeof J.query==="string"&&J.query.length>0)return this.parseReadQuery(J.query);return}extractPath($){let J=[$.path,$.file_path,$.filePath];for(let Q of J)if(typeof Q==="string"&&Q.length>0)return Q;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let J=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!J)return{path:$,startLine:null,endLine:null};return{path:J[1],startLine:Number(J[2]),endLine:J[3]==="EOF"?null:Number(J[3])}}dedupeReadLocators($){let J=new Map;for(let Q of $)J.set(this.toReadLocatorKey(Q),Q);return Array.from(J.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,J){let Q=this.latestFullContentOwnerByPathCache.get($.path);if(Q&&Q!==J)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==J}replaceOutdatedReadContent($,J){let Q=new Set(J.map((j)=>this.toReadLocatorKey(j))),Z=new Set(J.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Q)??o$;let W=0;for(let j of $)if(j.type==="text")W+=this.countOutdatedImageEntries(j.text,Q);return $.map((j)=>{if(j.type==="file"){if(!Z.has(j.path))return j;return{...j,content:o$}}if(j.type==="image"){if(W===0)return j;return W-=1,{type:"text",text:o$}}if(j.type!=="text")return j;let f=this.replaceOutdatedInString(j.text,Q);if(f===null)return{...j,text:o$};return f===j.text?j:{...j,text:f}})}countOutdatedImageEntries($,J){let Q;try{Q=JSON.parse($)}catch{return 0}let Z=Array.isArray(Q)?Q:[Q],W=0;for(let j of Z){if(!j||typeof j!=="object")continue;let f=j,X=this.extractLocatorFromResultEntry(f);if(!X)continue;if(!J.has(this.toReadLocatorKey(X)))continue;if(f.result==="Successfully read image"||f.content==="Successfully read image")W+=1}return W}replaceOutdatedInString($,J){let Q;try{Q=JSON.parse($)}catch{return null}let Z=Array.isArray(Q)?Q.map((W)=>this.replaceOutdatedReadEntry(W,J)):this.replaceOutdatedReadEntry(Q,J);return JSON.stringify(Z)}replaceOutdatedReadEntry($,J){if(!$||typeof $!=="object")return $;let Q=this.extractLocatorFromResultEntry($);if(!Q||!J.has(this.toReadLocatorKey(Q)))return $;let Z={...$};if(typeof Z.result==="string")Z.result=o$;else if(typeof Z.content==="string")Z.content=o$;else Z.result=o$;return Z}isReadTool($){return!!$&&rL.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((J)=>{if(J.type==="file"){let Q=this.truncateMiddle(J.content);return Q===J.content?J:{...J,content:Q}}if(J.type==="text"){let Q=this.truncateMiddle(J.text);return Q===J.text?J:{...J,text:Q}}if(Y6(J))return this.truncateNestedStrings(J);return J})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let J=!1,Q=$.map((Z)=>{let W=this.truncateNestedStrings(Z);if(W!==Z)J=!0;return W});return J?Q:$}if($!==null&&typeof $==="object"){if(u5($))return $;let J=!1,Q={};for(let[Z,W]of Object.entries($)){let j=this.truncateNestedStrings(W);if(j!==W)J=!0;Q[Z]=j}return J?Q:$}return $}truncateMiddle($){return R7($,this.maxToolResultChars,iL)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let J=this.countMessageTextBytes($);if(J<=this.maxTotalTextBytes)return $;let Q=$.map((W)=>{if(!Array.isArray(W.content))return W;return{...W,content:W.content.map((j)=>sL(j))}}),Z=this.collectTruncationCandidates(Q);for(let W of Z){if(J<=this.maxTotalTextBytes)break;let j=W.byteLength;if(j<=lY)continue;let f=J-this.maxTotalTextBytes,X=Math.max(lY,j-f),Y=aL(W.get(),X,nL);W.set(Y),J-=j-U0(Y)}return Q}countMessageTextBytes($){let J=0;for(let Q of $){if(typeof Q.content==="string"){J+=U0(Q.content);continue}for(let Z of Q.content)if(Z.type==="text")J+=U0(Z.text);else if(Z.type==="thinking")J+=U0(Z.thinking);else if(Z.type==="file")J+=U0(Z.content);else if(Z.type==="tool_result"){if(typeof Z.content==="string")J+=U0(Z.content);else for(let W of Z.content)if(W.type==="text")J+=U0(W.text);else if(W.type==="file")J+=U0(W.content);else if(Y6(W))J+=z7(W)}}return J}collectTruncationCandidates($){let J=[];for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content){if(Z.type!=="tool_result")continue;let W=this.toolNameByIdCache.get(Z.tool_use_id);if(!this.shouldTruncateTool(W))continue;if(typeof Z.content==="string"){J.push({byteLength:U0(Z.content),get:()=>Z.content,set:(j)=>{Z.content=j}});continue}for(let j of Z.content)if(j.type==="text")J.push({byteLength:U0(j.text),get:()=>j.text,set:(f)=>{j.text=f}});else if(j.type==="file")J.push({byteLength:U0(j.content),get:()=>j.content,set:(f)=>{j.content=f}});else if(Y6(j))L7(j,J)}}return J.sort((Q,Z)=>Z.byteLength-Q.byteLength)}applyMediaBudget($){let J=this.resolveMediaBudget();if(J.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&J.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&J.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Q=vL(),Z=!1,W=$.map((j)=>{if(!Array.isArray(j.content))return j;let f=!1,X=j.content.map((Y)=>{let V=this.applyMediaBudgetToBlock(Y,J,Q);if(V!==Y)f=!0;return V});if(!f)return j;return Z=!0,{...j,content:X}});return Z?W:$}resolveMediaBudget(){return cL(this.mediaBudget)}applyMediaBudgetToBlock($,J,Q){if(u5($))return this.limitImageContent($,J,Q);if($.type!=="tool_result"||typeof $.content==="string")return $;let Z=!1,W=$.content.map((j)=>{let f=this.applyMediaBudgetToToolResultEntry(j,J,Q);if(f!==j)Z=!0;return f});return Z?{...$,content:W}:$}applyMediaBudgetToToolResultEntry($,J,Q){if(u5($))return this.limitImageContent($,J,Q);if(Y6($))return this.limitNestedMedia($,J,Q);return $}limitNestedMedia($,J,Q){if(u5($)){let Z=this.limitImageContent($,J,Q);return Z.type==="text"?Z.text:Z}if(Array.isArray($)){let Z=!1,W=$.map((j)=>{let f=this.limitNestedMedia(j,J,Q);if(f!==j)Z=!0;return f});return Z?W:$}if($!==null&&typeof $==="object"){let Z=!1,W={};for(let[j,f]of Object.entries($)){let X=this.limitNestedMedia(f,J,Q);if(X!==f)Z=!0;W[j]=X}return Z?W:$}return $}limitImageContent($,J,Q){if(!T7($))return{type:"text",text:uY};let Z=uL($.mediaType,$.data,{maxImageEncodedBytes:J.maxImageEncodedBytes,maxImageDecodedBytes:J.maxImageDecodedBytes,maxTotalMediaBytes:J.maxTotalMediaBytes},Q);if(!Z.ok)return{type:"text",text:uY};return{...$,data:Z.base64,mediaType:Z.mediaType}}}function U0($){return Buffer.byteLength($,"utf8")}function R7($,J,Q){if($.length<=J)return $;let Z=Q($.length-J),W=Math.max(0,Math.floor((J-Z.length)/2)),j=Math.max(0,$.length-W*2),f=Q(j),X=Math.max(0,Math.floor((J-f.length)/2)),Y=$.slice(0,X),V=X>0?$.slice(-X):"";return`${Y}${f}${V}`}function aL($,J,Q){if(U0($)<=J)return $;let Z=0,W=$.length,j=R7($,0,Q);while(Z<=W){let f=Z+W>>>1,X=R7($,f,Q);if(U0(X)<=J)j=X,Z=f+1;else W=f-1}return j}function sL($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((J)=>Y6(J)?_7(J):{...J})}}function Y6($){if($===null||typeof $!=="object")return!1;let J=$.type;return J!=="text"&&J!=="image"&&J!=="file"}function u5($){return $!==null&&typeof $==="object"&&$.type==="image"}function T7($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function z7($){if(typeof $==="string")return U0($);if(Array.isArray($)){let J=0;for(let Q of $)J+=z7(Q);return J}if($!==null&&typeof $==="object"){if(T7($))return 0;let J=0;for(let Q of Object.values($))J+=z7(Q);return J}return 0}function L7($,J){if(Array.isArray($)){$.forEach((Q,Z)=>{if(typeof Q==="string")J.push({byteLength:U0(Q),get:()=>$[Z],set:(W)=>{$[Z]=W}});else L7(Q,J)});return}if($!==null&&typeof $==="object"){if(T7($))return;let Q=$;for(let Z of Object.keys(Q)){let W=Q[Z];if(typeof W==="string")J.push({byteLength:U0(W),get:()=>Q[Z],set:(j)=>{Q[Z]=j}});else L7(W,J)}}}function _7($){if(Array.isArray($))return $.map(_7);if($!==null&&typeof $==="object"){let J={};for(let[Q,Z]of Object.entries($))J[Q]=_7(Z);return J}return $}function M7(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class q7{messages=[];conversationId=M7();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=M7(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=M7(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function rY($){let{agentConfig:J}=$,Q=oL(J),Z=tL(J),W=$.hooks,j=eL(J.maxParallelToolCalls);return{sessionId:$.sessionId??J.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??J.systemPrompt,messageModelInfo:Z,model:$.model,modelOptions:Q,tools:$.tools,hooks:W,prepareTurn:$.prepareTurn,consumePendingUserMessage:J.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??J.logger,telemetry:$.telemetry??J.telemetry,initialMessages:$.initialMessages,completionPolicy:J.completionPolicy,maxIterations:J.maxIterations,toolExecution:j,toolPolicies:J.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:J.requestToolApproval}}function oL($){let J={};if($.thinking!==void 0)J.thinking=$.thinking;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)J.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)J.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(J).length>0?J:void 0}function tL($){let J=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:J}}function eL($){if($===void 0)return;return $>=2?"parallel":"sequential"}function $_(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function J_($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function P7($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(P7);let J={};for(let Q of Object.keys($).sort())J[Q]=P7($[Q]);return J}function Q_($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(P7($))}catch{return String($)}}function Z_($,J,Q,Z){if(J===$.lastToolName&&Q===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=J,$.lastToolSignature=Q,{softWarning:$.consecutiveIdenticalCount===Z.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Z.hardThreshold}}var iY={softThreshold:3,hardThreshold:5};class N7{config;state=$_();constructor($){this.config={softThreshold:$?.softThreshold??iY.softThreshold,hardThreshold:$?.hardThreshold??iY.hardThreshold}}inspect($){let J=Q_($.input),Q=Z_(this.state,$.name,J,this.config);if(Q.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Q.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){J_(this.state)}}class w7{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let J=this.options.maxConsecutiveMistakes,Q=$.forceAtLimit&&J?J:this.consecutiveMistakes+1;this.consecutiveMistakes=Q;let Z=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Z),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Q,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!J||Q<J)return{action:"continue"};let W=await j_({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details},this.options.onLimitReached);if(W.action==="continue"){let j=W.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:W.reason?.trim()||void 0,message:W_({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details,stopReason:W.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function W_($){let J=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Q=$.details?.trim();if(Q)J.push(`Error: ${Q}`);let Z=$.stopReason?.trim();if(Z)J.push(`Decision: ${Z}`);return J.push("Session state was preserved. Send a new prompt to resume from the latest state."),J.join(" ")}async function j_($,J){if(!J)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await J($)}catch(Q){return{action:"stop",reason:Q instanceof Error?Q.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function f_($){let J=$.content.filter((Q)=>Q.type==="text");if(J.length===0)return;return J.map((Q)=>Q.text).join("")}function X_($){let J=$.content.filter((Q)=>Q.type==="reasoning");if(J.length===0)return;return{reasoning:J.map((Q)=>Q.text).join(""),redacted:J.some((Q)=>Q.redacted===!0)}}function Y_($){return $.content.find((J)=>J.type==="tool-result")}function V_($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function H_($){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 S7{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let J=[],Q=f_($);if(Q!==void 0)J.push({type:"content_end",contentType:"text",text:Q});let Z=X_($);if(Z!==void 0)J.push({type:"content_end",contentType:"reasoning",reasoning:Z.reasoning});return J}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let J=this.toolStartedAt.get($.toolCall.toolCallId),Q=J===void 0?void 0:Date.now()-J;this.toolStartedAt.delete($.toolCall.toolCallId);let Z=Y_($.message),W=Z?.output,j=H_(Z);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:W,error:j,durationMs:Q}]}translateUsage($){let J=$.inputTokens-this.lastUsage.inputTokens,Q=$.outputTokens-this.lastUsage.outputTokens,Z=$.cacheReadTokens-this.lastUsage.cacheReadTokens,W=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,X=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,J),outputTokens:Math.max(0,Q),cacheReadTokens:Z===0?void 0:Math.max(0,Z),cacheWriteTokens:W===0?void 0:Math.max(0,W),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let J={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:V_($.status),text:$.outputText,iterations:$.iterations,usage:J}]}}function R_($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function z_($){let Q=(typeof $.content==="function"?await $.content():$.content).trim();return Q.length>0?Q:void 0}function L_($,J){let Q=$.trim(),Z=J.map((W)=>W.trim()).filter(Boolean).join(`
447
455
 
448
- `);if(J&&Q)return`${J}
456
+ `);if(Q&&Z)return`${Q}
449
457
 
450
- ${Q}`;return J||Q}function CL($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let Q of f){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of f)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of f){let j=await W.beforeModel?.({...J,request:Q});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},Q={...Q,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...Q.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let Q of f){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of f){let j=await W.beforeTool?.({...J,input:Q});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))Q=j.input}return Z},afterTool:async(J)=>{let Q=J.result,Z;for(let W of f){let j=await W.afterTool?.({...J,result:Q});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)Q=j.result}return Z},onEvent:async(J)=>{for(let Q of f)await Q.onEvent?.(J)}}}class B${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 FZ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??ML,this.conversation=new HZ($.initialMessages),this.messageBuilder=new YZ,this.contributionRegistry=TL({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new GZ({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,X)=>yL(this.logger,W,j,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(W,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:W}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new KZ(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of $)if(!f.has(Q.name))J.push(Q),f.add(Q.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await qL(f);if(J)$.push(J)}return wL(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let F=await EL(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Q=await this.composeSystemPrompt(),Z=GY(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let F of W)j.set(F.name,F);for(let F of this.config.tools)j.set(F.name,F);let X=this.conversation.getConversationId(),Y=_Y(this.config),A=Array.from(j.values()),V=S6(this.conversation.getMessages()),H=DY({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:X,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:A,toolContextMetadata:{modelSupportsImages:Y?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[IX]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(Y,A),initialMessages:V,systemPrompt:Q}),B=this.createAgentRuntimeImpl(H);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),G,R;try{if($.isContinue)G=await B.continue(void 0);else G=await B.run("")}catch(F){R=F instanceof Error?F:Error(String(F))}finally{K();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(G&&G.messages.length>0){let F=X2(G.messages);this.conversation.replaceMessages(F)}let P=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:P})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=CL([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let Q=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(Q);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(Q)=>{let Z=X2(Q.messages),W=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:Z,apiMessages:W,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:S6(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(E6($));return S6(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)f=await Q.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((Y)=>Y.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?NL(Z?.type==="tool-result"?Z.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(X),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(X2($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=X2(f).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:f});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:Q,endedAt:Z}=$,W=Z.getTime()-Q.getTime(),j=J?"error":SL(f),X=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",Y=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,A=f?X2(f.messages):this.conversation.getMessages(),V=_Y(this.config);if(J)throw J;return{text:X,usage:Y,messages:A,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:V},startedAt:Q,endedAt:Z,durationMs:W}}}function yL($,f,J,Q){if(!$)return;if(f==="debug"){$.debug(J,Q);return}if(f==="error"&&$.error){$.error(J,Q);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...Q,severity:Z})}function SL($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function EL($,f,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => LY);return Z($,f,J,Q)}function _Y($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=QZ($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as zY}from"@cline/shared";function OY($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return zY({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
451
- ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function MY($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return zY({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function K$($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function o$($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?OY($.prompt,f):MY($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function G$($){let f=o$($),J=new B$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var kL=PZ.object({systemPrompt:PZ.string().describe("System prompt defining the sub-agent's behavior"),task:PZ.string().describe("Task for the sub-agent to complete")});function F$($){return hL({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:bL(kL),execute:async(f,J)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=G$({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),X=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:X,input:f})}catch{}try{let Y=await Z.run(f.task),A={text:Y.text,iterations:Y.iterations,finishReason:Y.finishReason,usage:{inputTokens:Y.usage.inputTokens,outputTokens:Y.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,result:A,agentResult:Y})}catch{}return A}catch(Y){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,error:Y instanceof Error?Y:Error(String(Y))})}catch{}throw Y}},timeoutMs:300000,retryable:!1})}import{createTool as j0,TEAM_AWAIT_TIMEOUT_MS as IL,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as xL,TEAM_RUN_TEXT_PREVIEW_LIMIT as gL,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as mL,TeamAttachOutcomeFragmentInputSchema as TY,TeamAwaitRunsInputSchema as NY,TeamBroadcastInputSchema as qY,TeamBroadcastToolResultSchema as vL,TeamCancelRunInputSchema as wY,TeamCancelRunToolResultSchema as cL,TeamCleanupInputSchema as CY,TeamCleanupToolResultSchema as uL,TeamCreateOutcomeInputSchema as yY,TeamCreateOutcomeToolResultSchema as dL,TeamFinalizeOutcomeInputSchema as SY,TeamFinalizeOutcomeToolResultSchema as lL,TeamListOutcomesInputSchema as EY,TeamListRunsInputSchema as hY,TeamMailboxMessageToolResultSchema as pL,TeamMissionLogInputSchema as bY,TeamMissionLogToolResultSchema as rL,TeamOutcomeFragmentToolResultSchema as kY,TeamOutcomeToolResultSchema as iL,TeamReadMailboxInputSchema as IY,TeamReviewOutcomeFragmentInputSchema as xY,TeamRunTaskInputSchema as gY,TeamRunTaskToolResultSchema as RZ,TeamRunToolSummarySchema as DZ,TeamSendMessageInputSchema as mY,TeamSendMessageToolResultSchema as nL,TeamShutdownTeammateInputSchema as vY,TeamSimpleAgentStatusToolResultSchema as cY,TeamSpawnTeammateInputSchema as uY,TeamStatusInputSchema as dY,TeamStatusToolResultSchema as aL,TeamTaskInputSchema as lY,TeamTaskToolResultSchema as f4,validateWithZod as b,zodToJsonSchema as X0}from"@cline/shared";function pY($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function e$($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function tL($){let f=$.result;if(!f)return;return{textPreview:pY(f.text,gL),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function b6($){return $?.toISOString()}function UZ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:pY($.message,xL),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:b6($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:b6($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:b6($.heartbeatAt),lastProgressAt:b6($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:tL($)}}function sL($){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 Y2=["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 rY($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...$f({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:o$({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function A2($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,Q=$f({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let W of $.restoredTeammates??[]){if($.runtime.isTeammateActive(W.agentId))continue;rY({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function $f($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,Z=[];if(J)Z.push(j0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:X0(uY),execute:async(j)=>{let X=b(uY,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let Y={agentId:X.agentId,rolePrompt:X.rolePrompt};if(rY({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Y}),!Q)$.onLeadToolsUnlocked?.($f({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(cY,{agentId:X.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(j0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:X0(vY),execute:async(j)=>{let X=b(vY,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),b(cY,{agentId:X.agentId,status:"stopped"})}})),Z.push(j0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:X0(dY),execute:async(j)=>{return b(dY,j),b(aL,$.runtime.getSnapshot())}})),Z.push(j0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:X0(lY),execute:async(j)=>{let X=b(lY,j);switch(X.action){case"create":{let Y=new Set(mL.create??[]),A=Object.entries(j).filter(([H,B])=>Y.has(H)&&B!=null).map(([H])=>H),V=$.runtime.createTask({title:e$(X.title,"title"),description:e$(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return b(f4,{action:"create",taskId:V.id,status:V.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return b(f4,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let Y=$.runtime.claimTask(e$(X.taskId,"taskId"),$.requesterId);return b(f4,{action:"claim",taskId:Y.id,status:Y.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let Y=$.runtime.completeTask(e$(X.taskId,"taskId"),$.requesterId,e$(X.summary,"summary"));return b(f4,{action:"complete",taskId:Y.id,status:Y.status})}case"block":{let Y=$.runtime.blockTask(e$(X.taskId,"taskId"),$.requesterId,e$(X.reason,"reason"));return b(f4,{action:"block",taskId:Y.id,status:Y.status})}}}}));let W=new Map;return Z.push(j0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:X0(gY),execute:async(j)=>{let X=b(gY,j);if(X.runMode==="async"){let V=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return b(RZ,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${V.id}.`,runId:V.id})}let Y=W.get(X.agentId);if(Y){let V=await Y;return b(RZ,{...V,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((V)=>b(RZ,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:V.text,iterations:V.iterations})).finally(()=>{W.delete(X.agentId)});return W.set(X.agentId,A),await A}})),Z.push(j0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:X0(wY),execute:async(j)=>{let X=b(wY,j),Y=$.runtime.cancelRun(X.runId,X.reason);return b(cL,{runId:Y.id,status:Y.status})}})),Z.push(j0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:X0(hY),execute:async(j)=>b(DZ.array(),$.runtime.listRuns(b(hY,j)).map(UZ))})),Z.push(j0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:X0(NY),timeoutMs:IL,execute:async(j)=>{let X=b(NY,j);if(X.runId){let V=await $.runtime.awaitRun(X.runId);return sL(V),b(DZ,UZ(V))}let Y=await $.runtime.awaitAllRuns(),A=Y.filter((V)=>["failed","cancelled","interrupted"].includes(V.status));if(A.length>0){let V=A.map((H)=>`${H.id}:${H.status}${H.error?`(${H.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${V}`)}return b(DZ.array(),Y.map(UZ))}})),Z.push(j0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:X0(mY),execute:async(j)=>{let X=b(mY,j),Y=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return b(nL,{id:Y.id,toAgentId:Y.toAgentId})}})),Z.push(j0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:X0(qY),execute:async(j)=>{let X=b(qY,j),Y=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return b(vL,{delivered:Y.length})}})),Z.push(j0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:X0(IY),execute:async(j)=>{let X=b(IY,j);return b(pL.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),Z.push(j0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:X0(bY),execute:async(j)=>{let X=b(bY,j),Y=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return b(rL,{id:Y.id})}})),Z.push(j0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:X0(CY),execute:async(j)=>{if(b(CY,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),b(uL,{status:"cleaned"})}})),Z.push(j0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:X0(yY),execute:async(j)=>{let X=b(yY,j),Y=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return b(dL,{outcomeId:Y.id,status:Y.status,requiredSections:Y.requiredSections})}})),Z.push(j0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:X0(TY),execute:async(j)=>{let X=b(TY,j),Y=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return b(kY,{fragmentId:Y.id,status:Y.status})}})),Z.push(j0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:X0(xY),execute:async(j)=>{let X=b(xY,j),Y=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return b(kY,{fragmentId:Y.id,status:Y.status})}})),Z.push(j0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:X0(SY),execute:async(j)=>{let X=b(SY,j),Y=$.runtime.finalizeOutcome(X.outcomeId);return b(lL,{outcomeId:Y.id,status:Y.status})}})),Z.push(j0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:X0(EY),execute:async(j)=>{return b(EY,j),b(iL.array(),$.runtime.listOutcomes())}})),Z}function k6($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}function iY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var oL=[{id:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:F$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...Y2]}],eL={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function $_($){return $==="plan"||$==="yolo"?$:"act"}function aY($){let f=$_($.mode),J=v0[c1({mode:f})],Q=j2($.providerId??"",$.modelId??"",f,W2);return{mode:f,flags:{...J,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function nY($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=aY(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let Q=eL[$];return Q?J[Q]===!0:!1}function f_($,f){if($.id==="editor"){let{flags:J}=aY(f),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:nY($.id,f),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:nY($.id,f)}}function ff($={}){return oL.map((f)=>f_(f,$))}function I6($={}){return ff($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function x6($){if(!$.enabled)return new Set;let f=ff($.availabilityContext),J=new Set(f.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function J4($,f={}){return ff(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function g6($,f={}){return J4($,f)}function Jf($={}){let{executorOptions:f={},executors:J,...Q}=$,Z={...Z2(f),...J??{}};return V$({...Q,executors:Z})}import{mkdirSync as X_,writeFileSync as Y_}from"node:fs";import{dirname as A_}from"node:path";import{normalizeUserInput as V_}from"@cline/shared";import{nanoid as H_}from"nanoid";var sY={};q(sY,{sanitizeSessionToken:()=>Qf,parseTeamTaskSubSessionId:()=>H2,parseSubSessionId:()=>Z4,makeTeamTaskSubSessionId:()=>Q4,makeSubSessionId:()=>V2,deriveSubsessionStatus:()=>W4});import{nanoid as Z_}from"nanoid";function Qf($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function V2($,f){let J=Qf($),Q=Qf(f),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function Q4($,f){let J=Qf($),Q=Qf(f);return`${J}__teamtask__${Q}__${Z_(6)}`}function H2($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),X=Z.slice(W+2);if(!Q||!j||!X)return null;return{rootSessionId:Q,agentId:j,teamTaskId:X}}function Z4($){if(H2($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+f.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function W4($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var $A={};q($A,{isTerminalSessionStatus:()=>eY,isNonTerminalSessionStatus:()=>J0,SessionSource:()=>R0,SESSION_STATUSES:()=>j4,NON_TERMINAL_SESSION_STATUSES:()=>oY});import{SESSION_STATUS_VALUES as W_}from"@cline/shared";var j4=W_,oY=["idle","running","pending"];function eY($){return!oY.includes($)}function J0($){return!eY($)}var R0={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 j_=a.enum(j4),y0=a.object({version:a.literal(1),session_id:a.string().min(1),source:a.string().min(1),pid:a.number().int(),started_at:a.string().min(1),ended_at:a.string().min(1).optional(),exit_code:a.number().int().nullable().optional(),status:j_,interactive:a.boolean(),provider:a.string().min(1),model:a.string().min(1),cwd:a.string().min(1),workspace_root:a.string().min(1),team_name:a.string().min(1).optional(),enable_tools:a.boolean(),enable_spawn:a.boolean(),enable_teams:a.boolean(),prompt:a.string().optional(),metadata:a.record(a.string(),a.unknown()).optional(),messages_path:a.string().min(1).optional()});function fA($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function _Z($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let Q=[],Z=new Set;for(let W of J){if(Z.has(W.name))continue;Z.add(W.name),Q.push(W)}return Q}function JA($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function u1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function LZ($,f){let J={...$};J.id=u1(J.id)??H_();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:u1(Q?.id)??u1(J.modelId)??u1(f?.id),provider:u1(Q?.provider)??u1(J.providerId)??u1(f?.provider),family:u1(Q?.family)??u1(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function m6($){return $.map((f)=>LZ(f))}function v6($,f,J=[]){let Q=$.map((Y,A)=>{let V=J[A],B=V?.role===Y.role&&JSON.stringify(V.content)===JSON.stringify(Y.content)?{...V,...Y}:{...Y};return LZ(B)}),Z=J.length,W=[];for(let Y=Z;Y<Q.length;Y+=1)if(Q[Y]?.role==="assistant")W.push(Y);if(W.length===0){let Y=[...Q].reverse().findIndex((A)=>A.role==="assistant");if(Y===-1)return Q;W.push(Q.length-1-Y)}let j=W[W.length-1],X=W.some((Y)=>Q[Y]?.metrics);for(let Y of W){let A=Q[Y],V=A.metrics;if(!V&&Y===j&&!X){let H=f.usage;V={inputTokens:H.inputTokens,outputTokens:H.outputTokens,cacheReadTokens:H.cacheReadTokens??0,cacheWriteTokens:H.cacheWriteTokens??0,cost:H.totalCost}}Q[Y]={...LZ(A,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...V?{metrics:V}:{},ts:A.ts??f.endedAt.getTime()}}return Q}function X4($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var B_=120;function Zf($){let f=$?.trim();return f?f.slice(0,B_):void 0}function zZ($){let f=V_($??"").trim();if(!f)return;return Zf(f.split(`
452
- `)[0]?.trim())}function P$($){if(!$)return;let f={...$},J=Zf(typeof f.title==="string"?f.title:void 0);if(J)f.title=J;else delete f.title;return Object.keys(f).length>0?f:void 0}function Y4($){let f=P$($.metadata)??{},J=$.title!==void 0?Zf($.title):zZ($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function OZ($){let f=H2($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=Z4($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function MZ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:m6($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function QA($,f,J){X_(A_($),{recursive:!0}),Y_($,`${JSON.stringify(MZ({updatedAt:f,context:J,messages:[]}),null,2)}
453
- `,"utf8")}function ZA($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function WA($,f,J){let Q=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let W=await f(Z);if(typeof W==="object"&&W!==null&&"updated"in W&&W.updated===!1){if(Q+=1,Q>=J)return W;continue}return W}}_0();var jA={};q(jA,{summarizeUsageFromMessages:()=>K2,sumUsageTotals:()=>A4,getCurrentContextSize:()=>TZ,createInitialAccumulatedUsage:()=>K0,accumulateUsageTotals:()=>Y0});function K0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function Y0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function A4($){let f=K0();for(let J of $)f=Y0(f,J);return f}function B2($){return typeof $==="number"&&Number.isFinite($)?$:0}function K2($){let f=K0();for(let J of $){let Q=J.metrics;if(!Q)continue;f=Y0(f,{inputTokens:B2(Q.inputTokens),outputTokens:B2(Q.outputTokens),cacheReadTokens:B2(Q.cacheReadTokens),cacheWriteTokens:B2(Q.cacheWriteTokens),totalCost:B2(Q.cost)})}return f}function TZ($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let Q=B2(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function K_($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function NZ($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function d1($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,Q=$.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function G_($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function F_($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let Q=J?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function qZ($,f,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=$,X=Z.telemetry,Y=W?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,V=NZ(f),H=d1({agentId:J?.agentId??V.agentId,conversationId:J?.conversationId??V.conversationId,parentAgentId:J?.parentAgentId??V.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??Y?.getTeamId(),teamName:J?.teamName??Y?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=K_(f.input);if(B)xJ(X,{ulid:Q,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...H})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",K=!f.error;if(IJ(X,{ulid:Q,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...H}),!K&&(B==="editor"||B==="apply_patch"))gJ(X,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...H})}if(f.type==="notice"&&f.reason==="api_error")V8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...H});if(f.type==="error")V8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...H});if(f.type==="usage"&&W?.turnUsageBaseline){let B=G_(f);if(A){W.turnPrimaryUsage=Y0(W.turnPrimaryUsage??K0(),B);let G=Y0(W.turnUsageBaseline,W.turnPrimaryUsage);$.usageBySession.set(Q,G),cf(X,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...H}),bJ(X,{ulid:Q,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...H})}else{let G=F_({isPrimaryAgentEvent:A,overrides:J,eventMetadata:V}),R=W.turnUsageByAgent??new Map;W.turnUsageByAgent=R,R.set(G,Y0(R.get(G)??K0(),B))}let K=Y0(W.turnPrimaryUsage??K0(),A4(W.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,Y0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,K))}if(f.type==="iteration_end"&&A)$.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:JA(f),ts:Date.now()}})}function R$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as _O}from"@cline/shared";j1();import{existsSync as i6,readFileSync as Jz,statSync as Qz}from"node:fs";import{basename as Zz,dirname as p6,join as n6,resolve as r6}from"node:path";import{discoverPluginModulePaths as Wz,resolveConfiguredPluginModulePaths as qA,resolvePluginConfigSearchPaths as jz,SKILLS_CONFIG_DIRECTORY_NAME as Xz}from"@cline/shared/storage";import{resolve as k_}from"node:path";import{normalizePluginManifest as I_}from"@cline/shared";import{existsSync as D0,readFileSync as F2}from"node:fs";import{builtinModules as P_,createRequire as SZ}from"node:module";import{dirname as D$,extname as H4,isAbsolute as R_,resolve as l}from"node:path";import{fileURLToPath as YA}from"node:url";import{PLUGIN_FILE_EXTENSIONS as D_}from"@cline/shared";var AA=D$(YA(import.meta.url)),U_=SZ(import.meta.url),L_=l(AA,"..","..","..","..",".."),wZ=O_(L_),__=["@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"],EZ=new Set(P_.flatMap(($)=>[$,$.replace(/^node:/,"")])),V4=new Set(D_),z_=["development","node","import","require","default"];function O_($){let f={},J={"@cline/sdk":l($,"packages/sdk/src/index.ts"),"@cline/agents":l($,"packages/agents/src/index.ts"),"@cline/core":l($,"packages/core/src/index.ts"),"@cline/llms":l($,"packages/llms/src/index.ts"),"@cline/shared":l($,"packages/shared/src/index.ts"),"@cline/shared/storage":l($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":l($,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(D0(Z))f[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=l($,"packages",Q),W=l(Z,"package.json");if(!D0(W))continue;try{let j=JSON.parse(F2(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let X=l(Z,j.exports);if(D0(X))f[j.name]=X;continue}if(typeof j.exports!=="object")continue;for(let[X,Y]of Object.entries(j.exports)){let A=M_(Z,Y);if(!A)continue;let V=X==="."?j.name:`${j.name}/${X.replace(/^\.\//,"")}`;f[V]=A}}catch{}}return f}function M_($,f){let J=hZ(f);if(!J)return null;let Q=VA($,J);for(let Z of Q)if(D0(Z))return Z;return null}function hZ($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let Q of z_){let Z=hZ(J[Q],f);if(Z)return Z}return null}function VA($,f){let J=f.replace(/^\.\//,""),Q=[l($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[l($,`${Z}.ts`),l($,`${Z}.tsx`),l($,`${Z}.mts`),l($,`${Z}.cts`),...Q]}return Q}function T_($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function c6($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function G2($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function N_($){let f=G2($);if($===f)return".";return`.${$.slice(f.length)}`}function HA($){return G2($).startsWith("@cline/")}function CZ($,f){let J=G2(f),Q=D$($);while(!0){let Z=l(Q,"node_modules",J);if(D0(Z)||D0(l(Z,"package.json")))return!0;let W=l(Q,"..");if(W===Q)return!1;Q=W}}function XA($){return yZ($)!==null}function yZ($){try{return U_.resolve($)}catch{}return q_($)}function q_($){let f=G2($),J=BA(f);if(!J)return null;let Q=l(J,"package.json");try{let Z=JSON.parse(F2(Q,"utf8")),W=N_($),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,X=hZ(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!X)return null;let Y=l(J,X),A=[Y,...VA(J,X).filter((V)=>V!==Y)];for(let V of A)if(D0(V))return V;return null}catch{return null}}function w_(){let $=[AA],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(D$(D$(f)));let J=process.execPath?.trim();if(J)$.push(D$(J));return[...new Set($.map((Q)=>l(Q)))]}function C_($,f){let J=$;while(!0){let Q=l(J,"package.json");if(D0(Q))try{if(JSON.parse(F2(Q,"utf8")).name===f)return J}catch{}let Z=l(J,"node_modules",f,"package.json");if(D0(Z))return D$(Z);let W=l(J,"..");if(W===J)return null;J=W}}function BA($){for(let f of w_()){let J=C_(f,$);if(J)return J}return null}function y_($){let J=D$($);for(let Q=0;Q<4;Q++){let Z=l(J,"package.json");if(D0(Z))try{let j=JSON.parse(F2(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let W=l(J,"..");if(W===J)return!1;J=W}return!1}function KA($,f){let J=f.startsWith("file:")?YA(f):R_(f)?f:l(D$($),f);if(D0(J)&&V4.has(H4(J)))return J;for(let Q of V4){let Z=`${J}${Q}`;if(D0(Z))return Z}for(let Q of V4){let Z=l(J,`index${Q}`);if(D0(Z))return Z}return null}function GA($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of J)for(let Z of $.matchAll(Q)){let W=Z[1];if(W)f.add(W)}return[...f]}function S_($){return H4($)!==".ts"}function FA($,f,J=new Set){if(J.has($)||!D0($))return;if(J.add($),!V4.has(H4($)))return;let Q=F2($,"utf8"),Z=S_($);for(let W of GA(Q)){if(W.startsWith("node:")||EZ.has(W))continue;if(c6(W)){if(!Z)continue;if(Object.hasOwn(wZ,W)||Object.hasOwn(wZ,G2(W))||CZ($,W)||HA(W)&&XA(W)||f&&XA(W))continue;throw Error(`Cannot find module '${G2(W)}'`)}let j=KA($,W);if(j)FA(j,f,J)}}function PA($,f=new Set,J=new Set){if(f.has($)||!D0($))return J;if(f.add($),!V4.has(H4($)))return J;let Q=F2($,"utf8");for(let Z of GA(Q)){if(J.add(Z),c6(Z))continue;let W=KA($,Z);if(W)PA(W,f,J)}return J}function E_($,f){let J=SZ($),Q={},Z=PA($),W=new Set(__);for(let[j,X]of Object.entries(wZ)){try{J.resolve(j);continue}catch{}Q[j]=X}for(let j of Z)if(c6(j)&&(HA(j)||f))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||CZ($,j))continue;let X=yZ(j);if(X)Q[j]=X}if(!f)return Q;for(let j of Z){if(!c6(j)||Object.hasOwn(Q,j)||CZ($,j)||j.startsWith("node:")||EZ.has(j))continue;let X=yZ(j);if(X)Q[j]=X}return Q}function h_($){let f=H4($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var Wf;function b_(){if(Wf!==void 0)return Wf;let $=BA("jiti");if(!$)return Wf=null,null;let f=l($,"dist","babel.cjs");if(!D0(f))return Wf=null,null;try{let Q=SZ(f)(f);Wf=typeof Q==="function"?Q:null}catch{Wf=null}return Wf}async function RA($,f={}){let J=!y_($);FA($,J);let Q=E_($,J),Z=T_(Q),W=await import("jiti"),j=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!j)throw Error("Unable to load jiti");let X=Object.entries(Z).filter(([,H])=>h_(H)).map(([H])=>H),Y=b_(),A=Y?(H)=>Y({...H,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...EZ],transformModules:X,tryNative:!1,...A?{transform:A}:{}}).import($,{})}function DA($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function UA($){return typeof $==="object"&&$!==null}function bZ($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function x_($,f){if(!UA($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!bZ($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!bZ($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!bZ($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function g_($,f){if(!UA($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);x_($,f)}async function B4($,f={}){let J=k_(f.cwd??process.cwd(),$),Q=await RA(J,{useCache:f.useCache}),Z=f.exportName??"plugin",W=Q.default??Q[Z];g_(W,J);let j=W,X=j.setup,Y=X?(A,V)=>{let H={...f.session,...V.session},B={...V,session:Object.keys(H).length>0?H:void 0,client:f.client??V.client,user:f.user??V.user,workspaceInfo:f.workspaceInfo??V.workspaceInfo,automation:f.automation??V.automation,logger:f.logger??V.logger,telemetry:f.telemetry??V.telemetry};return X(A,B)}:void 0;return{...j,manifest:I_(j.manifest),setup:Y}}async function u6($,f={}){return(await jf($,f)).plugins}async function jf($,f={}){let J=[],Q=[],Z=new Map,W=0;for(let X of $)try{let Y=await B4(X,f);if(!DA(Y.manifest,f))continue;let A=Z.get(Y.name);if(A)Q.push({type:"duplicate_plugin_override",pluginName:Y.name,pluginPath:X,overriddenPluginPath:A.pluginPath,message:`Plugin "${Y.name}" from ${X} overrides ${A.pluginPath}`});Z.set(Y.name,{plugin:Y,pluginPath:X,order:W++})}catch(Y){let A=Y instanceof Error?Y.message:String(Y);J.push({pluginPath:X,phase:"load",message:A,stack:Y instanceof Error?Y.stack:void 0})}let j=[...Z.values()].sort((X,Y)=>X.order-Y.order);return{plugins:j.map((X)=>X.plugin),pluginPaths:j.map((X)=>X.pluginPath),failures:J,warnings:Q}}import{existsSync as gZ}from"node:fs";import{createRequire as NA}from"node:module";import{dirname as d6,join as R2}from"node:path";import{fileURLToPath as d_}from"node:url";var MA={};q(MA,{resolveSubprocessRuntimeExecutable:()=>kZ,buildSubprocessSandboxCommand:()=>OA,SubprocessSandbox:()=>P2,CLINE_JS_RUNTIME_PATH_ENV:()=>zA});import{spawn as m_}from"node:child_process";import{basename as v_}from"node:path";import{augmentNodeCommandForDebug as c_,withResolvedClineBuildEnv as u_}from"@cline/shared";function LA($){if($ instanceof Error)return $;return Error(String($))}var zA="CLINE_JS_RUNTIME_PATH";function _A($){let f=$?.trim();if(!f)return!1;let J=v_(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function kZ($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[zA]?.trim();if(J)return J;let Q=$.execPath?.trim()||process.execPath;if(_A(Q))return Q;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let W=Z?.trim();if(W&&_A(W))return W}return"node"}function OA($,f={}){let J=kZ({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return c_([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class P2{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=OA($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=m_(f[0]??kZ(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:u_(process.env),windowsHide:!0});this.process=J;let Q="",Z=(W)=>{let j=Q+W;Q=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{Z(W)}),J.on("message",(W)=>{this.onMessage(W)}),J.on("error",(W)=>{this.failPending(Error(`${this.processLabel} process error: ${LA(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let X=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${X?`: ${X}`:""}`))})}async call($,f,J={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,W={type:"call",id:Z,method:$,args:f};return await new Promise((j,X)=>{let Y={resolve:(A)=>j(A),reject:X};if((J.timeoutMs??0)>0)Y.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,Y),Q.send(W,(A)=>{if(!A)return;let V=this.clearPendingRequest(Z);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${$}": ${LA(A).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function l_($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function K4($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function p_(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function r_(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=NA($).resolve(`${p_()}/package.json`),Q=R2(d6(J),"extensions","plugin-sandbox-bootstrap.js");return gZ(Q)?Q:void 0}catch{return}}function i_(){let $=process.execPath?.trim();if(!$)return;let f=R2(d6(d6($)),"extensions","plugin-sandbox-bootstrap.js");return gZ(f)?f:void 0}function n_(){let $=d6(d_(import.meta.url)),f=NA(import.meta.url),J=[R2($,"plugin-sandbox-bootstrap.js"),R2($,"extensions","plugin-sandbox-bootstrap.js"),R2($,"agents","plugin-sandbox-bootstrap.js"),r_(),i_()];for(let W of J.filter((j)=>typeof j==="string"))if(gZ(W))return{file:W};let Q=R2($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
454
- `)}}var IZ=n_();function xZ($,f,J){if(typeof $==="number"&&$>0)return $;if(J){let Q=process.env[J];if(Q){let Z=Number(Q);if(Number.isInteger(Z)&&Z>0)return Z}}return f}async function l6($){let f=new P2({name:"plugin-sandbox",..."file"in IZ?{bootstrapFile:IZ.file}:{bootstrapScript:IZ.script},onEvent:$.onEvent}),J=xZ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=xZ($.hookTimeoutMs,3000),Z=xZ($.contributionTimeoutMs,60000),W={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,X=()=>{return j??=f.call("initialize",W,{timeoutMs:J}).finally(()=>{j=void 0}),j},Y;try{Y=await f.call("initialize",W,{timeoutMs:J})}catch(H){throw await f.shutdown().catch(()=>{}),H}let A=Y.plugins.map(l_);return{extensions:A.map((H)=>{let B={name:H.name,__clinePluginPath:H.pluginPath,manifest:H.manifest,setup:(K)=>{a_(K,f,H,Z,X),t_(K,f,H,Z,X),s_(K,f,H,Z,X),e_(K,f,H,Z,X),o_(K,H)}};return B.hooks=fz(f,H,Q,X),B}),failures:Y.failures,pluginPaths:A.map((H)=>H.pluginPath),shutdown:async()=>{await f.shutdown()},warnings:Y.warnings}}function a_($,f,J,Q,Z){for(let W of J.contributions?.tools??[]){let j={name:W.name,description:W.description??"",inputSchema:W.inputSchema??{type:"object",properties:{}},timeoutMs:W.timeoutMs,retryable:W.retryable,execute:async(X,Y)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:Y},{timeoutMs:Q})}catch(A){if(!K4(A))throw A;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:Y},{timeoutMs:Q})}}};$.registerTool(j)}}function t_($,f,J,Q,Z){for(let W of J.contributions?.commands??[])$.registerCommand({name:W.name,description:W.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}catch(X){if(!K4(X))throw X;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}}})}function s_($,f,J,Q,Z){for(let W of J.contributions?.rules??[])$.registerRule({id:W.ruleId,source:W.source,content:W.hasContentHandler===!0?async()=>{try{return await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}catch(j){if(!K4(j))throw j;return await Z(),await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}}:W.content??""})}function o_($,f){for(let J of f.contributions?.providers??[])$.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of f.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function e_($,f,J,Q,Z){for(let W of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:W.name,async build(j){try{let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return TA(X)?X:j}catch(X){if(!K4(X))throw X;await Z();let Y=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return TA(Y)?Y:j}}})}function TA($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function $z($,f,J,Q,Z){return async(W)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}catch(j){if(!K4(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}}}function fz($,f,J,Q){let Z={};for(let W of f.hooks??[])Z[W]=$z($,f.pluginId,W,J,Q);return Object.keys(Z).length>0?Z:void 0}var vZ="package.json",Yz="package";function G4($){return jz($)}function F4($){return Wz($)}function Az($){try{return i6($)&&Qz($).isDirectory()}catch{return!1}}function cZ($){let f=[],J=new Set;for(let Q of $){let Z=r6(Q);if(J.has(Z))continue;J.add(Z),f.push(Z)}return f}function wA($){let f=cZ($);return tJ(f)}function CA($){return G4($).flatMap((f)=>F4(f)).filter((f)=>i6(f))}function Vz($,f){let J=[];for(let Q of $)try{J.push(...qA([Q],f))}catch{}return J}function mZ($){return typeof $==="object"&&$!==null}function Hz($){try{let f=JSON.parse(Jz(n6($,vZ),"utf8"));if(!mZ(f)||!mZ(f.cline))return[];let J=f.cline.plugins;if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(typeof Z==="string"){Q.push(Z);continue}if(!mZ(Z)||!Array.isArray(Z.paths))continue;for(let W of Z.paths)if(typeof W==="string")Q.push(W)}return Q}catch{return[]}}function yA($,f){let J=r6(f);return Hz($).some((Q)=>r6($,Q)===J)}function Bz($,f){return Zz($)===Yz&&i6(n6(p6($),vZ))&&yA(p6($),f)}function Kz($){let f=r6($),J=[],Q=p6(f);while(!0){if(Bz(Q,f)){J.push(Q);break}if(i6(n6(Q,vZ))){if(yA(Q,f))J.push(Q);break}let Z=p6(Q);if(Z===Q)break;Q=Z}return cZ(J)}function Xf($={}){let f=$.cwd??process.cwd(),J=CA($.workspacePath),Q=qA($.pluginPaths??[],f);return wA([...Q,...J])}function Gz($={}){let f=$.cwd??process.cwd(),J=CA($.workspacePath),Q=Vz($.pluginPaths??[],f);return wA([...Q,...J])}function Yf($){let f=[];for(let J of $)for(let Q of Kz(J)){let Z=n6(Q,Xz);if(Az(Z))f.push(Z)}return cZ(f)}function SA($={}){return Yf(Gz($))}async function D2($={}){let f=Xf($);if(f.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await jf(f,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let J=await l6({pluginPaths:f,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}import{execFile as Fz}from"node:child_process";import{promisify as Pz}from"node:util";var Rz=Pz(Fz);function uZ($,f){$?.log(f,{severity:"warn"})}function Dz($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let Q=J.latest,Z=J.history.filter((W)=>!!W&&typeof W==="object"&&typeof W.ref==="string"&&typeof W.createdAt==="number"&&typeof W.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:Z}}async function Af($,f){let J=await Rz("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function dZ($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:Q}=await Af($,["for-each-ref","--format=%(refname)",J]),Z=Q.trim().split(`
455
- `).filter(Boolean);await Promise.allSettled(Z.map((W)=>Af($,["update-ref","-d",W])))}catch{}}async function EA($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((Q)=>Af($,["update-ref",`refs/cline/checkpoints/${f}/${Q.runCount}`,Q.ref])))}function Uz($,f){let J=$.findIndex((Q)=>Q.runCount===f.runCount);if(J<0)return[...$,f];return $.map((Q,Z)=>Z===J?f:Q)}function hA($){let f=$.initialRunCount??0,J,Q=async()=>{if(J!==void 0)return J;try{J=(await Af($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await Q())return;let W=async(A)=>{try{let H=(await Af($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!H)return;return{ref:H,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(V){uZ($.logger,`${A}: ${V instanceof Error?V.message:String(V)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,X="";try{X=(await Af($.cwd,["stash","create",j])).stdout.trim()}catch(A){return uZ($.logger,`Checkpoint snapshot failed: ${A instanceof Error?A.message:String(A)}`),W("Checkpoint HEAD fallback failed")}if(!X)return W("Checkpoint HEAD fallback failed");let Y=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await Af($.cwd,["update-ref",Y,X])}catch(A){uZ($.logger,`Checkpoint store failed: ${A instanceof Error?A.message:String(A)}`);return}return{ref:X,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:W})=>{if(W.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:W})=>{if(W.parentAgentId!=null||W.iteration!==1||f<1)return;let j=await Z();if(!j)return;let X=await $.readSessionMetadata(),Y=Dz(X);if(Y?.latest.ref===j.ref)return;let A=Uz(Y?.history??[],j);await $.writeSessionMetadata({...X??{},checkpoint:{latest:j,history:A}});return}}}import{spawn as wz}from"node:child_process";import{appendFileSync as Cz,readFileSync as yz}from"node:fs";import{join as Sz}from"node:path";import{augmentNodeCommandForDebug as IA,withResolvedClineBuildEnv as rZ}from"@cline/shared";import{ensureHookLogDir as bA}from"@cline/shared/storage";function U2($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as Lz,readdirSync as _z}from"node:fs";import{basename as zz,extname as Oz,join as Mz}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as a6,resolveHooksConfigSearchPaths as Tz}from"@cline/shared/storage";function P4($){return Tz($)}var L2;((V)=>{V.TaskStart="TaskStart";V.TaskResume="TaskResume";V.TaskCancel="TaskCancel";V.TaskComplete="TaskComplete";V.TaskError="TaskError";V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.UserPromptSubmit="UserPromptSubmit";V.PreCompact="PreCompact";V.SessionShutdown="SessionShutdown"})(L2||={});var R4={["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"},Nz=new Map(Object.values(L2).map(($)=>[$.toLowerCase(),$])),qz=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function D4($){let f=Oz($).toLowerCase();if(!qz.has(f))return;let J=zz($,f).trim().toLowerCase();return Nz.get(J)}function U$($){let f=[],J=new Set,Q=P4($).filter((Z)=>Lz(Z));for(let Z of Q)try{for(let W of _z(Z,{withFileTypes:!0})){if(!W.isFile())continue;let j=D4(W.name);if(!j)continue;let X=Mz(Z,W.name);if(J.has(X))continue;J.add(X),f.push({fileName:j,hookEventName:R4[j],path:X})}}catch{}return f.sort((Z,W)=>Z.path.localeCompare(W.path))}function s6($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))f[J]=typeof Q==="string"?Q:JSON.stringify(Q);return f}function t6($,f,J){let Q=J instanceof Error?`: ${J.message}`:"",Z=`${f}${Q}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function Ez($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
456
- `),Q=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function hz($){if(!$||typeof $!=="object")return;let f=$,J=typeof f.context==="string"?f.context:typeof f.contextModification==="string"?f.contextModification:typeof f.errorMessage==="string"?f.errorMessage:void 0;return{cancel:typeof f.cancel==="boolean"?f.cancel:void 0,review:typeof f.review==="boolean"?f.review:void 0,context:J,overrideInput:Object.hasOwn(f,"overrideInput")?f.overrideInput:void 0}}function lZ($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function U0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function bz($){let f=$.trim();if(!f)return{};let Q=f.split(`
457
- `).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse hook stdout JSON"}}}async function kz($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((Q,Z)=>{let W=!1,j=()=>{J.off("error",Y),J.off("finish",A),$.off("close",V)},X=(H)=>{if(W)return;if(W=!0,j(),H){let B=H.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){Q();return}Z(H);return}Q()},Y=(H)=>X(H),A=()=>X(),V=()=>X();J.on("error",Y),J.once("finish",A),$.once("close",V);try{J.end(f)}catch(H){X(H)}})}async function xA($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await kA($,f)}catch(J){let Q=gz(f.command,process.platform,J);if(!Q)throw J;return await kA($,{...f,command:Q})}}async function kA($,f){let J=IA(f.command,{env:f.env,debugRole:"hook"}),Q=wz(J[0],J.slice(1),{cwd:f.cwd,env:rZ(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached,windowsHide:!0}),Z=new Promise((B)=>{Q.once("spawn",()=>B())}),W=new Promise((B,K)=>{Q.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,W]),await kz(Q,j),f.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let X="",Y="",A=!1,V;Q.stdout.on("data",(B)=>{X+=B.toString()}),Q.stderr.on("data",(B)=>{Y+=B.toString()});let H=new Promise((B)=>{if((f.timeoutMs??0)>0)V=setTimeout(()=>{A=!0,Q.kill("SIGKILL")},f.timeoutMs);Q.once("close",(K)=>{if(V)clearTimeout(V);let{parsedJson:G,parseError:R}=bz(X);B({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:A})})});return await Promise.race([H,W])}function Iz($){try{let J=yz($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let Q=J.slice(2).trim();if(!Q)return;let Z=Q.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function xz($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function gz($,f=process.platform,J){if(f!=="win32"||!xz(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function gA($){if($.length===0)return;let[f,...J]=$,Q=f.replace(/\\/g,"/").toLowerCase(),Z=Q.split("/").at(-1)??Q;if(Z==="env")return gA(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function mz($){let f=Iz($);if(f&&f.length>0)return[...gA(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return IA(["node",$],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",$];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function vz($){let f={};for(let J of U$($)){if(!J.hookEventName)continue;let Q=J.hookEventName,Z=f[Q]??[];Z.push(mz(J.path)),f[Q]=Z}return f}async function cz($){let f;for(let J of $.commands){let Q=J.join(" ");try{let Z=await xA($.payload,{command:J,cwd:$.cwd,env:rZ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){t6($.logger,`hook command timed out: ${Q}`);continue}if(Z?.parseError){t6($.logger,`hook command returned invalid JSON control output: ${Q} (${Z.parseError})`);continue}f=Ez(f,hz(Z?.parsedJson))}catch(Z){t6($.logger,`hook command failed: ${Q}`,Z)}}return f}function Vf($){for(let f of $.commands){let J=f.join(" ");xA($.payload,{command:f,cwd:$.cwd,env:rZ(process.env),detached:!0}).catch((Q)=>{t6($.logger,`hook command failed: ${J}`,Q)})}}function L$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function pZ($,f){return{...L$($.snapshot),userMessage:f}}function mA($){return{...L$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function vA($){return{...L$($.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 cA($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function uz($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}function _2($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(Q)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
458
- `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Sz(bA(),"hooks.jsonl");bA(j),Cz(j,Z,"utf8")};return{beforeRun:async(Q)=>{let Z=pZ(Q,"");J({...U0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let Z=mA(Q);J({...U0(Z,f),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:s6(Z.call.input)}});return},afterTool:async(Q)=>{let Z=vA(Q);J({...U0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:s6(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:Q,result:Z})=>{let W=L$(Q);if(Z.status==="completed"){J({...U0(W,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||lZ(Z.error?.message)){J({...U0(W,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...U0(W,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let Z=pZ({snapshot:Q.snapshot},cA(Q.message.content));J({...U0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function U4($){let f=vz($.workspacePath);if(!Object.values(f).some((H)=>H.length>0))return;let Q=async(H,B)=>{let K=f[B]??[];if(K.length===0)return;Vf({commands:K,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...U0(H,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...U0(H,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(H)=>{let B=f.prompt_submit??[];if(B.length>0)Vf({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:H.userMessage,attachments:[]}}})},W=async(H)=>{let B=f.tool_call??[];if(B.length===0)return;return cz({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...U0(H,$),hookName:"tool_call",iteration:H.iteration,tool_call:{id:H.call.id,name:H.call.name,input:H.call.input},preToolUse:{toolName:H.call.name,parameters:s6(H.call.input)}}})},j=async(H)=>{let B=f.tool_result??[];if(B.length===0)return;Vf({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(H,$),hookName:"tool_result",iteration:H.iteration,tool_result:H.record,postToolUse:{toolName:H.record.name,parameters:s6(H.record.input),result:typeof H.record.output==="string"?H.record.output:JSON.stringify(H.record.output),success:!H.record.error,executionTimeMs:H.record.durationMs}}})},X=async(H)=>{let B=f.agent_end??[];if(B.length===0)return;Vf({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(H,$),hookName:"agent_end",iteration:H.iteration,turn:H.turn,taskComplete:{taskMetadata:{}}}})},Y=async(H)=>{let B=f.agent_error??[];if(B.length===0)return;Vf({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(H,$),hookName:"agent_error",iteration:H.iteration,error:{name:H.error.name,message:H.error.message,stack:H.error.stack}}})},A=async(H)=>{if(lZ(H.reason)){let K=f.agent_abort??[];if(K.length>0)Vf({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(H,$),hookName:"agent_abort",reason:H.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;Vf({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(H,$),hookName:"session_shutdown",reason:H.reason}})},V={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)V.beforeRun=async(H)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(L$(H.snapshot),B);return};if((f.prompt_submit?.length??0)>0)V.onEvent=async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;await Z(pZ({snapshot:H.snapshot},cA(H.message.content)))}}if((f.tool_call?.length??0)>0)V.beforeTool=async(H)=>{let B=await W(mA(H));return uz(B)};if((f.tool_result?.length??0)>0)V.afterTool=async(H)=>{await j(vA(H));return};if((f.agent_end?.length??0)>0)V.afterRun=async({snapshot:H,result:B})=>{if(B.status!=="completed")return;await X({...L$(H),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let H=V.afterRun;V.afterRun=async(B)=>{await H?.(B);let{snapshot:K,result:G}=B;if(G.status==="aborted"||lZ(G.error?.message)){await A({...L$(K),reason:G.error?.message});return}if(G.error)await Y({...L$(K),iteration:G.iterations,error:G.error})}}return V}function z2($){return U2("core.hook_config_files",U4($))}function Hf($,f){let J=$.map((Q)=>Q[f]).filter((Q)=>typeof Q==="function");if(J.length===0)return;return async(Q)=>{let Z;for(let W of J){let j=await W(Q);if(!j||typeof j!=="object")continue;let X=j;Z={...Z??{},...X,stop:Z?.stop===!0||X.stop===!0?!0:X.stop,options:Z?.options||X.options?{...Z?.options??{},...X.options??{}}:void 0}}return Z}}function Bf($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:Hf(f,"beforeRun"),afterRun:Hf(f,"afterRun"),beforeModel:Hf(f,"beforeModel"),afterModel:Hf(f,"afterModel"),beforeTool:Hf(f,"beforeTool"),afterTool:Hf(f,"afterTool"),onEvent:Hf(f,"onEvent")}}var uA={};q(uA,{normalizeRuntimeCapabilities:()=>L0});function L0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let Q=f&&Object.keys(f).length>0;if(!Q&&!J)return;return{...Q?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}var sA={};q(sA,{toProviderConfig:()=>u0,emptyStoredProviderSettings:()=>O$,StoredProviderSettingsSchema:()=>T2,StoredProviderSettingsEntrySchema:()=>L5,ProviderSettingsSchemaTyped:()=>T4});import{z as z$}from"zod";var tA={};q(tA,{toProviderConfig:()=>u0,safeParseSettings:()=>U5,safeCreateProviderConfig:()=>JW,parseSettings:()=>D5,normalizeProviderId:()=>M2,isBuiltInProviderId:()=>$W,createProviderConfig:()=>fW,SapSettingsSchema:()=>F5,ReasoningSettingsSchema:()=>H5,ProviderSettingsSchema:()=>_$,ProviderProtocolSchema:()=>Y5,ProviderIdSchema:()=>M4,ProviderClientSchema:()=>A5,OcaSettingsSchema:()=>P5,ModelCatalogSettingsSchema:()=>R5,GcpSettingsSchema:()=>K5,BUILT_IN_PROVIDER_IDS:()=>eZ,BUILT_IN_PROVIDER:()=>O4,AzureSettingsSchema:()=>G5,AwsSettingsSchema:()=>B5,AuthSettingsSchema:()=>V5});import*as c0 from"@cline/llms";import{z as N}from"zod";var aA={};q(aA,{resolveProviderConfig:()=>z4,getProviderConfig:()=>X5,getLiveModelsCatalog:()=>O2,clearPublicModelsCatalogCache:()=>AO,clearPrivateModelsCatalogCache:()=>oZ,clearLiveModelsCatalogCache:()=>sZ,OPENAI_COMPATIBLE_PROVIDERS:()=>_4,DEFAULT_MODELS_CATALOG_URL:()=>Q5});import*as A0 from"@cline/llms";function iZ($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((f)=>f.length>0)}function dz($,f){let J=iZ($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let Q=$,Z=iZ(Q.data??Q.models);if(Z.length>0)return Z;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let j=Object.keys(Q.models).filter((X)=>X.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[f];if(W&&typeof W==="object"){let X=iZ(W.models??W);if(X.length>0)return X}return[]}async function o6($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return dz(await J.json(),f)}function dA($){return $.replace(/\/+$/,"")}function e6($,f,J){let Q=J?.trim();if(!Q)return;let Z=$?.trim();if(!Z||!f?.trim())return Q;try{let W=new URL(Q),j=new URL(f),X=new URL(Z);if(W.origin!==j.origin)return Q;let Y=dA(j.pathname),A=dA(X.pathname);if(Y&&W.pathname.startsWith(`${Y}/`)){let V=W.pathname.slice(Y.length);X.pathname=`${A}${V}`}else X.pathname=W.pathname;return X.search=W.search,X.hash=W.hash,X.toString()}catch{return Q}}function lz($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function pz($){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 rz=Object.values(A0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:lz($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),pA=Object.fromEntries(rz.map(($)=>[$.id,$]));function iz($){return pA[$]}function nz(){return Object.fromEntries(Object.entries(pA).filter(([,$])=>pz($)))}function rA($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var Q5="https://models.dev/api.json",az=600000,iA=300000,tz=5000,J5=new Map,L4=new Map,nZ=new Map,$5=new Map;async function sz(){return A0.getGeneratedProviderModels()}async function oz($,f={},J={},Q={},Z={},W={}){let j=await sz(),X=A0.resolveProviderModelCatalogKeys($),Y=Object.assign({},...X.map((H)=>j[H]??{})),A=Boolean(A0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),V=Object.keys(Z).length>0;if(A&&V)return A0.sortModelsByReleaseDate({...Z,...W});if($==="openai-codex")return A0.sortModelsByReleaseDate({...f,...A0.filterOpenAICodexModels(J),...Z,...W});return A0.sortModelsByReleaseDate({...Y,...f,...J,...Q,...Z,...W})}function ez($,f){let J=A0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((Q)=>f[Q]??{}))}function Z5($){let f=$?.trim();return f&&f.length>0?f:""}function tZ($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function $O($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function fO($,f){return`${$}:${Z5(f.baseUrl)}:${$O(tZ(f)??"")}`}async function W5($,f,J=tz){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch($,{...f,signal:Q.signal})}finally{clearTimeout(Z)}}function Kf($,f,J){if(J&&!$.includes(f))$.push(f)}function j5($,f){let J=["streaming","tools"];return Kf(J,"images",Boolean(f.supportsImages)),Kf(J,"prompt-cache",Boolean(f.supportsPromptCache)),Kf(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}async function JO($,f){let J=await W5("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let Y=j.supported_features??[];W[X]=j5(X,{name:X,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:Y.includes("reasoning")||Y.includes("reasoning_effort"),supportsImages:!1})}return W}function lA($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function QO($,f){let J=await W5("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;W[X]=j5(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}async function ZO($,f){let Q=`${(Z5($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await W5(Q,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],X={};for(let Y of j){let A=Y.id?.trim();if(!A)continue;let V=Y.supported_features??[],H=Y.supported_sampling_parameters??[],B=Y.input_modalities??[],K=["streaming"];Kf(K,"tools",V.includes("tools")),Kf(K,"reasoning",V.includes("reasoning")),Kf(K,"temperature",H.includes("temperature")),Kf(K,"images",B.includes("image"));let G={input:lA(Y.pricing?.prompt),output:lA(Y.pricing?.completion)};X[A]={id:A,name:Y.name??A,description:Y.description,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function WO($){let f=Z5($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function jO($,f){let Q=`${WO($.baseUrl)}/v1/model/info`,Z=async(A)=>W5(Q,{method:"GET",headers:{accept:"application/json",...A}}),W=await Z({"x-litellm-api-key":f});if(!W.ok)W=await Z({Authorization:`Bearer ${f}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let X=(await W.json())?.data??[],Y={};for(let A of X){let V=A.model_name?.trim(),B=A.litellm_params?.model?.trim()||V;if(!B)continue;let K=A.model_info,G=j5(B,{name:V??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(Y[B]=G,V)Y[V]={...G,id:V,name:V}}return Y}var nA={baseten:JO,hicap:QO,litellm:jO,poolside:ZO},aZ=new Map,f5=new Map;function XO($,f){return`${$}:${Z5(f.baseUrl)}`}async function YO($,f,J){let Q=A0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=e6(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=f?.cacheTtlMs??iA,j=XO($,J),X=Date.now(),Y=aZ.get(j);if(Y&&Y.expiresAt>X)return Y.data;let A=f5.get(j);if(A)return A;let V=o6(Z,$).then((H)=>{let B=Object.fromEntries(H.map((K)=>[K,j5(K,{name:K})]));return aZ.set(j,{data:B,expiresAt:X+W}),B}).finally(()=>{f5.delete(j)});return f5.set(j,V),V}function AO(){aZ.clear(),f5.clear()}async function VO($,f){let J=tZ(f);if(!J)return{};let Q=nA[$];if(!Q)return{};return Q(f,J)}function HO($,f,J){if(!J)return!1;if(!nA[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(tZ(J))}async function BO($,f,J){let Q=f?.cacheTtlMs??iA,Z=fO($,J),W=Date.now(),j=nZ.get(Z);if(j&&j.expiresAt>W)return j.data;let X=$5.get(Z);if(X)return X;let Y=VO($,J).then((A)=>{return nZ.set(Z,{data:A,expiresAt:W+Q}),A}).finally(()=>{$5.delete(Z)});return $5.set(Z,Y),Y}async function KO($){return A0.fetchModelsDevProviderModels($,globalThis.fetch)}async function O2($={}){let f=$.url??Q5,J=$.cacheTtlMs??az,Q=Date.now(),Z=J5.get(f);if(Z&&Z.expiresAt>Q)return Z.data;let W=L4.get(f);if(W)return W;let j=KO(f).then((X)=>{return J5.set(f,{data:X,expiresAt:Q+J}),X}).finally(()=>{L4.delete(f)});return L4.set(f,j),j}function sZ($){if($){J5.delete($),L4.delete($);return}J5.clear(),L4.clear()}function oZ(){nZ.clear(),$5.clear()}function GO($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:rA(J.capabilities)}]))}var _4=GO(nz());function X5($){let f=iz($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:rA(f.capabilities)}}async function z4($,f,J){let Q=X5($);if(!Q)return;try{let Z=f?.loadLatestOnInit?await O2(f):void 0,W=Z?ez($,Z):{},j=J&&HO($,f,J)?await BO($,f,J):{},Y=Boolean(A0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,A=Y?await YO($,f,Y).catch(()=>({})):{},V=await oz($,Q.knownModels,W,j,A,J?.knownModels);return{...Q,knownModels:V}}catch(Z){if(f?.failOnError)throw Z;return Q}}var O4=c0.BUILT_IN_PROVIDER,eZ=c0.BUILT_IN_PROVIDER_IDS,$W=c0.isBuiltInProviderId,M2=c0.normalizeProviderId,M4=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),Y5=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),A5=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),V5=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),FO=N.enum(["none","low","medium","high","xhigh"]),H5=N.object({enabled:N.boolean().optional(),effort:FO.optional(),budgetTokens:N.number().int().positive().optional()}),B5=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()}),K5=N.object({projectId:N.string().optional(),region:N.string().optional()}),G5=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),F5=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()}),P5=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),R5=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()}),_$=N.object({provider:M4,apiKey:N.string().optional(),auth:V5.optional(),model:N.string().optional(),protocol:Y5.optional(),client:A5.optional(),routingProviderId:M4.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:H5.optional(),aws:B5.optional(),gcp:K5.optional(),azure:G5.optional(),sap:F5.optional(),oca:P5.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:R5.optional()});function D5($){return _$.parse($)}function U5($){return _$.safeParse($)}function PO($){return $.protocol==="openai-responses"||$.client==="openai"}function u0($,f={}){let J=$.provider,Q=M2(J),Z=f.includeKnownModels!==!1,W=$.reasoning?.effort||"none",j=W==="none"?void 0:W,X=_4[Q],Y=Object.assign({},...c0.resolveProviderModelCatalogKeys(Q).map((R)=>c0.getGeneratedModelsForProvider(R))),A=Object.keys(Y)[0],V=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,H=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?R6:D6:X?.baseUrl),B=$.routingProviderId??(PO($)&&Q!==O4.OPENAI_NATIVE?O4.OPENAI_NATIVE:void 0),K=Z?X?.knownModels??(Object.keys(Y).length>0?Y:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??X?.modelId??A??"default",...Z?{knownModels:K}:{},apiKey:V,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:H,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,P])=>P!==void 0))}function fW($){let f=D5($);return u0(f)}function JW($){let f=U5($);if(f.success)return{success:!0,config:u0(f.data)};return{success:!1,error:f.error}}var T4=_$;var L5=z$.object({settings:_$,updatedAt:z$.string().datetime(),tokenSource:z$.enum(["manual","oauth","migration"]).default("manual")}),T2=z$.object({version:z$.literal(1),lastUsedProvider:z$.string().min(1).optional(),providers:z$.record(z$.string(),L5)});function O$(){return{version:1,providers:{}}}j1();var oA={};q(oA,{InMemoryWorkspaceManager:()=>N2});import{upsertWorkspaceInfo as RO,WorkspaceManifestSchema as QW}from"@cline/shared";class N2{manifest;listeners=new Set;constructor($){this.manifest=QW.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await mf($);return this.manifest=RO(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=T1($),J=this.manifest.workspaces[f];if(J)return this.manifest=QW.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath(f);return this.manifest=QW.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=T1($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}_0();import{createHash as DO}from"node:crypto";var eA=new Set,$V=new Set;function UO($){return DO("sha256").update($).digest("hex")}function LO($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function fV($){if(!$.telemetry)return;let f=UO($.rootPath),J=$.rootCount??1;if(!eA.has(f))eA.add(f),yJ($.telemetry,{root_count:J,vcs_types:LO($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!$V.has(f)){$V.add(f);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",SJ($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function zO($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function OO($,f,J){if(f.length>0)for(let W of f)J?.log(W.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(zO).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of $)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function MO($,f){let J=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!J&&!Q)return f;return{...f??{},...J?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function JV($,f){return _O($,f)}function TO($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function NO($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||qO($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function qO($){let f=$?.trim();if(!f)return;let J=M0(f),Q=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let W=J?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;return}function wO($,f,J,Q,Z){let W=J.getProviderSettings($.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,X=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,Y={...W??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.providerId==="openai-codex"?NO({sessionId:f,configHeaders:$.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:$.apiKey??W?.auth?.accessToken??W?.apiKey}):$.headers??W?.headers,reasoning:MO($,W?.reasoning),modelCatalog:j},A={...u0(Y),...X??{}};if($.knownModels)A.knownModels=$.knownModels;if($.extensionContext)A.extensionContext=$.extensionContext;let H=$.fetch??A.fetch??Z;if(H)A.fetch=H;return A}async function QV($){let{input:f,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:X,onPluginEvent:Y,onTeamEvent:A,createSubAgentLifecycleCallbacks:V,createSpawnTool:H,localRuntime:B,readSessionMetadata:K,writeSessionMetadata:G}=$,R=R$(f.config),{modelCatalogDefaults:P,userInstructionService:F,configExtensions:D,onTeamRestored:z,...T}=B??{},L=Object.keys(T).length>0?T:void 0,{workspaceInfo:U,workspaceMetadata:w,durationMs:h,vcsType:I,initError:o}=await v9(R),V0=L?.extensionContext,$0={...V0??{},workspace:{...U,...V0?.workspace??{}},session:{...V0?.session??{},sessionId:J},logger:V0?.logger??L?.logger,telemetry:V0?.telemetry??L?.telemetry??Z};fV({telemetry:$0.telemetry,rootPath:U.rootPath,workspaceInfo:U,rootCount:1,vcsType:I,durationMs:h,initError:o,featureFlagEnabled:!0});let t=z2({cwd:f.config.cwd,workspacePath:R,rootSessionId:J,logger:L?.logger,workspaceInfo:U}),t0=fA(L?.hooks)?void 0:_2({rootSessionId:J,workspacePath:R,workspaceInfo:U}),E$=Bf([L?.hooks,t0]),i;if(JV(D,"plugins"))try{i=await D2({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:f.config.cwd,onEvent:Y,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:U,session:$0.session,client:$0.client,user:$0.user,logger:$0.logger,telemetry:$0.telemetry,automation:$0.automation}),OO(i.failures,i.warnings,L?.logger)}catch(kf){let I9=kf instanceof Error?kf.message:String(kf);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${I9})`)}let C=_Z(t?[t]:void 0,_Z(L?.extensions,sJ(i?.extensions))),G0=JV(D,"plugins")?Yf(i?.pluginPaths??[]):void 0,Q0={...f.config,...L??{},sessionId:J,hooks:E$,extensions:C,extensionContext:$0,telemetry:$0.telemetry},w0=wO(Q0,J,Q,P,X),hf=Bf([Q0.hooks,Q0.checkpoint?.enabled===!0?hA({cwd:Q0.cwd,sessionId:J,logger:Q0.logger,createCheckpoint:Q0.checkpoint?.createCheckpoint,initialRunCount:TO(f.initialMessages),readSessionMetadata:K,writeSessionMetadata:G}):void 0]),z1={...Q0,providerConfig:w0,workspaceMetadata:w,hooks:hf},Z1=f.toolPolicies??Q0.toolPolicies??j,$8=L0(W,f.capabilities),bf=$8?.requestToolApproval,_J=$8?.toolExecutors,O1=V?.(z1),zJ=new N2({currentWorkspacePath:U.rootPath,workspaces:{[U.rootPath]:U}});return{effectiveInput:f,config:z1,providerConfig:w0,workspaceMetadata:w,workspaceInfo:U,extensions:C,hooks:hf,toolPolicies:Z1,requestToolApproval:bf,pluginSandboxShutdown:i?.shutdown,runtimeBuilderInput:{config:z1,hooks:hf,extensions:C,onTeamEvent:A,createSpawnTool:H,onTeamRestored:z,onSubAgentEvent:O1?.onSubAgentEvent,onSubAgentStart:O1?.onSubAgentStart,onSubAgentEnd:O1?.onSubAgentEnd,userInstructionService:F,pluginSkillDirectories:G0,configExtensions:D,toolExecutors:_J,toolPolicies:Z1,workspaceManager:zJ,logger:z1.logger,telemetry:z1.telemetry,requestToolApproval:bf}}}import{existsSync as z5,mkdirSync as CO,readdirSync as yO,rmdirSync as SO,rmSync as EO,unlinkSync as hO}from"node:fs";import{dirname as ZV,join as _5}from"node:path";function s(){return new Date().toISOString()}function N4($){if(!$||!z5($))return;try{hO($)}catch{}}function bO($){let f=H2($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=Z4($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class ZW{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return _5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!z5(f))CO(f,{recursive:!0});return f}sessionMessagesPath($){return _5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return _5(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!z5(f)){f=ZV(f);continue}try{if(yO(f).length>0)break;SO(f)}catch{break}f=ZV(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!z5($))return;try{EO($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:Q,fileStem:Z}=bO($),W=this.sessionArtifactsDir(Q);return{messagesPath:_5(W,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as kO}from"@cline/shared/storage";_0();function WV($,f,J,Q,Z){if(J)hJ($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else EJ($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});IO($.telemetry,{workspacePath:Q})}function IO($,f){let J=kO("Hooks"),Q=U$(f.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",X=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))X.global+=1;else X.workspace+=1;Z.set(j,X)}for(let[W,j]of Z.entries())dJ($,W,j.global,j.workspace)}function jV($,f){for(let J of f.mentions)cJ($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)mJ($,"file",J.length);for(let J of f.ignoredMentions)vJ($,"file","not_found",J)}var GK={};q(GK,{ProviderSettingsManager:()=>L1});import{chmodSync as LK,existsSync as n7,mkdirSync as iy,readFileSync as ny,writeFileSync as ay}from"node:fs";import{basename as _K,dirname as a7}from"node:path";import{resolveProviderSettingsPath as ty}from"@cline/shared/storage";var O={};q(O,{writeHubDiscovery:()=>f6,writeGlobalSettings:()=>y1,withHubStartupLock:()=>J6,verifyHubConnection:()=>A1,updateMcpServerOAuthState:()=>Df,updateLocalProvider:()=>P9,uninstallPlugin:()=>P7,truncateNotificationBody:()=>GJ,toggleDisabledTool:()=>aJ,toTeamProgressLifecycleEvent:()=>m2,toProviderConfig:()=>u0,toHubStatusUrl:()=>ZQ,toHubHealthUrl:()=>Q6,toHookConfigFileName:()=>D4,summarizeUsageFromMessages:()=>K2,stopLocalHubServerGracefully:()=>PQ,startLocalOAuthServer:()=>$1,startHubWebSocketServer:()=>RJ,startHubServer:()=>RK,startClineDeviceAuth:()=>NQ,splitCoreSessionConfig:()=>U8,spawnDetachedHubServerWithRetry:()=>nf,spawnDetachedHubServer:()=>VQ,setTelemetryOptOutGlobally:()=>a3,setMcpServerDisabled:()=>Pf,setDisabledTools:()=>s9,setDisabledPlugin:()=>fj,setAutoUpdateEnabledGlobally:()=>s3,sendHubCommand:()=>hj,saveProviderOAuthCredentials:()=>p$,saveLocalProviderSettings:()=>M7,saveLocalProviderOAuthCredentials:()=>w7,sanitizeSessionToken:()=>Qf,safeParseSettings:()=>U5,safeCreateProviderConfig:()=>JW,runSubprocessEvent:()=>d2,runHook:()=>p2,reviveTeamStateDates:()=>k6,restartLocalHubIfIdleAfterStartupTimeout:()=>Y6,resolveWorkspaceHubOwnerContext:()=>Pj,resolveWorkflowsConfigSearchPaths:()=>x4,resolveSkillsConfigSearchPaths:()=>k4,resolveSharedHubOwnerContext:()=>o0,resolveSessionBackend:()=>tW,resolveRulesConfigSearchPaths:()=>I4,resolveProviderConfig:()=>z4,resolveProviderApiKeyFromSettings:()=>EQ,resolveProductionHubOwnerContext:()=>Y1,resolvePluginSkillDirectoriesFromPaths:()=>Yf,resolvePluginConfigSearchPaths:()=>G4,resolveMcpServerRegistrations:()=>B1,resolveLocalClineAuthToken:()=>y7,resolveHubUrl:()=>RQ,resolveHubOwnerContext:()=>k1,resolveHubEndpointOptions:()=>X1,resolveHubBuildId:()=>$6,resolveHooksConfigSearchPaths:()=>P4,resolveDisabledToolNames:()=>W1,resolveDisabledPluginPaths:()=>K8,resolveDefaultMcpSettingsPath:()=>T0,resolveDefaultHubPort:()=>rf,resolveDefaultHubPathname:()=>AQ,resolveDefaultHubHost:()=>YQ,resolveCoreSelectedToolIds:()=>x6,resolveCompatibleLocalHubUrl:()=>O8,resolveClineDir:()=>Bj,resolveClineDataDir:()=>m$,resolveAndLoadAgentPlugins:()=>D2,resolveAgentPluginPaths:()=>Xf,requestHubShutdown:()=>z8,requestDesktopToolApproval:()=>Y7,rememberRecoverableLocalHubUrl:()=>Q$,registerRemoteConfigSessionBlobUpload:()=>Z9,registerMcpServersFromSettingsFile:()=>Uf,registerDisposable:()=>dy,refreshProviderModelsFromSource:()=>T7,refreshOpenAICodexToken:()=>P6,refreshOcaToken:()=>L6,refreshClineToken:()=>G6,readSessionCheckpointHistory:()=>BJ,readRemoteConfigSessionBlobUploadMetadata:()=>eW,readHubDiscovery:()=>Z0,readGlobalSettings:()=>z0,readBearerToken:()=>w9,probeHubServer:()=>I1,probeHubConnection:()=>Ej,prewarmFileIndex:()=>q6,prewarmDetachedHubServer:()=>W6,prepareRemoteConfigCoreIntegration:()=>f7,parseWorkflowConfigFromMarkdown:()=>b4,parseUserCommandEnvelope:()=>uy,parseSkillConfigFromMarkdown:()=>E4,parseSettings:()=>D5,parseRuleConfigFromMarkdown:()=>h4,parseHookEventPayload:()=>l2,parseConfiguredAgentConfig:()=>fJ,normalizeWorkspacePath:()=>T1,normalizeUserInput:()=>cy,normalizeSdkError:()=>vy,normalizeRuntimeCapabilities:()=>L0,normalizeProviderId:()=>M2,normalizeOAuthProvider:()=>N7,normalizeHubWebSocketUrl:()=>Z$,noopBasicLogger:()=>my,migrateLegacyProviderSettings:()=>HJ,mergeRulesForSystemPrompt:()=>gf,mergeAgentHooks:()=>Bf,makeTeamTaskSubSessionId:()=>Q4,makeSubSessionId:()=>V2,loginOpenAICodex:()=>N8,loginOcaOAuth:()=>C8,loginLocalProvider:()=>q7,loginClineOAuth:()=>M8,loginAndSaveProviderOAuthCredentials:()=>S8,loginAndSaveLocalProviderOAuthCredentials:()=>C7,loadOpenTelemetryAdapter:()=>Ty,loadMcpSettingsFile:()=>Ff,loadLlmsConfigFromFile:()=>p7,loadConfiguredAgentConfigs:()=>I2,loadAgentPluginsFromPathsWithDiagnostics:()=>jf,loadAgentPluginsFromPaths:()=>u6,loadAgentPluginFromPath:()=>B4,listSessionHistoryFromBackend:()=>yW,listPluginToolsWithDiagnostics:()=>v5,listPluginTools:()=>r4,listMcpServerOAuthStatuses:()=>l4,listLocalProviders:()=>z7,listHookConfigFiles:()=>U$,isToolDisabledGlobally:()=>o3,isTelemetryOptedOutGlobally:()=>nJ,isSessionNotFoundError:()=>b1,isRuleEnabled:()=>MJ,isPluginDisabledGlobally:()=>$j,isOAuthProvider:()=>l$,isHubReconnectableTransportError:()=>GQ,isHubCommandTimeoutError:()=>X6,isDiscoveryFilePresent:()=>Gj,isClineAccountActionRequest:()=>O5,isBuiltInProviderId:()=>$W,isAutoUpdateEnabledGlobally:()=>t3,identifyAccount:()=>C1,hasMcpSettingsFile:()=>p1,getValidOpenAICodexCredentials:()=>q8,getValidOcaCredentials:()=>y8,getValidClineCredentials:()=>T8,getProviderOAuthCredentialsFromSettings:()=>E8,getProviderConfigFields:()=>S7,getProviderConfig:()=>X5,getProviderAuthStorageId:()=>SQ,getProviderAuthHandler:()=>B0,getPersistedProviderApiKey:()=>z6,getMcpServerOAuthState:()=>Rf,getLocalProviderModels:()=>O7,getLiveModelsCatalog:()=>O2,getFileIndex:()=>v1,getCurrentContextSize:()=>TZ,getCoreHeadlessToolNames:()=>J4,getCoreDefaultEnabledToolIds:()=>I6,getCoreBuiltinToolCatalog:()=>ff,getCoreAcpToolNames:()=>g6,getClineDefaultSystemPrompt:()=>qy,generateWorkspaceInfoWithDiagnostics:()=>J8,generateWorkspaceInfo:()=>mf,formatRulesForSystemPrompt:()=>xf,formatProviderOAuthApiKey:()=>hQ,formatDisplayUserInput:()=>gy,filterExtensionToolRegistrations:()=>sJ,filterDisabledTools:()=>x$,filterDisabledPluginPaths:()=>tJ,fetchClineRecommendedModels:()=>d7,executeClineAccountAction:()=>M5,ensureHubWebSocketServer:()=>C9,ensureHubServer:()=>DK,ensureDetachedHubServer:()=>zj,ensureCustomProvidersLoaded:()=>K9,ensureCompatibleLocalHubUrl:()=>u$,enrichPromptWithMentions:()=>Q2,emptyWorkspaceManifest:()=>ky,emptyStoredProviderSettings:()=>O$,discoverPluginModulePaths:()=>F4,deriveSubsessionStatus:()=>W4,deleteLocalProvider:()=>R9,defineLlmsConfig:()=>l7,createWorkflowsConfigDefinition:()=>v4,createUserInstructionConfigService:()=>M$,createToolPoliciesWithPreset:()=>C6,createTool:()=>by,createTeamName:()=>X9,createSubprocessHooks:()=>f9,createSpawnAgentTool:()=>F$,createSkillsConfigDefinition:()=>g4,createSessionHost:()=>u2,createRuntimeHost:()=>u2,createRulesConfigDefinition:()=>m4,createRemoteConfigSessionMessagesArtifactUploader:()=>$7,createProviderConfig:()=>fW,createOpenTelemetryTelemetryService:()=>D8,createOAuthClientCallbacks:()=>q2,createMcpTools:()=>E2,createLocalHubScheduleRuntimeHandlers:()=>PK,createLlmsSdk:()=>i7,createInitialAccumulatedUsage:()=>K0,createInMemoryHubOwnerContext:()=>Kj,createHubServerUrl:()=>s0,createHubAuthToken:()=>eJ,createHookConfigFileHooks:()=>U4,createHookConfigFileExtension:()=>z2,createHookAuditHooks:()=>_2,createDisabledMcpToolPolicy:()=>p4,createDisabledMcpToolPolicies:()=>m5,createDelegatedAgentConfigProvider:()=>K$,createDelegatedAgent:()=>G$,createDefaultToolsWithPreset:()=>y6,createDefaultTools:()=>V$,createDefaultMcpServerClientFactory:()=>S2,createDefaultExecutors:()=>Z2,createCoreSettingsService:()=>_f,createCoreSessionSnapshot:()=>G1,createContributionRegistry:()=>hy,createContextCompactionPrepareTurn:()=>g8,createConfiguredTelemetryService:()=>E1,createConfiguredTelemetryHandle:()=>pf,createConfiguredAgentTools:()=>x2,createClineTelemetryServiceMetadata:()=>Ey,createClineTelemetryServiceConfig:()=>Sy,createBuiltinTools:()=>Jf,createAgentTeamsTools:()=>$f,createAgentRuntime:()=>ry,createAgentHooksExtension:()=>U2,connectToHub:()=>A6,completeClineDeviceAuth:()=>qQ,clearPrivateModelsCatalogCache:()=>oZ,clearLiveModelsCatalogCache:()=>sZ,clearHubDiscovery:()=>C0,captureWorkspacePathResolved:()=>d3,captureWorkspaceInitialized:()=>yJ,captureWorkspaceInitError:()=>SJ,captureToolUsage:()=>IJ,captureTokenUsage:()=>bJ,captureTaskRestarted:()=>hJ,captureTaskCreated:()=>EJ,captureTaskCompleted:()=>A8,captureSubagentExecution:()=>H8,captureSkillUsed:()=>xJ,captureSdkError:()=>yy,captureProviderConfigured:()=>l3,captureProviderApiError:()=>V8,captureModeSwitch:()=>kJ,captureMentionUsed:()=>mJ,captureMentionSearchResults:()=>cJ,captureMentionFailed:()=>vJ,captureHookDiscovery:()=>dJ,captureExtensionActivated:()=>u3,captureDiffEditFailure:()=>gJ,captureConversationTurnEvent:()=>cf,captureCompactionSkipped:()=>pJ,captureCompactionExecuted:()=>lJ,captureAuthSucceeded:()=>q1,captureAuthStarted:()=>N1,captureAuthLoggedOut:()=>f$,captureAuthFailed:()=>w1,captureAgentTeamCreated:()=>uJ,captureAgentCreated:()=>J$,buildWorkspaceMetadata:()=>Q8,buildTeamProgressSummary:()=>g2,buildSdkErrorProperties:()=>wy,buildRemoteConfigSessionBlobUploadMetadata:()=>J9,buildDelegatedAgentConfig:()=>o$,buildConfiguredAgentToolName:()=>JJ,buildConfiguredAgentToolDescriptors:()=>QJ,bootstrapAgentTeams:()=>A2,authorizeMcpServerOAuth:()=>I5,addLocalProvider:()=>_7,accumulateUsageTotals:()=>Y0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>S4,UnifiedConfigFileWatcher:()=>Gf,ToolPresets:()=>v0,TelemetryService:()=>df,TelemetryLoggerSink:()=>R8,TEAM_TOOL_NAMES:()=>Y2,SubprocessSandbox:()=>P2,StoredProviderSettingsSchema:()=>T2,StoredProviderSettingsEntrySchema:()=>L5,SqliteTeamStore:()=>wf,SqliteSessionStore:()=>P1,SessionVersioningService:()=>y$,SessionVersioningError:()=>h0,SessionSource:()=>R0,SessionNotFoundError:()=>h1,SapSettingsSchema:()=>F5,SKILLS_CONFIG_DIRECTORY_NAME:()=>y4,SESSION_STATUSES:()=>j4,SESSION_NOT_FOUND_ERROR_CODE:()=>g$,SDK_ERROR_TELEMETRY_EVENT:()=>ly,RpcClineAccountService:()=>w4,RemoteRuntimeHost:()=>k2,ReasoningSettingsSchema:()=>H5,RULES_CONFIG_DIRECTORY_NAME:()=>S5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>Q9,ProviderSettingsSchema:()=>_$,ProviderSettingsManager:()=>L1,ProviderProtocolSchema:()=>Y5,ProviderIdSchema:()=>M4,ProviderClientSchema:()=>A5,OpenTelemetryProvider:()=>lf,OcaSettingsSchema:()=>P5,OPENAI_COMPATIBLE_PROVIDERS:()=>_4,NodeHubClient:()=>e0,NoOpFeatureFlagsProvider:()=>Tf,NativeHubTransportAdapter:()=>PJ,ModelCatalogSettingsSchema:()=>R5,LocalRuntimeHost:()=>U1,Llms:()=>Ny,InMemoryWorkspaceManager:()=>N2,InMemoryMcpManager:()=>Lf,HubUIClient:()=>LQ,HubTransportError:()=>O0,HubSessionClient:()=>UQ,HubServerTransport:()=>e2,HubScheduleService:()=>vf,HubScheduleCommandService:()=>If,HubRuntimeHost:()=>r1,HubCommandError:()=>af,HookEventPayloadSchema:()=>$9,HookEventNameSchema:()=>e5,HookConfigFileName:()=>L2,HOOK_CONFIG_FILE_EVENT_MAP:()=>R4,HOOKS_CONFIG_DIRECTORY_NAME:()=>a6,GlobalSettingsSchema:()=>B8,GcpSettingsSchema:()=>K5,FileTeamPersistenceStore:()=>_9,FeatureFlagsService:()=>Mf,FeatureFlagDefaultValue:()=>xy,FEATURE_FLAGS:()=>Iy,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>q9,DefaultToolNames:()=>H0,DefaultRuntimeBuilder:()=>n2,DefaultLlmsSdk:()=>KJ,DEFAULT_MODELS_CATALOG_URL:()=>Q5,DEFAULT_HUB_PORT:()=>jQ,DEFAULT_HUB_PATHNAME:()=>XQ,DEFAULT_HUB_HOST:()=>WQ,CoreSettingsService:()=>T$,CoreSessionService:()=>D1,ContributionRegistry:()=>Cy,ClineCore:()=>YJ,ClineAccountService:()=>q4,ChatViewStateSchema:()=>c7,ChatSummarySchema:()=>N9,ChatSessionStatusSchema:()=>O9,ChatSessionConfigSchema:()=>z9,ChatMessageSchema:()=>T9,ChatMessageRoleSchema:()=>M9,CORE_TELEMETRY_EVENTS:()=>g,CORE_BUILD_VERSION:()=>u7,BrowserWebSocketHubAdapter:()=>FJ,BUILT_IN_PROVIDER_IDS:()=>eZ,BUILT_IN_PROVIDER:()=>O4,AzureSettingsSchema:()=>G5,AwsSettingsSchema:()=>B5,AuthSettingsSchema:()=>V5,AgentTeamsRuntime:()=>Of,AgentTeam:()=>c2,Agent:()=>py,ALL_DEFAULT_TOOL_NAMES:()=>o1});M(O,Sl);import*as Ny from"@cline/llms";import{buildClineSystemPrompt as qy,buildSdkErrorProperties as wy,ContributionRegistry as Cy,captureSdkError as yy,createClineTelemetryServiceConfig as Sy,createClineTelemetryServiceMetadata as Ey,createContributionRegistry as hy,createTool as by,emptyWorkspaceManifest as ky,FEATURE_FLAGS as Iy,FeatureFlagDefaultValue as xy,formatDisplayUserInput as gy,noopBasicLogger as my,normalizeSdkError as vy,normalizeUserInput as cy,parseUserCommandEnvelope as uy,registerDisposable as dy,SDK_ERROR_TELEMETRY_EVENT as ly}from"@cline/shared";import"@cline/shared/storage";var YV={};q(YV,{isClineAccountActionRequest:()=>O5,executeClineAccountAction:()=>M5,RpcClineAccountService:()=>w4,ClineAccountService:()=>q4});function xO($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function XV($,f,J){let Q=xO(J);if(Q)return Q;let Z=f.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${W}`}return`Cline account request failed with status ${$}`}class q4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,W=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let X=await j.text(),Y;if(X.trim())try{Y=JSON.parse(X)}catch{if(!j.ok)throw Error(XV(j.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(XV(j.status,X,Y));if(typeof Y==="object"&&Y!==null){let A=Y;if(typeof A.success==="boolean"){if(!A.success)throw Error(A.error||"Cline account request failed");if(A.data!==void 0)return A.data}}if(Y===void 0||Y===null)throw Error("Cline account response payload was empty");return Y}finally{clearTimeout(W)}}}function O5($){return $.action==="clineAccount"}async function M5($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class w4{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var AV={};q(AV,{createOAuthClientCallbacks:()=>q2});function q2($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((Q)=>{$.onOpenUrlError?.({url:f,error:Q})})}catch(Q){$.onOpenUrlError?.({url:f,error:Q})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var XB={};q(XB,{ClineCore:()=>YJ});function VV($){if($===!0)return{};if(!$)return;return $}function HV($){if($==="user")return"global";return $}class WW{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function BV($){let{host:f}=$;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||R0.CLI,interactive:!1,config:{providerId:M2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:vO(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content),delivery:Q.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:mO(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function T5($){let f=gO($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,W=$.context?.telemetry??$.telemetry;if(!f&&!J&&!Q&&!Z&&!W)return $.context;return{...$.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...f?{automation:f}:{}}}function gO($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function mO($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function vO($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var oV={};q(oV,{createCoreSettingsService:()=>_f,CoreSettingsService:()=>T$});import{existsSync as c5}from"node:fs";import{basename as aV,isAbsolute as XT,relative as YT}from"node:path";var TV={};q(TV,{resolveWorkflowsConfigSearchPaths:()=>x4,resolveSkillsConfigSearchPaths:()=>k4,resolveRulesConfigSearchPaths:()=>I4,parseWorkflowConfigFromMarkdown:()=>b4,parseSkillConfigFromMarkdown:()=>E4,parseRuleConfigFromMarkdown:()=>h4,createWorkflowsConfigDefinition:()=>v4,createUserInstructionConfigService:()=>M$,createSkillsConfigDefinition:()=>g4,createRulesConfigDefinition:()=>m4,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>S4,UnifiedConfigFileWatcher:()=>Gf,SKILLS_CONFIG_DIRECTORY_NAME:()=>y4,RULES_CONFIG_DIRECTORY_NAME:()=>S5});import{createHash as cO}from"node:crypto";import{watch as uO}from"node:fs";import{readdir as dO,readFile as lO}from"node:fs/promises";import{join as pO}from"node:path";function rO($){return cO("sha1").update($).digest("hex")}function FV($){return Boolean($&&typeof $==="object"&&"code"in $)}function KV($){return FV($)&&$.code==="ENOENT"}function GV($){return FV($)&&($.code==="EACCES"||$.code==="EPERM")}class Gf{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let Q of J.directories){let Z=this.baseTypesByDirectory.get(Q);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(Q,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,Q])=>[J,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=uO(f,()=>{let Q=this.watchedTypesByDirectory.get(f);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:f})})}catch(J){if(!KV(J)&&!GV(J)){let Q=$.get(f);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[Z,W]of Q.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:W.filePath})}for(let[Z,W]of f.entries()){let j=Q.get(Z);if(j&&j.filePath===W.filePath&&j.fingerprint===W.fingerprint)continue;this.emit({kind:"upsert",record:{type:W.type,id:Z,item:W.item,filePath:W.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let Q of $.directories){J.add(Q);let Z=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:X}=W;if(J.add(W.directoryPath),$.includeFile&&!$.includeFile(j,X))continue;try{let Y=await lO(X,"utf8"),A={type:$.type,directoryPath:W.directoryPath,fileName:j,filePath:X,content:Y},V=$.parseFile(A),H=$.resolveId(V,A).trim();if(!H)continue;f.set(H,{type:$.type,id:H,item:V,filePath:X,fingerprint:rO(Y)})}catch(Y){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Y,filePath:X})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let Q of J){let Z=$.get(Q);if(Z)Z.add(f);else $.set(Q,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await dO($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:pO($,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch(f){if(KV(f)||GV(f))return[];throw f}}}import{readdir as XW,readFile as iO,stat as jW}from"node:fs/promises";import{basename as l1,dirname as nO,extname as q5,join as S0,resolve as C4}from"node:path";import{AGENTS_RULES_FILE_NAME as PV,RULES_CONFIG_DIRECTORY_NAME as S5,resolveGlobalAgentsRulesPath as aO,resolveRulesConfigSearchPaths as tO,resolveSkillsConfigSearchPaths as sO,resolveWorkflowsConfigSearchPaths as oO,SKILLS_CONFIG_DIRECTORY_NAME as y4,WORKFLOWS_CONFIG_DIRECTORY_NAME as S4}from"@cline/shared/storage";import eO from"yaml";var N5="SKILL.md",$M="managed.json",fM=new Set([".md",".markdown",".txt"]);function YW($){return $.trim().toLowerCase()}function w2($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"||f?.code==="ELOOP"}function w5($){return fM.has(q5($).toLowerCase())}function RV($){let f=[],J=new Set;for(let Q of $){let Z=C4(Q);if(J.has(Z))continue;J.add(Z),f.push(Q)}return f}function JM($){let f=[...$?.directories??k4($?.workspacePath)];if($?.pluginSkillDirectories)f.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)f.push(...SA({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return RV(f)}async function AW($){try{let f=await XW($,{withFileTypes:!0}),J=[];for(let Q of f){if(!Q.isDirectory())continue;let Z=S0($,Q.name),W=S0(Z,$M);try{let j=await iO(W,"utf8"),X=JSON.parse(j);if(X&&typeof X==="object")J.push(Z)}catch(j){if(w2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch(f){if(w2(f))return[];throw f}}function VW($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=eO.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}catch(W){let j=W instanceof Error?W.message:String(W);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function C5($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let Q=$.trim();if(!Q&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return Q||void 0}function C2($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function QM($,f){if(l1($.filePath).toLowerCase()!==PV.toLowerCase())return l1($.filePath,q5($.filePath));if(f&&C4($.filePath)===C4(f,PV))return"Workspace AGENTS.md";if(C4($.filePath)===C4(aO()))return"Global AGENTS.md";return l1($.filePath,q5($.filePath))}function E4($,f){let{data:J,body:Q,parseError:Z}=VW($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in skill file.");let X=C5(J.name,"name",!1)??f.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:C5(J.description,"description",!1),disabled:C2(J.disabled,"disabled")??(C2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function h4($,f){let{data:J,body:Q,parseError:Z}=VW($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in rule file.");let j=C5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:C2(J.disabled,"disabled")??(C2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function b4($,f){let{data:J,body:Q,parseError:Z}=VW($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in workflow file.");let j=C5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:C2(J.disabled,"disabled")??(C2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function k4($){return sO($)}function I4($){return tO($)}function x4($){return oO($)}async function DV($){if(l1($)===".cline"){let f=await AW($);return(await Promise.all(f.map((Q)=>DV(S0(Q,y4))))).flat()}try{let f=await XW($,{withFileTypes:!0}),J=[];for(let Q of f){if(Q.isFile()&&Q.name===N5){J.push({directoryPath:$,fileName:Q.name,filePath:S0($,Q.name)});continue}let Z=S0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await jW(Z).then((j)=>j.isDirectory()).catch((j)=>{if(w2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:N5,filePath:S0(Z,N5)})}return J}catch(f){if(w2(f))return[];throw f}}async function y5($){if(l1($)===".cline"){let f=await AW($);return(await Promise.all(f.map((Q)=>y5(S0(Q,"rules.md"))))).flat()}try{if((await jW($)).isFile())return[{directoryPath:nO($),fileName:l1($),filePath:$}]}catch(f){if(!w2(f))throw f}try{let J=(await XW($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&w5(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:S0($,Z.name)})),Q=S0($,"AGENTS.md");try{if((await jW(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch(f){if(w2(f))return[];throw f}}async function ZM($){if(l1($)===".cline"){let f=await AW($);return(await Promise.all(f.map((Q)=>y5(S0(Q,S4))))).flat()}return y5($)}function g4($){let f=JM($),J=$?.workspacePath?S0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?RV([...f,J]):f,discoverFiles:DV,includeFile:(Q)=>Q===N5,parseFile:(Q)=>E4(Q.content,l1(Q.directoryPath)),resolveId:(Q)=>YW(Q.name)}}function m4($){let f=$?.directories??I4($?.workspacePath),J=$?.workspacePath?S0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:y5,includeFile:(Q,Z)=>Q===".clinerules"||w5(Q)||w5(Z),parseFile:(Q)=>h4(Q.content,QM(Q,$?.workspacePath)),resolveId:(Q)=>YW(Q.name)}}function v4($){let f=$?.directories??x4($?.workspacePath),J=$?.workspacePath?S0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:ZM,includeFile:(Q)=>w5(Q),parseFile:(Q)=>b4(Q.content,l1(Q.filePath,q5(Q.filePath))),resolveId:(Q)=>YW(Q.name)}}function UV($){let f=[g4($?.skills),m4($?.rules),v4($?.workflows)];return new Gf(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as LV}from"@cline/shared";function WM($,f){if($.description?.trim())return LV($.description,".");if(f==="workflow")return;return LV($.instructions,".")}function jM($){return $.disabled!==!0}function _V($,f){return[...$.getSnapshot(f).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>jM(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:WM(Q.item,f),kind:f})).sort((J,Q)=>J.name.localeCompare(Q.name))}function c4($){let f=new Map;for(let J of[..._V($,"workflow"),..._V($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function zV($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let Q=J[1];if(!Q)return $;let Z=Q.length+1,W=$.slice(Z),j=c4(f).find((X)=>X.name===Q);return j?`${j.instructions}${W}`:$}function E5($){return $.trim().replace(/^\/+/,"").toLowerCase()}function XM($){if(!$||$.length===0)return;let f=$.map(E5).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function YM($,f,J){if(!J)return!0;let Q=E5($),Z=E5(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function u4($,f){let J=XM(f);return[...$.getSnapshot("skill").entries()].map(([Z,W])=>{let j=W.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>YM(Z.id,Z.name,J))}function AM($,f){return u4($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,Q)=>J.localeCompare(Q))}function VM($,f,J){let Q=E5(f);if(!Q)return{error:"Missing skill name."};let Z=u4($,J),W=Z.find((V)=>V.id===Q);if(W){let{skill:V}=W;if(V.disabled===!0)return{error:`Skill "${V.name}" is configured but disabled.`};return{id:W.id,skill:V}}let j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=Z.filter(({id:V})=>{if(V===j)return!0;return V.endsWith(`:${j}`)}),Y=X.filter(({skill:V})=>V.disabled!==!0);if(Y.length===1){let{id:V,skill:H}=Y[0];return{id:V,skill:H}}if(Y.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${Y.map(({id:V})=>V).join(", ")}`};if(X.length===1){let{skill:V}=X[0];return{error:`Skill "${V.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${X.map(({id:V})=>V).join(", ")}`};let A=AM($,J);return{error:A.length>0?`Skill "${f}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function HW($,f=Promise.resolve(),J){let Q=new Set,Z=async(W,j)=>{await f;let X=VM($,W,J);if("error"in X)return X.error;let{id:Y,skill:A}=X;if(Q.has(Y))return`Skill "${A.name}" is already running.`;Q.add(Y);try{let V=j?.trim(),H=V?`
459
- <command-args>${V}</command-args>`:"",B=A.description?.trim()?`Description: ${A.description.trim()}
458
+ ${Z}`;return Q||Z}function __($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function O_($,J){return $.filter((Q)=>__(Q.name,J))}function T_($,J){return E1(O_($,J))}function M_($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return{};return{beforeRun:async(Q)=>{for(let Z of J){let W=await Z.beforeRun?.(Q);if(W?.stop)return W}return},afterRun:async(Q)=>{for(let Z of J)await Z.afterRun?.(Q)},beforeModel:async(Q)=>{let Z=Q.request,W;for(let j of J){let f=await j.beforeModel?.({...Q,request:Z});if(!f)continue;if(f.stop)return f;W={...W,...f,options:aY(W?.options,f.options)},Z={...Z,...f.messages?{messages:f.messages}:{},...f.tools?{tools:f.tools}:{},...f.options?{options:aY(Z.options,f.options)}:{}}}return W},afterModel:async(Q)=>{for(let Z of J){let W=await Z.afterModel?.(Q);if(W?.stop)return W}return},beforeTool:async(Q)=>{let Z=Q.input,W;for(let j of J){let f=await j.beforeTool?.({...Q,input:Z});if(!f)continue;if(f.stop||f.skip)return f;if(W={...W,...f},Object.hasOwn(f,"input"))Z=f.input}return W},afterTool:async(Q)=>{let Z=Q.result,W;for(let j of J){let f=await j.afterTool?.({...Q,result:Z});if(!f)continue;if(f.stop)return f;if(W={...W,...f},f.result)Z=f.result}return W},onEvent:async(Q)=>{for(let Z of J)await Z.onEvent?.(Q)}}}class K${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 S7;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,J={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=J.logger??$.logger,this.telemetry=J.telemetry??$.telemetry,this.createAgentRuntimeImpl=J.createAgentRuntimeImpl??D_,this.conversation=new q7($.initialMessages),this.messageBuilder=new O7,this.contributionRegistry=U_({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Q=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new w7({maxConsecutiveMistakes:Q,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,f,X)=>q_(this.logger,j,f,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,f)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Z=$.execution?.loopDetection;this.loopDetectionDisabled=Z===!1;let W=Z===!1||Z===void 0?void 0:Z;this.loopTracker=new N7(W)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let J=new Set(this.config.tools.map((Z)=>Z.name)),Q=[...this.config.tools];for(let Z of $)if(!J.has(Z.name))Q.push(Z),J.add(Z.name);this.config={...this.config,tools:Q}}updateConnection($){let J={...this.config};if($.providerId!==void 0)J.providerId=$.providerId;if($.modelId!==void 0)J.modelId=$.modelId;if($.apiKey!==void 0)J.apiKey=$.apiKey;if($.baseUrl!==void 0)J.baseUrl=$.baseUrl;if($.headers!==void 0)J.headers=$.headers;if($.providerConfig!==void 0)J.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)J.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=J}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let J=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=J,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(J)}async shutdown($,J){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,J,Q){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!1})}continue($,J,Q){return this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let J of this.contributionRegistry.getRegisteredRules()){let Q=await z_(J);if(Q)$.push(Q)}return L_(this.config.systemPrompt,$)}executeRun($){let J;return J=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===J)this.activeRunPromise=null}),this.activeRunPromise=J,J}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let J=new Date,Q=$.userMessage;if(Q!==void 0){let F=await N_(Q,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Z=await this.composeSystemPrompt(),W=cY(this.config,this.logger,this.telemetry),j=new Map;for(let F of this.contributionRegistry.getRegisteredTools())j.set(F.name,F);let f=T_([...j.values()],this.config.toolPolicies),X=new Map;for(let F of f)X.set(F.name,F);for(let F of this.config.tools)X.set(F.name,F);let Y=this.conversation.getConversationId(),V=sY(this.config),H=Array.from(X.values()),B=v5(this.conversation.getMessages()),A=rY({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:Y,parentAgentId:this.parentAgentId,model:W,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:V?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[WY]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(V,H),initialMessages:B,systemPrompt:Z}),K=this.createAgentRuntimeImpl(A);if(this.activeRuntime=K,this.abortRequested)K.abort(this.abortReason);let G=K.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,D;try{if($.isContinue)R=await K.continue(void 0);else R=await K.run("")}catch(F){D=F instanceof Error?F:Error(String(F))}finally{G();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=B8(R.messages);this.conversation.replaceMessages(F)}let U=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:D,startedAt:J,endedAt:U})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=M_([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((J)=>J.hooks)]);return{...$,beforeModel:async(J)=>{let Q=await $.beforeModel?.(J);if(Q?.stop)return Q;let Z=Q?.messages??J.request.messages,W=await this.prepareMessagesForModelRequest(Z);return{...Q,messages:W}}}}createRuntimePrepareTurn($,J){let Q=this.config.prepareTurn;if(!Q)return;return async(Z)=>{let W=B8(Z.messages),j=await this.prepareProviderMessagesForApi(W),f=await Q({agentId:Z.agentId,conversationId:Z.conversationId??this.conversation.getConversationId(),parentAgentId:Z.parentAgentId??null,iteration:Z.iteration,messages:W,apiMessages:j,abortSignal:Z.signal??new AbortController().signal,systemPrompt:Z.systemPrompt??"",tools:J,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Z.emitStatusNotice});if(!f)return;return{...f.messages?{messages:v5(f.messages)}:{},...f.systemPrompt!==void 0?{systemPrompt:f.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let J=await this.prepareProviderMessagesForApi(c5($));return v5(J)}async prepareProviderMessagesForApi($){let J=$,Q=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Z of Q)J=await Z.build(J);return this.messageBuilder.buildForApi(J)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let J=this.toolStartedAt.get($.toolCall.toolCallId),Q=new Date,Z=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let W=$.message.content.find((Y)=>Y.type==="tool-result"),j=W?.type==="tool-result"&&W.isError===!0,f=j?R_(W?.type==="tool-result"?W.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Z,output:W?.type==="tool-result"?W.output:void 0,error:f,durationMs:J===void 0?0:Q.getTime()-J.getTime(),startedAt:J??Q,endedAt:Q};if(this.currentRunToolCalls.push(X),j){if(this.currentTurnFailedTools+=1,f)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${f}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let J=this.currentTurnFailedTools,Q=this.currentTurnSuccessfulTools;if(J>0&&Q===0){let Z=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${J} tool call(s) failed${Z?`: ${Z}`:""}`})}else if(Q>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let J of this.eventAdapter.translate($))this.emitLegacyEvent(J)}syncConversationFromRuntimeMessage($,J){if($.length>0){this.conversation.replaceMessages(B8($));return}if(J.length===0)return;let Q=new Set(this.conversation.getMessages().map((W)=>W.id).filter((W)=>typeof W==="string")),Z=B8(J).filter((W)=>!W.id||!Q.has(W.id));if(Z.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Z])}emitLegacyEvent($){for(let J of this.listeners)try{J($)}catch(Q){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Q})}}inspectLoopForToolCall($,J,Q){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Z=this.loopTracker.inspect({name:$,input:J});if(Z.kind==="ok")return;if(Z.kind==="soft"){if(Z.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Z.message}]});return}this.enqueueMistakeRecord({iteration:Q,reason:"tool_execution_failed",forceAtLimit:!0,details:Z.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let J=await this.mistakeTracker.record($);if(J.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:J.message}]}),this.activeRuntime?.abort(J.reason??J.message)})}buildLegacyResult($){let{runResult:J,thrownError:Q,startedAt:Z,endedAt:W}=$,j=W.getTime()-Z.getTime(),f=Q?"error":P_(J),X=J?.outputText||(J?.status==="failed"?J.error?.message:void 0)||"",Y=J?{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens>0?J.usage.cacheReadTokens:void 0,cacheWriteTokens:J.usage.cacheWriteTokens>0?J.usage.cacheWriteTokens:void 0,totalCost:J.usage.totalCost}:this.currentRunUsage,V=J?B8(J.messages):this.conversation.getMessages(),H=sY(this.config);if(Q)throw Q;return{text:X,usage:Y,messages:V,toolCalls:this.currentRunToolCalls,iterations:J?.iterations??0,finishReason:f,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Z,endedAt:W,durationMs:j}}}function q_($,J,Q,Z){if(!$)return;if(J==="debug"){$.debug(Q,Z);return}if(J==="error"&&$.error){$.error(Q,Z);return}let W=J==="warn"?"warn":J==="error"?"error":"info";$.log(Q,{...Z,severity:W})}function P_($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function N_($,J,Q,Z){let{buildInitialUserContent:W}=await Promise.resolve().then(() => nY);return W($,J,Q,Z)}function sY($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let J=U7($);if(J?.[$.modelId])return J[$.modelId];return}import{buildClineSystemPrompt as oY}from"@cline/shared";function tY($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return oY({ide:J.clineIdeName?.trim()||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,rules:`# Team Teammate Role
459
+ ${Q}`,platform:J.clinePlatform,metadata:J.workspaceMetadata})}function eY($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return oY({ide:J.clineIdeName||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,overridePrompt:Q,metadata:J.workspaceMetadata,platform:J.clinePlatform})}function G$($){let J={...$};return{getRuntimeConfig:()=>J,getConnectionConfig:()=>({providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking}),updateConnectionDefaults:(Q)=>{J={...J,...Q}}}}function t$($){let J=$.configProvider.getRuntimeConfig(),Q=$.kind==="teammate"?tY($.prompt,J):eY($.prompt,J);return{...$.configProvider.getConnectionConfig(),systemPrompt:Q,tools:$.tools,maxIterations:$.maxIterations??J.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:J.hooks,extensions:J.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:J.logger,role:$.role}}function F$($){let J=t$($),Q=new K$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);return Q}var C_=C7.object({systemPrompt:C7.string().describe("System prompt defining the sub-agent's behavior"),task:C7.string().describe("Task for the sub-agent to complete")});function D$($){return w_({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:S_(C_),execute:async(J,Q)=>{let Z=$.createSubAgentTools?await $.createSubAgentTools(J,Q):$.subAgentTools??[],W=F$({kind:"subagent",prompt:J.systemPrompt,configProvider:$.configProvider,tools:Z,maxIterations:$.defaultMaxIterations,parentAgentId:Q.agentId,abortSignal:Q.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=W.getAgentId(),f=W.getConversationId(),X=Q.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:f,parentAgentId:X,input:J})}catch{}try{let Y=await W.run(J.task),V={text:Y.text,iterations:Y.iterations,finishReason:Y.finishReason,usage:{inputTokens:Y.usage.inputTokens,outputTokens:Y.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,result:V,agentResult:Y})}catch{}return V}catch(Y){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,error:Y instanceof Error?Y:Error(String(Y))})}catch{}throw Y}},timeoutMs:300000,retryable:!1})}import{createTool as Y0,TEAM_AWAIT_TIMEOUT_MS as y_,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as E_,TEAM_RUN_TEXT_PREVIEW_LIMIT as b_,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as h_,TeamAttachOutcomeFragmentInputSchema as $V,TeamAwaitRunsInputSchema as JV,TeamBroadcastInputSchema as QV,TeamBroadcastToolResultSchema as k_,TeamCancelRunInputSchema as ZV,TeamCancelRunToolResultSchema as I_,TeamCleanupInputSchema as WV,TeamCleanupToolResultSchema as x_,TeamCreateOutcomeInputSchema as jV,TeamCreateOutcomeToolResultSchema as g_,TeamFinalizeOutcomeInputSchema as fV,TeamFinalizeOutcomeToolResultSchema as m_,TeamListOutcomesInputSchema as XV,TeamListRunsInputSchema as YV,TeamMailboxMessageToolResultSchema as v_,TeamMissionLogInputSchema as VV,TeamMissionLogToolResultSchema as c_,TeamOutcomeFragmentToolResultSchema as HV,TeamOutcomeToolResultSchema as u_,TeamReadMailboxInputSchema as BV,TeamReviewOutcomeFragmentInputSchema as AV,TeamRunTaskInputSchema as KV,TeamRunTaskToolResultSchema as y7,TeamRunToolSummarySchema as E7,TeamSendMessageInputSchema as GV,TeamSendMessageToolResultSchema as d_,TeamShutdownTeammateInputSchema as FV,TeamSimpleAgentStatusToolResultSchema as DV,TeamSpawnTeammateInputSchema as UV,TeamStatusInputSchema as RV,TeamStatusToolResultSchema as l_,TeamTaskInputSchema as zV,TeamTaskToolResultSchema as V6,validateWithZod as k,zodToJsonSchema as V0}from"@cline/shared";function LV($,J){let Q=$.replace(/\s+/g," ").trim();if(Q.length<=J)return Q;return`${Q.slice(0,Math.max(0,J-3)).trimEnd()}...`}function e$($,J){if($===void 0)throw Error(`Missing required field: ${J}`);return $}function p_($){let J=$.result;if(!J)return;return{textPreview:LV(J.text,b_),iterations:J.iterations,finishReason:J.finishReason,durationMs:J.durationMs,usage:{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens,cacheWriteTokens:J.usage.cacheWriteTokens,totalCost:J.usage.totalCost}}}function d5($){return $?.toISOString()}function b7($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:LV($.message,E_),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:d5($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:d5($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:d5($.heartbeatAt),lastProgressAt:d5($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:p_($)}}function r_($){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 _V($){let J=[];if($.createBaseTools)J.push(...$.createBaseTools());J.push(...$2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:t$({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:J,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function K8($){let J=$.leadAgentId??"lead",Q=$.restoredFromPersistence===!0,Z=$2({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),W=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;_V({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),W.push(j.agentId)}return{tools:Z,restoredFromPersistence:Q,restoredTeammates:W}}function $2($){let J=$.allowSpawn??!0,Q=$.includeSpawnTool??!0,Z=$.includeManagementTools??!0,W=[];if(Q)W.push(Y0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:V0(UV),execute:async(f)=>{let X=k(UV,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!J)throw Error("Spawning teammates is disabled in this context.");let Y={agentId:X.agentId,rolePrompt:X.rolePrompt};if(_V({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Y}),!Z)$.onLeadToolsUnlocked?.($2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return k(DV,{agentId:X.agentId,status:"spawned"})}}));if(!Z)return W;W.push(Y0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:V0(FV),execute:async(f)=>{let X=k(FV,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),k(DV,{agentId:X.agentId,status:"stopped"})}})),W.push(Y0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:V0(RV),execute:async(f)=>{return k(RV,f),k(l_,$.runtime.getSnapshot())}})),W.push(Y0({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:V0(zV),execute:async(f)=>{let X=k(zV,f);switch(X.action){case"create":{let Y=new Set(h_.create??[]),V=Object.entries(f).filter(([B,A])=>Y.has(B)&&A!=null).map(([B])=>B),H=$.runtime.createTask({title:e$(X.title,"title"),description:e$(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return k(V6,{action:"create",taskId:H.id,status:H.status,...V.length>0?{ignoredFields:V,note:`Ignored fields for action=create: ${V.join(", ")}`}:{}})}case"list":return k(V6,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let Y=$.runtime.claimTask(e$(X.taskId,"taskId"),$.requesterId);return k(V6,{action:"claim",taskId:Y.id,status:Y.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let Y=$.runtime.completeTask(e$(X.taskId,"taskId"),$.requesterId,e$(X.summary,"summary"));return k(V6,{action:"complete",taskId:Y.id,status:Y.status})}case"block":{let Y=$.runtime.blockTask(e$(X.taskId,"taskId"),$.requesterId,e$(X.reason,"reason"));return k(V6,{action:"block",taskId:Y.id,status:Y.status})}}}}));let j=new Map;return W.push(Y0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:V0(KV),execute:async(f)=>{let X=k(KV,f);if(X.runMode==="async"){let H=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return k(y7,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${H.id}.`,runId:H.id})}let Y=j.get(X.agentId);if(Y){let H=await Y;return k(y7,{...H,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let V=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((H)=>k(y7,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(X.agentId)});return j.set(X.agentId,V),await V}})),W.push(Y0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:V0(ZV),execute:async(f)=>{let X=k(ZV,f),Y=$.runtime.cancelRun(X.runId,X.reason);return k(I_,{runId:Y.id,status:Y.status})}})),W.push(Y0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:V0(YV),execute:async(f)=>k(E7.array(),$.runtime.listRuns(k(YV,f)).map(b7))})),W.push(Y0({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:V0(JV),timeoutMs:y_,execute:async(f)=>{let X=k(JV,f);if(X.runId){let H=await $.runtime.awaitRun(X.runId);return r_(H),k(E7,b7(H))}let Y=await $.runtime.awaitAllRuns(),V=Y.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(V.length>0){let H=V.map((B)=>`${B.id}:${B.status}${B.error?`(${B.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return k(E7.array(),Y.map(b7))}})),W.push(Y0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:V0(GV),execute:async(f)=>{let X=k(GV,f),Y=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return k(d_,{id:Y.id,toAgentId:Y.toAgentId})}})),W.push(Y0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:V0(QV),execute:async(f)=>{let X=k(QV,f),Y=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return k(k_,{delivered:Y.length})}})),W.push(Y0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:V0(BV),execute:async(f)=>{let X=k(BV,f);return k(v_.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),W.push(Y0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:V0(VV),execute:async(f)=>{let X=k(VV,f),Y=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return k(c_,{id:Y.id})}})),W.push(Y0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:V0(WV),execute:async(f)=>{if(k(WV,f),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),k(x_,{status:"cleaned"})}})),W.push(Y0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:V0(jV),execute:async(f)=>{let X=k(jV,f),Y=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return k(g_,{outcomeId:Y.id,status:Y.status,requiredSections:Y.requiredSections})}})),W.push(Y0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:V0($V),execute:async(f)=>{let X=k($V,f),Y=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return k(HV,{fragmentId:Y.id,status:Y.status})}})),W.push(Y0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:V0(AV),execute:async(f)=>{let X=k(AV,f),Y=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return k(HV,{fragmentId:Y.id,status:Y.status})}})),W.push(Y0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:V0(fV),execute:async(f)=>{let X=k(fV,f),Y=$.runtime.finalizeOutcome(X.outcomeId);return k(m_,{outcomeId:Y.id,status:Y.status})}})),W.push(Y0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:V0(XV),execute:async(f)=>{return k(XV,f),k(u_.array(),$.runtime.listOutcomes())}})),W}function l5($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}function OV($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var i_=[{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:D$({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]}],n_={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function a_($){return $==="plan"||$==="yolo"?$:"act"}function MV($){let J=a_($.mode),Q=c0[u1({mode:J})],Z=H8($.providerId??"",$.modelId??"",J,V8);return{mode:J,flags:{...Q,...Z,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function TV($,J){if(J.disabledToolIds?.has($))return!1;let{flags:Q}=MV(J);if($==="spawn_agent")return Q.enableSpawnAgent===!0;if($==="teams")return Q.enableAgentTeams===!0;if($==="editor")return Q.enableEditor===!0||Q.enableApplyPatch===!0;let Z=n_[$];return Z?Q[Z]===!0:!1}function s_($,J){if($.id==="editor"){let{flags:Q}=MV(J),Z=Q.enableApplyPatch===!0&&Q.enableEditor!==!0;return{...$,defaultEnabled:TV($.id,J),headlessToolNames:[Z?"apply_patch":"editor"]}}return{...$,defaultEnabled:TV($.id,J)}}function J2($={}){return i_.map((J)=>s_(J,$))}function p5($={}){return J2($).filter((J)=>J.defaultEnabled).map((J)=>J.id)}function r5($){if(!$.enabled)return new Set;let J=J2($.availabilityContext),Q=new Set(J.map((Z)=>Z.id));if(!$.allowlist||$.allowlist.length===0)return new Set(J.filter((Z)=>Z.defaultEnabled).map((Z)=>Z.id));for(let Z of $.allowlist)if(!Q.has(Z))throw Error(`Unknown tool "${Z}". Available tools: ${J.map((W)=>W.id).join(", ")}`);return new Set($.allowlist)}function H6($,J={}){return J2(J).filter((Q)=>$.has(Q.id)).flatMap((Q)=>Q.headlessToolNames)}function i5($,J={}){return H6($,J)}function Q2($={}){let{executorOptions:J={},executors:Q,...Z}=$,W={...Y8(J),...Q??{}};return B$({...Z,executors:W})}import{mkdirSync as QO,writeFileSync as ZO}from"node:fs";import{dirname as WO}from"node:path";import{normalizeUserInput as jO}from"@cline/shared";import{nanoid as fO}from"nanoid";var PV={};w(PV,{sanitizeSessionToken:()=>Z2,parseTeamTaskSubSessionId:()=>F8,parseSubSessionId:()=>A6,makeTeamTaskSubSessionId:()=>B6,makeSubSessionId:()=>G8,deriveSubsessionStatus:()=>K6});import{nanoid as e_}from"nanoid";function Z2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function G8($,J){let Q=Z2($),Z=Z2(J),W=`${Q}__${Z}`;return W.length>180?W.slice(0,180):W}function B6($,J){let Q=Z2($),Z=Z2(J);return`${Q}__teamtask__${Z}__${e_(6)}`}function F8($){let Q=$.indexOf("__teamtask__");if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+12),j=W.lastIndexOf("__");if(j<=0)return null;let f=W.slice(0,j),X=W.slice(j+2);if(!Z||!f||!X)return null;return{rootSessionId:Z,agentId:f,teamTaskId:X}}function A6($){if(F8($))return null;let J="__",Q=$.indexOf(J);if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+J.length);if(!Z||!W)return null;return{rootSessionId:Z,agentId:W}}function K6($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let J=String($.reason??"").toLowerCase();if(J.includes("cancel")||J.includes("abort")||J.includes("interrupt"))return"cancelled";if(J.includes("fail")||J.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as s}from"zod";var SV={};w(SV,{isTerminalSessionStatus:()=>wV,isNonTerminalSessionStatus:()=>j0,SessionSource:()=>R0,SESSION_STATUSES:()=>G6,NON_TERMINAL_SESSION_STATUSES:()=>NV});import{SESSION_STATUS_VALUES as $O}from"@cline/shared";var G6=$O,NV=["idle","running","pending"];function wV($){return!NV.includes($)}function j0($){return!wV($)}var R0={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 JO=s.enum(G6),y0=s.object({version:s.literal(1),session_id:s.string().min(1),source:s.string().min(1),pid:s.number().int(),started_at:s.string().min(1),ended_at:s.string().min(1).optional(),exit_code:s.number().int().nullable().optional(),status:JO,interactive:s.boolean(),provider:s.string().min(1),model:s.string().min(1),cwd:s.string().min(1),workspace_root:s.string().min(1),team_name:s.string().min(1).optional(),enable_tools:s.boolean(),enable_spawn:s.boolean(),enable_teams:s.boolean(),prompt:s.string().optional(),metadata:s.record(s.string(),s.unknown()).optional(),messages_path:s.string().min(1).optional()});function CV($){if(!$)return!1;return Object.values($).some((J)=>typeof J==="function")}function k7($,J){let Q=[...$??[],...J??[]];if(Q.length===0)return;let Z=[],W=new Set;for(let j of Q){if(W.has(j.name))continue;W.add(j.name),Z.push(j)}return Z}function yV($){return JSON.stringify($,(J,Q)=>{if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};return Q})}function d1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function h7($,J){let Q={...$};Q.id=d1(Q.id)??fO();let Z=Q.modelInfo&&typeof Q.modelInfo==="object"?{...Q.modelInfo}:void 0,W={id:d1(Z?.id)??d1(Q.modelId)??d1(J?.id),provider:d1(Z?.provider)??d1(Q.providerId)??d1(J?.provider),family:d1(Z?.family)??d1(J?.family)};if(delete Q.providerId,delete Q.modelId,W.id&&W.provider)Q.modelInfo={id:W.id,provider:W.provider,...W.family?{family:W.family}:{}};else delete Q.modelInfo;return Q}function n5($){return $.map((J)=>h7(J))}function a5($,J,Q=[]){let Z=$.map((Y,V)=>{let H=Q[V],A=H?.role===Y.role&&JSON.stringify(H.content)===JSON.stringify(Y.content)?{...H,...Y}:{...Y};return h7(A)}),W=Q.length,j=[];for(let Y=W;Y<Z.length;Y+=1)if(Z[Y]?.role==="assistant")j.push(Y);if(j.length===0){let Y=[...Z].reverse().findIndex((V)=>V.role==="assistant");if(Y===-1)return Z;j.push(Z.length-1-Y)}let f=j[j.length-1],X=j.some((Y)=>Z[Y]?.metrics);for(let Y of j){let V=Z[Y],H=V.metrics;if(!H&&Y===f&&!X){let B=J.usage;H={inputTokens:B.inputTokens,outputTokens:B.outputTokens,cacheReadTokens:B.cacheReadTokens??0,cacheWriteTokens:B.cacheWriteTokens??0,cost:B.totalCost}}Z[Y]={...h7(V,{id:J.model.id,provider:J.model.provider,family:J.model.info?.family}),...H?{metrics:H}:{},ts:V.ts??J.endedAt.getTime()}}return Z}function F6($){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 XO=120;function W2($){let J=$?.trim();return J?J.slice(0,XO):void 0}function I7($){let J=jO($??"").trim();if(!J)return;return W2(J.split(`
460
+ `)[0]?.trim())}function U$($){if(!$)return;let J={...$},Q=W2(typeof J.title==="string"?J.title:void 0);if(Q)J.title=Q;else delete J.title;return Object.keys(J).length>0?J:void 0}function D6($){let J=U$($.metadata)??{},Q=$.title!==void 0?W2($.title):I7($.prompt);if(Q)J.title=Q;return Object.keys(J).length>0?J:void 0}function x7($){let J=F8($);if(J)return{agent:"teammate",sessionId:J.rootSessionId,taskType:"team"};let Q=A6($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function g7($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:n5($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function EV($,J,Q){QO(WO($),{recursive:!0}),ZO($,`${JSON.stringify(g7({updatedAt:J,context:Q,messages:[]}),null,2)}
461
+ `,"utf8")}function bV($,J){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:J?.endedAt??$.endedAt??void 0,exit_code:J?.exitCode??$.exitCode??void 0,status:J?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:J?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function hV($,J,Q){let Z=0;while(!0){let W=await $();if(W===void 0)return{updated:!1};let j=await J(W);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Z+=1,Z>=Q)return j;continue}return j}}O0();var kV={};w(kV,{summarizeUsageFromMessages:()=>U8,sumUsageTotals:()=>U6,getCurrentContextSize:()=>m7,createInitialAccumulatedUsage:()=>G0,accumulateUsageTotals:()=>H0});function G0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0($,J){return{inputTokens:$.inputTokens+Math.max(0,J.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,J.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,J.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,J.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,J.totalCost??0)}}function U6($){let J=G0();for(let Q of $)J=H0(J,Q);return J}function D8($){return typeof $==="number"&&Number.isFinite($)?$:0}function U8($){let J=G0();for(let Q of $){let Z=Q.metrics;if(!Z)continue;J=H0(J,{inputTokens:D8(Z.inputTokens),outputTokens:D8(Z.outputTokens),cacheReadTokens:D8(Z.cacheReadTokens),cacheWriteTokens:D8(Z.cacheWriteTokens),totalCost:D8(Z.cost)})}return J}function m7($){for(let J=$.length-1;J>=0;J-=1){let Q=$[J];if(Q?.role!=="assistant")continue;let Z=D8(Q.metrics?.inputTokens);return Z>0?Z:void 0}return}function YO($){if(!$||typeof $!=="object")return;let J=$,Q=J.skill??J.skill_name??J.skillName;if(typeof Q!=="string")return;let Z=Q.trim();return Z.length>0?Z:void 0}function v7($){if(!$||typeof $!=="object")return{};let J=$;return{agentId:typeof J.agentId==="string"?J.agentId:void 0,conversationId:typeof J.conversationId==="string"?J.conversationId:void 0,parentAgentId:typeof J.parentAgentId==="string"?J.parentAgentId:void 0}}function l1($){let J=$.agentId?.trim();if(!J)return;let Q=$.parentAgentId?.trim()||void 0,Z=$.teamRole,W="root";if(Z==="teammate")W="team_teammate";else if(Z==="lead")W="team_lead";else if(Q)W="subagent";return{agentId:J,agentKind:W,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Q,createdByAgentId:$.createdByAgentId?.trim()||Q||void 0,isSubagent:Boolean(Q),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Z,teamAgentId:$.teamAgentId?.trim()||void 0}}function VO($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function HO($){let J=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Q of J){let Z=Q?.trim();if(Z)return Z}return $.isPrimaryAgentEvent?"root":"unknown"}function c7($,J,Q){let{sessionId:Z,config:W,liveSession:j,emit:f}=$,X=W.telemetry,Y=j?.runtime.teamRuntime,V=Q?.isPrimaryAgentEvent??!0,H=v7(J),B=l1({agentId:Q?.agentId??H.agentId,conversationId:Q?.conversationId??H.conversationId,parentAgentId:Q?.parentAgentId??H.parentAgentId,createdByAgentId:Q?.createdByAgentId,teamId:Q?.teamId??Y?.getTeamId(),teamName:Q?.teamName??Y?.getTeamName(),teamRole:Q?.teamRole,teamAgentId:Q?.teamAgentId});if(J.type==="content_start"&&J.contentType==="tool"&&J.toolName==="skills"){let A=YO(J.input);if(A)pJ(X,{ulid:Z,skillName:A,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:W.providerId,modelId:W.modelId,...B})}if(J.type==="content_end"&&J.contentType==="tool"){let A=J.toolName??"unknown",K=!J.error;if(lJ(X,{ulid:Z,tool:A,autoApproved:void 0,success:K,modelId:W.modelId,provider:W.providerId,...B}),!K&&(A==="editor"||A==="apply_patch"))rJ(X,{ulid:Z,modelId:W.modelId,provider:W.providerId,errorType:J.error,...B})}if(J.type==="notice"&&J.reason==="api_error")U4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.message,...B});if(J.type==="error")U4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.error?.message??"unknown error",...B});if(J.type==="usage"&&j?.turnUsageBaseline){let A=VO(J);if(V){j.turnPrimaryUsage=H0(j.turnPrimaryUsage??G0(),A);let G=H0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Z,G),u2(X,{ulid:Z,provider:W.providerId,model:W.modelId,source:"assistant",mode:W.mode,...B}),uJ(X,{ulid:Z,tokensIn:J.inputTokens,tokensOut:J.outputTokens,cacheWriteTokens:J.cacheWriteTokens,cacheReadTokens:J.cacheReadTokens,totalCost:J.cost,model:W.modelId,...B})}else{let G=HO({isPrimaryAgentEvent:V,overrides:Q,eventMetadata:H}),R=j.turnUsageByAgent??new Map;j.turnUsageByAgent=R,R.set(G,H0(R.get(G)??G0(),A))}let K=H0(j.turnPrimaryUsage??G0(),U6(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Z,H0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,K))}if(J.type==="iteration_end"&&V)$.persistMessages(Z,j?.agent.getMessages()??[],j?.config.systemPrompt);f({type:"agent_event",payload:{sessionId:Z,event:J,teamAgentId:Q?.teamAgentId,teamRole:Q!==void 0?Q.teamRole??(V?"lead":void 0):void 0}}),f({type:"chunk",payload:{sessionId:Z,stream:"agent",chunk:yV(J),ts:Date.now()}})}function R$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as DM}from"@cline/shared";t0();import{existsSync as JQ,readFileSync as oO,statSync as tO}from"node:fs";import{basename as eO,dirname as e5,join as QQ,resolve as $Q}from"node:path";import{discoverPluginModulePaths as $T,resolveConfiguredPluginModulePaths as QH,resolvePluginConfigSearchPaths as JT,SKILLS_CONFIG_DIRECTORY_NAME as QT}from"@cline/shared/storage";import{resolve as CO}from"node:path";import{normalizePluginManifest as yO}from"@cline/shared";import{existsSync as z0,readFileSync as z8}from"node:fs";import{builtinModules as BO,createRequire as p7}from"node:module";import{dirname as z$,extname as z6,isAbsolute as AO,resolve as p}from"node:path";import{fileURLToPath as xV}from"node:url";import{PLUGIN_FILE_EXTENSIONS as KO}from"@cline/shared";var gV=z$(xV(import.meta.url)),GO=p7(import.meta.url),FO=p(gV,"..","..","..","..",".."),u7=RO(FO),DO=["@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"],r7=new Set(BO.flatMap(($)=>[$,$.replace(/^node:/,"")])),R6=new Set(KO),UO=["development","node","import","require","default"];function RO($){let J={},Q={"@cline/sdk":p($,"packages/sdk/src/index.ts"),"@cline/agents":p($,"packages/agents/src/index.ts"),"@cline/core":p($,"packages/core/src/index.ts"),"@cline/llms":p($,"packages/llms/src/index.ts"),"@cline/shared":p($,"packages/shared/src/index.ts"),"@cline/shared/storage":p($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":p($,"packages/shared/src/db/index.ts")};for(let[Z,W]of Object.entries(Q))if(z0(W))J[Z]=W;for(let Z of["agents","core","llms","shared"]){let W=p($,"packages",Z),j=p(W,"package.json");if(!z0(j))continue;try{let f=JSON.parse(z8(j,"utf8"));if(typeof f.name!=="string"||!f.exports)continue;if(typeof f.exports==="string"){let X=p(W,f.exports);if(z0(X))J[f.name]=X;continue}if(typeof f.exports!=="object")continue;for(let[X,Y]of Object.entries(f.exports)){let V=zO(W,Y);if(!V)continue;let H=X==="."?f.name:`${f.name}/${X.replace(/^\.\//,"")}`;J[H]=V}}catch{}}return J}function zO($,J){let Q=i7(J);if(!Q)return null;let Z=mV($,Q);for(let W of Z)if(z0(W))return W;return null}function i7($,J=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(J.has($))return null;J.add($);let Q=$;for(let Z of UO){let W=i7(Q[Z],J);if(W)return W}return null}function mV($,J){let Q=J.replace(/^\.\//,""),Z=[p($,J)];if(Q.startsWith("dist/")){let W=Q.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[p($,`${W}.ts`),p($,`${W}.tsx`),p($,`${W}.mts`),p($,`${W}.cts`),...Z]}return Z}function LO($){return Object.fromEntries(Object.entries($).sort(([J],[Q])=>Q.length-J.length))}function s5($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function R8($){if($.startsWith("@")){let[J,Q]=$.split("/",3);return Q?`${J}/${Q}`:$}return $.split("/",1)[0]??$}function _O($){let J=R8($);if($===J)return".";return`.${$.slice(J.length)}`}function vV($){return R8($).startsWith("@cline/")}function d7($,J){let Q=R8(J),Z=z$($);while(!0){let W=p(Z,"node_modules",Q);if(z0(W)||z0(p(W,"package.json")))return!0;let j=p(Z,"..");if(j===Z)return!1;Z=j}}function IV($){return l7($)!==null}function l7($){try{return GO.resolve($)}catch{}return OO($)}function OO($){let J=R8($),Q=cV(J);if(!Q)return null;let Z=p(Q,"package.json");try{let W=JSON.parse(z8(Z,"utf8")),j=_O($),f=j==="."&&typeof W.exports==="string"?W.exports:W.exports&&typeof W.exports==="object"&&Object.hasOwn(W.exports,j)?W.exports[j]:void 0,X=i7(f)??(j==="."&&typeof W.main==="string"?W.main:null);if(!X)return null;let Y=p(Q,X),V=[Y,...mV(Q,X).filter((H)=>H!==Y)];for(let H of V)if(z0(H))return H;return null}catch{return null}}function TO(){let $=[gV],J=process.env.CLINE_WRAPPER_PATH?.trim();if(J)$.push(z$(z$(J)));let Q=process.execPath?.trim();if(Q)$.push(z$(Q));return[...new Set($.map((Z)=>p(Z)))]}function MO($,J){let Q=$;while(!0){let Z=p(Q,"package.json");if(z0(Z))try{if(JSON.parse(z8(Z,"utf8")).name===J)return Q}catch{}let W=p(Q,"node_modules",J,"package.json");if(z0(W))return z$(W);let j=p(Q,"..");if(j===Q)return null;Q=j}}function cV($){for(let J of TO()){let Q=MO(J,$);if(Q)return Q}return null}function qO($){let Q=z$($);for(let Z=0;Z<4;Z++){let W=p(Q,"package.json");if(z0(W))try{let f=JSON.parse(z8(W,"utf8"));return f!=null&&typeof f==="object"&&"cline"in f}catch{return!1}let j=p(Q,"..");if(j===Q)return!1;Q=j}return!1}function uV($,J){let Q=J.startsWith("file:")?xV(J):AO(J)?J:p(z$($),J);if(z0(Q)&&R6.has(z6(Q)))return Q;for(let Z of R6){let W=`${Q}${Z}`;if(z0(W))return W}for(let Z of R6){let W=p(Q,`index${Z}`);if(z0(W))return W}return null}function dV($){let J=new Set,Q=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Z of Q)for(let W of $.matchAll(Z)){let j=W[1];if(j)J.add(j)}return[...J]}function PO($){return z6($)!==".ts"}function lV($,J,Q=new Set){if(Q.has($)||!z0($))return;if(Q.add($),!R6.has(z6($)))return;let Z=z8($,"utf8"),W=PO($);for(let j of dV(Z)){if(j.startsWith("node:")||r7.has(j))continue;if(s5(j)){if(!W)continue;if(Object.hasOwn(u7,j)||Object.hasOwn(u7,R8(j))||d7($,j)||vV(j)&&IV(j)||J&&IV(j))continue;throw Error(`Cannot find module '${R8(j)}'`)}let f=uV($,j);if(f)lV(f,J,Q)}}function pV($,J=new Set,Q=new Set){if(J.has($)||!z0($))return Q;if(J.add($),!R6.has(z6($)))return Q;let Z=z8($,"utf8");for(let W of dV(Z)){if(Q.add(W),s5(W))continue;let j=uV($,W);if(j)pV(j,J,Q)}return Q}function NO($,J){let Q=p7($),Z={},W=pV($),j=new Set(DO);for(let[f,X]of Object.entries(u7)){try{Q.resolve(f);continue}catch{}Z[f]=X}for(let f of W)if(s5(f)&&(vV(f)||J))j.add(f);for(let f of j){if(Object.hasOwn(Z,f)||d7($,f))continue;let X=l7(f);if(X)Z[f]=X}if(!J)return Z;for(let f of W){if(!s5(f)||Object.hasOwn(Z,f)||d7($,f)||f.startsWith("node:")||r7.has(f))continue;let X=l7(f);if(X)Z[f]=X}return Z}function wO($){let J=z6($);return J===".ts"||J===".tsx"||J===".mts"||J===".cts"}var j2;function SO(){if(j2!==void 0)return j2;let $=cV("jiti");if(!$)return j2=null,null;let J=p($,"dist","babel.cjs");if(!z0(J))return j2=null,null;try{let Z=p7(J)(J);j2=typeof Z==="function"?Z:null}catch{j2=null}return j2}async function rV($,J={}){let Q=!qO($);lV($,Q);let Z=NO($,Q),W=LO(Z),j=await import("jiti"),f=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!f)throw Error("Unable to load jiti");let X=Object.entries(W).filter(([,B])=>wO(B)).map(([B])=>B),Y=SO(),V=Y?(B)=>Y({...B,interopDefault:!0}):void 0;return await f($,{alias:W,cache:J.useCache,requireCache:J.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...r7],transformModules:X,tryNative:!1,...V?{transform:V}:{}}).import($,{})}function iV($,J){if(!$)return!0;if($.providerIds?.length){if(!J?.providerId||!$.providerIds.includes(J.providerId))return!1}if($.modelIds?.length){if(!J?.modelId||!$.modelIds.includes(J.modelId))return!1}return!0}function nV($){return typeof $==="object"&&$!==null}function n7($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function EO($,J){if(!nV($.manifest))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);if(!n7($.manifest.capabilities))throw Error(`Invalid plugin module at ${J}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${J}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!n7($.manifest.providerIds))throw Error(`Invalid plugin module at ${J}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!n7($.manifest.modelIds))throw Error(`Invalid plugin module at ${J}: manifest.modelIds must be a string array when provided`)}function bO($,J){if(!nV($))throw Error(`Invalid plugin module at ${J}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${J}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);EO($,J)}async function L6($,J={}){let Q=CO(J.cwd??process.cwd(),$),Z=await rV(Q,{useCache:J.useCache}),W=J.exportName??"plugin",j=Z.default??Z[W];bO(j,Q);let f=j,X=f.setup,Y=X?(V,H)=>{let B={...J.session,...H.session},A={...H,session:Object.keys(B).length>0?B:void 0,client:J.client??H.client,user:J.user??H.user,workspaceInfo:J.workspaceInfo??H.workspaceInfo,automation:J.automation??H.automation,logger:J.logger??H.logger,telemetry:J.telemetry??H.telemetry};return X(V,A)}:void 0;return{...f,manifest:yO(f.manifest),setup:Y}}async function o5($,J={}){return(await f2($,J)).plugins}async function f2($,J={}){let Q=[],Z=[],W=new Map,j=0;for(let X of $)try{let Y=await L6(X,J);if(!iV(Y.manifest,J))continue;let V=W.get(Y.name);if(V)Z.push({type:"duplicate_plugin_override",pluginName:Y.name,pluginPath:X,overriddenPluginPath:V.pluginPath,message:`Plugin "${Y.name}" from ${X} overrides ${V.pluginPath}`});W.set(Y.name,{plugin:Y,pluginPath:X,order:j++})}catch(Y){let V=Y instanceof Error?Y.message:String(Y);Q.push({pluginPath:X,phase:"load",message:V,stack:Y instanceof Error?Y.stack:void 0})}let f=[...W.values()].sort((X,Y)=>X.order-Y.order);return{plugins:f.map((X)=>X.plugin),pluginPaths:f.map((X)=>X.pluginPath),failures:Q,warnings:Z}}import{existsSync as t7}from"node:fs";import{createRequire as JH}from"node:module";import{dirname as t5,join as _8}from"node:path";import{fileURLToPath as gO}from"node:url";var eV={};w(eV,{resolveSubprocessRuntimeExecutable:()=>a7,buildSubprocessSandboxCommand:()=>tV,SubprocessSandbox:()=>L8,CLINE_JS_RUNTIME_PATH_ENV:()=>oV});import{spawn as hO}from"node:child_process";import{basename as kO}from"node:path";import{augmentNodeCommandForDebug as IO,withResolvedClineBuildEnv as xO}from"@cline/shared";function aV($){if($ instanceof Error)return $;return Error(String($))}var oV="CLINE_JS_RUNTIME_PATH";function sV($){let J=$?.trim();if(!J)return!1;let Q=kO(J).toLowerCase();return Q==="node"||Q==="node.exe"||Q==="bun"||Q==="bun.exe"}function a7($={}){let J=$.env??process.env,Q=$.runtimeExecutable?.trim()||J[oV]?.trim();if(Q)return Q;let Z=$.execPath?.trim()||process.execPath;if(sV(Z))return Z;for(let W of[J.BUN_EXEC_PATH,J.npm_node_execpath,J.NODE]){let j=W?.trim();if(j&&sV(j))return j}return"node"}function tV($,J={}){let Q=a7({env:J.env,execPath:J.execPath,runtimeExecutable:J.runtimeExecutable});return IO([Q,...$],{env:J.env,execArgv:J.execArgv,debugRole:J.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class L8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let J=this.pending.get($);if(!J)return;if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);return J}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],J=tV($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Q=hO(J[0]??a7(this.options),J.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:xO(process.env),windowsHide:!0});this.process=Q;let Z="",W=(j)=>{let f=Z+j;Z=f.length>4000?f.slice(-4000):f};Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(j)=>{W(j)}),Q.on("message",(j)=>{this.onMessage(j)}),Q.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${aV(j).message}`))}),Q.on("exit",(j,f)=>{this.process=null;let X=Z.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(f)})${X?`: ${X}`:""}`))})}async call($,J,Q={}){this.start();let Z=this.process;if(!Z||Z.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let W=`req_${++this.requestCounter}`,j={type:"call",id:W,method:$,args:J};return await new Promise((f,X)=>{let Y={resolve:(V)=>f(V),reject:X};if((Q.timeoutMs??0)>0)Y.timeout=setTimeout(()=>{this.clearPendingRequest(W),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${Q.timeoutMs}ms: ${$}`))},Q.timeoutMs);this.pending.set(W,Y),Z.send(j,(V)=>{if(!V)return;let H=this.clearPendingRequest(W);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${aV(V).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((J)=>{let Q=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}J()},300);$.once("exit",()=>{clearTimeout(Q),J()});try{$.kill("SIGTERM")}catch{clearTimeout(Q),J()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let J=this.clearPendingRequest($.id);if(!J)return;if($.ok){J.resolve($.result);return}J.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[J,Q]of this.pending.entries()){if(this.pending.delete(J),Q.timeout)clearTimeout(Q.timeout);Q.reject($)}}}function mO($){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 _6($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function vO(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function cO(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Q=JH($).resolve(`${vO()}/package.json`),Z=_8(t5(Q),"extensions","plugin-sandbox-bootstrap.js");return t7(Z)?Z:void 0}catch{return}}function uO(){let $=process.execPath?.trim();if(!$)return;let J=_8(t5(t5($)),"extensions","plugin-sandbox-bootstrap.js");return t7(J)?J:void 0}function dO(){let $=t5(gO(import.meta.url)),J=JH(import.meta.url),Q=[_8($,"plugin-sandbox-bootstrap.js"),_8($,"extensions","plugin-sandbox-bootstrap.js"),_8($,"agents","plugin-sandbox-bootstrap.js"),cO(),uO()];for(let j of Q.filter((f)=>typeof f==="string"))if(t7(j))return{file:j};let Z=_8($,"plugin-sandbox-bootstrap.ts"),W="jiti";try{W=J.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(W)});`,`const jiti = createJiti(${JSON.stringify(Z)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Z)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
462
+ `)}}var s7=dO();function o7($,J,Q){if(typeof $==="number"&&$>0)return $;if(Q){let Z=process.env[Q];if(Z){let W=Number(Z);if(Number.isInteger(W)&&W>0)return W}}return J}async function O8($){let J=new L8({name:"plugin-sandbox",..."file"in s7?{bootstrapFile:s7.file}:{bootstrapScript:s7.script},onEvent:$.onEvent}),Q=o7($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Z=o7($.hookTimeoutMs,3000),W=o7($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},f,X=()=>{return f??=J.call("initialize",j,{timeoutMs:Q}).finally(()=>{f=void 0}),f},Y;try{Y=await J.call("initialize",j,{timeoutMs:Q})}catch(B){throw await J.shutdown().catch(()=>{}),B}let V=Y.plugins.map(mO);return{extensions:V.map((B)=>{let A={name:B.name,__clinePluginPath:B.pluginPath,manifest:B.manifest,setup:(K)=>{lO(K,J,B,W,X),pO(K,J,B,W,X),rO(K,J,B,W,X),nO(K,J,B,W,X),iO(K,B)}};return A.hooks=sO(J,B,Z,X),A}),failures:Y.failures,pluginPaths:V.map((B)=>B.pluginPath),shutdown:async()=>{await J.shutdown()},warnings:Y.warnings}}function lO($,J,Q,Z,W){for(let j of Q.contributions?.tools??[]){let f={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(X,Y)=>{try{return await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}catch(V){if(!_6(V))throw V;return await W(),await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}}};$.registerTool(f)}}function pO($,J,Q,Z,W){for(let j of Q.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(f)=>{try{return await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}catch(X){if(!_6(X))throw X;return await W(),await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}}})}function rO($,J,Q,Z,W){for(let j of Q.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}catch(f){if(!_6(f))throw f;return await W(),await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}}:j.content??""})}function iO($,J){for(let Q of J.contributions?.providers??[])$.registerProvider({name:Q.name,description:Q.description,metadata:Q.metadata});for(let Q of J.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Q.eventType,source:Q.source,description:Q.description,attributesSchema:Q.attributesSchema,payloadSchema:Q.payloadSchema,examples:Q.examples,metadata:Q.metadata});for(let Q of J.contributions?.mcpServers??[])$.registerMcpServer(Q)}function nO($,J,Q,Z,W){for(let j of Q.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(f){try{let X=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return $H(X)?X:f}catch(X){if(!_6(X))throw X;await W();let Y=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return $H(Y)?Y:f}}})}function $H($){return Array.isArray($)&&$.every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&("content"in J))}function aO($,J,Q,Z,W){return async(j)=>{try{return await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}catch(f){if(!_6(f))throw f;return await W(),await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}}}function sO($,J,Q,Z){let W={};for(let j of J.hooks??[])W[j]=aO($,J.pluginId,j,Q,Z);return Object.keys(W).length>0?W:void 0}var $W="package.json",ZT="package";function O6($){return JT($)}function T6($){return $T($)}function WT($){try{return JQ($)&&tO($).isDirectory()}catch{return!1}}function JW($){let J=[],Q=new Set;for(let Z of $){let W=$Q(Z);if(Q.has(W))continue;Q.add(W),J.push(W)}return J}function ZH($){let J=JW($);return W5(J)}function WH($){return O6($).flatMap((J)=>T6(J)).filter((J)=>JQ(J))}function jT($,J){let Q=[];for(let Z of $)try{Q.push(...QH([Z],J))}catch{}return Q}function e7($){return typeof $==="object"&&$!==null}function fT($){try{let J=JSON.parse(oO(QQ($,$W),"utf8"));if(!e7(J)||!e7(J.cline))return[];let Q=J.cline.plugins;if(!Array.isArray(Q))return[];let Z=[];for(let W of Q){if(typeof W==="string"){Z.push(W);continue}if(!e7(W)||!Array.isArray(W.paths))continue;for(let j of W.paths)if(typeof j==="string")Z.push(j)}return Z}catch{return[]}}function jH($,J){let Q=$Q(J);return fT($).some((Z)=>$Q($,Z)===Q)}function XT($,J){return eO($)===ZT&&JQ(QQ(e5($),$W))&&jH(e5($),J)}function YT($){let J=$Q($),Q=[],Z=e5(J);while(!0){if(XT(Z,J)){Q.push(Z);break}if(JQ(QQ(Z,$W))){if(jH(Z,J))Q.push(Z);break}let W=e5(Z);if(W===Z)break;Z=W}return JW(Q)}function X2($={}){let J=$.cwd??process.cwd(),Q=WH($.workspacePath),Z=QH($.pluginPaths??[],J);return ZH([...Z,...Q])}function VT($={}){let J=$.cwd??process.cwd(),Q=WH($.workspacePath),Z=jT($.pluginPaths??[],J);return ZH([...Z,...Q])}function Y2($){let J=[];for(let Q of $)for(let Z of YT(Q)){let W=QQ(Z,QT);if(WT(W))J.push(W)}return JW(J)}function fH($={}){return Y2(VT($))}async function T8($={}){let J=X2($);if(J.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Z=await f2(J,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Z.plugins,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}let Q=await O8({pluginPaths:J,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Q.extensions??[],shutdown:Q.shutdown,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}import{execFile as HT}from"node:child_process";import{promisify as BT}from"node:util";var AT=BT(HT);function QW($,J){$?.log(J,{severity:"warn"})}function KT($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))return;let Q=J;if(!Q.latest||!Array.isArray(Q.history))return;let Z=Q.latest,W=Q.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")return;return{latest:Z,history:W}}async function V2($,J){let Q=await AT("git",["-C",$,...J],{windowsHide:!0});return{stdout:Q.stdout.trim(),stderr:Q.stderr.trim()}}async function ZW($,J){if(!$)return;let Q=`refs/cline/checkpoints/${J}/`;try{let{stdout:Z}=await V2($,["for-each-ref","--format=%(refname)",Q]),W=Z.trim().split(`
463
+ `).filter(Boolean);await Promise.allSettled(W.map((j)=>V2($,["update-ref","-d",j])))}catch{}}async function XH($,J,Q){if(!$||Q.length===0)return;await Promise.allSettled(Q.map((Z)=>V2($,["update-ref",`refs/cline/checkpoints/${J}/${Z.runCount}`,Z.ref])))}function GT($,J){let Q=$.findIndex((Z)=>Z.runCount===J.runCount);if(Q<0)return[...$,J];return $.map((Z,W)=>W===Q?J:Z)}function YH($){let J=$.initialRunCount??0,Q,Z=async()=>{if(Q!==void 0)return Q;try{Q=(await V2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Q=!1}return Q},W=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:J});if(!await Z())return;let j=async(V)=>{try{let B=(await V2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:J,kind:"commit"}}catch(H){QW($.logger,`${V}: ${H instanceof Error?H.message:String(H)}`);return}},f=`cline checkpoint session=${$.sessionId} run=${J}`,X="";try{X=(await V2($.cwd,["stash","create",f])).stdout.trim()}catch(V){return QW($.logger,`Checkpoint snapshot failed: ${V instanceof Error?V.message:String(V)}`),j("Checkpoint HEAD fallback failed")}if(!X)return j("Checkpoint HEAD fallback failed");let Y=`refs/cline/checkpoints/${$.sessionId}/${J}`;try{await V2($.cwd,["update-ref",Y,X])}catch(V){QW($.logger,`Checkpoint store failed: ${V instanceof Error?V.message:String(V)}`);return}return{ref:X,createdAt:Date.now(),runCount:J,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;J+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||J<1)return;let f=await W();if(!f)return;let X=await $.readSessionMetadata(),Y=KT(X);if(Y?.latest.ref===f.ref)return;let V=GT(Y?.history??[],f);await $.writeSessionMetadata({...X??{},checkpoint:{latest:f,history:V}});return}}}import{spawn as TT}from"node:child_process";import{appendFileSync as MT,readFileSync as qT}from"node:fs";import{join as PT}from"node:path";import{augmentNodeCommandForDebug as BH,withResolvedClineBuildEnv as fW}from"@cline/shared";import{ensureHookLogDir as VH}from"@cline/shared/storage";function M8($,J){if(!J)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:J}}import{existsSync as FT,readdirSync as DT}from"node:fs";import{basename as UT,extname as RT,join as zT}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as ZQ,resolveHooksConfigSearchPaths as LT}from"@cline/shared/storage";function M6($){return LT($)}var q8;((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"})(q8||={});var q6={["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"},_T=new Map(Object.values(q8).map(($)=>[$.toLowerCase(),$])),OT=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function P6($){let J=RT($).toLowerCase();if(!OT.has(J))return;let Q=UT($,J).trim().toLowerCase();return _T.get(Q)}function L$($){let J=[],Q=new Set,Z=M6($).filter((W)=>FT(W));for(let W of Z)try{for(let j of DT(W,{withFileTypes:!0})){if(!j.isFile())continue;let f=P6(j.name);if(!f)continue;let X=zT(W,j.name);if(Q.has(X))continue;Q.add(X),J.push({fileName:f,hookEventName:q6[f],path:X})}}catch{}return J.sort((W,j)=>W.path.localeCompare(j.path))}function jQ($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))J[Q]=typeof Z==="string"?Z:JSON.stringify(Z);return J}function WQ($,J,Q){let Z=Q instanceof Error?`: ${Q.message}`:"",W=`${J}${Z}`;if($){try{$.log(W,{severity:"warn",...Q!==void 0?{error:Q}:{}})}catch{}return}console.warn(W)}function NT($,J){if(!J)return $;if(!$)return{...J};let Q=[$.context,J.context].filter((W)=>typeof W==="string"&&W.length>0).join(`
464
+ `),Z=[...$.appendMessages??[],...J.appendMessages??[]];return{cancel:$.cancel===!0||J.cancel===!0?!0:void 0,review:$.review===!0||J.review===!0?!0:void 0,context:Q||void 0,overrideInput:J.overrideInput!==void 0?J.overrideInput:$.overrideInput,systemPrompt:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,appendMessages:Z.length>0?Z:void 0}}function wT($){if(!$||typeof $!=="object")return;let J=$,Q=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Q,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function WW($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function L0($,J){let Q=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Z={rootSessionId:J.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Z,workspaceRoots:J.workspacePath?[J.workspacePath]:[],workspaceInfo:J.workspaceInfo,userId:Q,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function ST($){let J=$.trim();if(!J)return{};let Z=J.split(`
465
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function CT($,J){let Q=$.stdin;if(!Q)throw Error("hook command failed to create stdin");await new Promise((Z,W)=>{let j=!1,f=()=>{Q.off("error",Y),Q.off("finish",V),$.off("close",H)},X=(B)=>{if(j)return;if(j=!0,f(),B){let A=B.code;if(A==="EPIPE"||A==="ERR_STREAM_DESTROYED"){Z();return}W(B);return}Z()},Y=(B)=>X(B),V=()=>X(),H=()=>X();Q.on("error",Y),Q.once("finish",V),$.once("close",H);try{Q.end(J)}catch(B){X(B)}})}async function AH($,J){if(J.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await HH($,J)}catch(Q){let Z=bT(J.command,process.platform,Q);if(!Z)throw Q;return await HH($,{...J,command:Z})}}async function HH($,J){let Q=BH(J.command,{env:J.env,debugRole:"hook"}),Z=TT(Q[0],Q.slice(1),{cwd:J.cwd,env:fW(J.env),stdio:J.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:J.detached,windowsHide:!0}),W=new Promise((A)=>{Z.once("spawn",()=>A())}),j=new Promise((A,K)=>{Z.once("error",(G)=>K(G))}),f=JSON.stringify($);if(await Promise.race([W,j]),await CT(Z,f),J.detached){Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("hook command failed to create stdout/stderr");let X="",Y="",V=!1,H;Z.stdout.on("data",(A)=>{X+=A.toString()}),Z.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,Z.kill("SIGKILL")},J.timeoutMs);Z.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=ST(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,j])}function yT($){try{let Q=qT($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Q?.startsWith("#!"))return;let Z=Q.slice(2).trim();if(!Z)return;let W=Z.split(/\s+/).filter(Boolean);return W.length>0?W:void 0}catch{return}}function ET($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function bT($,J=process.platform,Q){if(J!=="win32"||!ET(Q))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function KH($){if($.length===0)return;let[J,...Q]=$,Z=J.replace(/\\/g,"/").toLowerCase(),W=Z.split("/").at(-1)??Z;if(W==="env")return KH(Q);if(W==="bash"||W==="sh"||W==="zsh")return[W,...Q];if(W==="python3"||W==="python")return process.platform==="win32"?["py","-3",...Q]:[W,...Q];return $}function hT($){let J=yT($);if(J&&J.length>0)return[...KH(J)??J,$];let Q=$.toLowerCase();if(Q.endsWith(".sh")||Q.endsWith(".bash")||Q.endsWith(".zsh"))return["bash",$];if(Q.endsWith(".js")||Q.endsWith(".mjs")||Q.endsWith(".cjs"))return BH(["node",$],{debugRole:"hook"});if(Q.endsWith(".ts")||Q.endsWith(".mts")||Q.endsWith(".cts"))return["bun","run",$];if(Q.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Q.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function kT($){let J={};for(let Q of L$($)){if(!Q.hookEventName)continue;let Z=Q.hookEventName,W=J[Z]??[];W.push(hT(Q.path)),J[Z]=W}return J}async function IT($){let J;for(let Q of $.commands){let Z=Q.join(" ");try{let W=await AH($.payload,{command:Q,cwd:$.cwd,env:fW(process.env),detached:!1,timeoutMs:$.timeoutMs});if(W?.timedOut){WQ($.logger,`hook command timed out: ${Z}`);continue}if(W?.parseError){WQ($.logger,`hook command returned invalid JSON control output: ${Z} (${W.parseError})`);continue}J=NT(J,wT(W?.parsedJson))}catch(W){WQ($.logger,`hook command failed: ${Z}`,W)}}return J}function H2($){for(let J of $.commands){let Q=J.join(" ");AH($.payload,{command:J,cwd:$.cwd,env:fW(process.env),detached:!0}).catch((Z)=>{WQ($.logger,`hook command failed: ${Q}`,Z)})}}function _$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function jW($,J){return{..._$($.snapshot),userMessage:J}}function GH($){return{..._$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function FH($){return{..._$($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function DH($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function xT($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}function P8($){let J={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Q=(Z)=>{let W=`${JSON.stringify({ts:new Date().toISOString(),...Z})}
466
+ `,f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??PT(VH(),"hooks.jsonl");VH(f),MT(f,W,"utf8")};return{beforeRun:async(Z)=>{let W=jW(Z,"");Q({...L0(W,J),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Z)=>{let W=GH(Z);Q({...L0(W,J),hookName:"tool_call",iteration:W.iteration,tool_call:{id:W.call.id,name:W.call.name,input:W.call.input},preToolUse:{toolName:W.call.name,parameters:jQ(W.call.input)}});return},afterTool:async(Z)=>{let W=FH(Z);Q({...L0(W,J),hookName:"tool_result",iteration:W.iteration,tool_result:W.record,postToolUse:{toolName:W.record.name,parameters:jQ(W.record.input),result:typeof W.record.output==="string"?W.record.output:JSON.stringify(W.record.output),success:!W.record.error,executionTimeMs:W.record.durationMs}});return},afterRun:async({snapshot:Z,result:W})=>{let j=_$(Z);if(W.status==="completed"){Q({...L0(j,J),hookName:"agent_end",iteration:W.iterations,turn:{outputText:W.outputText,status:W.status},taskComplete:{taskMetadata:{}}});return}if(W.status==="aborted"||WW(W.error?.message)){Q({...L0(j,J),hookName:"agent_abort",reason:W.error?.message,taskCancel:{taskMetadata:{}}});return}if(W.error)Q({...L0(j,J),hookName:"agent_error",iteration:W.iterations,error:{name:W.error.name,message:W.error.message,stack:W.error.stack}})},onEvent:async(Z)=>{if(Z.type!=="message-added"||Z.message.role!=="user")return;let W=jW({snapshot:Z.snapshot},DH(Z.message.content));Q({...L0(W,J),hookName:"prompt_submit",userPromptSubmit:{prompt:W.userMessage,attachments:[]}})}}}function N6($){let J=kT($.workspacePath);if(!Object.values(J).some((B)=>B.length>0))return;let Z=async(B,A)=>{let K=J[A]??[];if(K.length===0)return;H2({commands:K,cwd:$.cwd,logger:$.logger,payload:A==="agent_resume"?{...L0(B,$),hookName:A,taskResume:{taskMetadata:{},previousState:{}}}:{...L0(B,$),hookName:A,taskStart:{taskMetadata:{}}}})},W=async(B)=>{let A=J.prompt_submit??[];if(A.length>0)H2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...L0(B,$),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},j=async(B)=>{let A=J.tool_call??[];if(A.length===0)return;return IT({commands:A,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...L0(B,$),hookName:"tool_call",iteration:B.iteration,tool_call:{id:B.call.id,name:B.call.name,input:B.call.input},preToolUse:{toolName:B.call.name,parameters:jQ(B.call.input)}}})},f=async(B)=>{let A=J.tool_result??[];if(A.length===0)return;H2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...L0(B,$),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:jQ(B.record.input),result:typeof B.record.output==="string"?B.record.output:JSON.stringify(B.record.output),success:!B.record.error,executionTimeMs:B.record.durationMs}}})},X=async(B)=>{let A=J.agent_end??[];if(A.length===0)return;H2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...L0(B,$),hookName:"agent_end",iteration:B.iteration,turn:B.turn,taskComplete:{taskMetadata:{}}}})},Y=async(B)=>{let A=J.agent_error??[];if(A.length===0)return;H2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...L0(B,$),hookName:"agent_error",iteration:B.iteration,error:{name:B.error.name,message:B.error.message,stack:B.error.stack}}})},V=async(B)=>{if(WW(B.reason)){let K=J.agent_abort??[];if(K.length>0)H2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...L0(B,$),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let A=J.session_shutdown??[];if(A.length===0)return;H2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...L0(B,$),hookName:"session_shutdown",reason:B.reason}})},H={};if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0||(J.prompt_submit?.length??0)>0){if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0)H.beforeRun=async(B)=>{let A=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Z(_$(B.snapshot),A);return};if((J.prompt_submit?.length??0)>0)H.onEvent=async(B)=>{if(B.type!=="message-added"||B.message.role!=="user")return;await W(jW({snapshot:B.snapshot},DH(B.message.content)))}}if((J.tool_call?.length??0)>0)H.beforeTool=async(B)=>{let A=await j(GH(B));return xT(A)};if((J.tool_result?.length??0)>0)H.afterTool=async(B)=>{await f(FH(B));return};if((J.agent_end?.length??0)>0)H.afterRun=async({snapshot:B,result:A})=>{if(A.status!=="completed")return;await X({..._$(B),iteration:A.iterations,turn:{outputText:A.outputText,status:A.status}})};if((J.agent_error?.length??0)>0||(J.agent_abort?.length??0)>0||(J.session_shutdown?.length??0)>0){let B=H.afterRun;H.afterRun=async(A)=>{await B?.(A);let{snapshot:K,result:G}=A;if(G.status==="aborted"||WW(G.error?.message)){await V({..._$(K),reason:G.error?.message});return}if(G.error)await Y({..._$(K),iteration:G.iterations,error:G.error})}}return H}function N8($){return M8("core.hook_config_files",N6($))}function B2($,J){let Q=$.map((Z)=>Z[J]).filter((Z)=>typeof Z==="function");if(Q.length===0)return;return async(Z)=>{let W;for(let j of Q){let f=await j(Z);if(!f||typeof f!=="object")continue;let X=f;W={...W??{},...X,stop:W?.stop===!0||X.stop===!0?!0:X.stop,options:W?.options||X.options?{...W?.options??{},...X.options??{}}:void 0}}return W}}function A2($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return;return{beforeRun:B2(J,"beforeRun"),afterRun:B2(J,"afterRun"),beforeModel:B2(J,"beforeModel"),afterModel:B2(J,"afterModel"),beforeTool:B2(J,"beforeTool"),afterTool:B2(J,"afterTool"),onEvent:B2(J,"onEvent")}}var UH={};w(UH,{normalizeRuntimeCapabilities:()=>_0});function _0(...$){let J,Q;for(let W of $){if(!W)continue;if(W.toolExecutors)J={...J??{},...W.toolExecutors};if(W.requestToolApproval)Q=W.requestToolApproval}let Z=J&&Object.keys(J).length>0;if(!Z&&!Q)return;return{...Z?{toolExecutors:J}:{},...Q?{requestToolApproval:Q}:{}}}var PH={};w(PH,{toProviderConfig:()=>d0,emptyStoredProviderSettings:()=>M$,StoredProviderSettingsSchema:()=>y8,StoredProviderSettingsEntrySchema:()=>wQ,ProviderSettingsSchemaTyped:()=>C8});import{z as T$}from"zod";var qH={};w(qH,{toProviderConfig:()=>d0,safeParseSettings:()=>NQ,safeCreateProviderConfig:()=>DW,parseSettings:()=>PQ,normalizeProviderId:()=>S8,isBuiltInProviderId:()=>GW,createProviderConfig:()=>FW,SapSettingsSchema:()=>TQ,ReasoningSettingsSchema:()=>zQ,ProviderSettingsSchema:()=>O$,ProviderProtocolSchema:()=>DQ,ProviderIdSchema:()=>E6,ProviderClientSchema:()=>UQ,OcaSettingsSchema:()=>MQ,ModelCatalogSettingsSchema:()=>qQ,GcpSettingsSchema:()=>_Q,BUILT_IN_PROVIDER_IDS:()=>KW,BUILT_IN_PROVIDER:()=>y6,AzureSettingsSchema:()=>OQ,AwsSettingsSchema:()=>LQ,AuthSettingsSchema:()=>RQ});import*as u0 from"@cline/llms";import{z as N}from"zod";var MH={};w(MH,{resolveProviderConfig:()=>C6,getProviderConfig:()=>FQ,getLiveModelsCatalog:()=>w8,clearPublicModelsCatalogCache:()=>WM,clearPrivateModelsCatalogCache:()=>AW,clearLiveModelsCatalogCache:()=>BW,OPENAI_COMPATIBLE_PROVIDERS:()=>S6,DEFAULT_MODELS_CATALOG_URL:()=>BQ});import*as B0 from"@cline/llms";function XW($){if(!Array.isArray($))return[];return $.map((J)=>{if(typeof J==="string")return J.trim();if(J&&typeof J==="object"){let Q=J;for(let Z of[Q.id,Q.name,Q.model])if(typeof Z==="string"&&Z.trim())return Z.trim()}return""}).filter((J)=>J.length>0)}function gT($,J){let Q=XW($);if(Q.length>0)return Q;if(!$||typeof $!=="object")return[];let Z=$,W=XW(Z.data??Z.models);if(W.length>0)return W;if(Z.models&&typeof Z.models==="object"&&!Array.isArray(Z.models)){let f=Object.keys(Z.models).filter((X)=>X.trim().length>0);if(f.length>0)return f}let j=Z.providers?.[J];if(j&&typeof j==="object"){let X=XW(j.models??j);if(X.length>0)return X}return[]}async function fQ($,J){let Q=await fetch($,{method:"GET"});if(!Q.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Q.status}`);return gT(await Q.json(),J)}function RH($){return $.replace(/\/+$/,"")}function XQ($,J,Q){let Z=Q?.trim();if(!Z)return;let W=$?.trim();if(!W||!J?.trim())return Z;try{let j=new URL(Z),f=new URL(J),X=new URL(W);if(j.origin!==f.origin)return Z;let Y=RH(f.pathname),V=RH(X.pathname);if(Y&&j.pathname.startsWith(`${Y}/`)){let H=j.pathname.slice(Y.length);X.pathname=`${V}${H}`}else X.pathname=j.pathname;return X.search=j.search,X.hash=j.hash,X.toString()}catch{return Z}}function mT($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{...Q}]))}function vT($){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 cT=Object.values(B0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:mT($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),LH=Object.fromEntries(cT.map(($)=>[$.id,$]));function uT($){return LH[$]}function dT(){return Object.fromEntries(Object.entries(LH).filter(([,$])=>vT($)))}function _H($=[]){let J=$.flatMap((Q)=>{switch(Q){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Q];default:return[]}});return J.length>0?J:void 0}var BQ="https://models.dev/api.json",lT=600000,OH=300000,pT=5000,HQ=new Map,w6=new Map,YW=new Map,YQ=new Map;async function rT(){return B0.getGeneratedProviderModels()}async function iT($,J={},Q={},Z={},W={},j={}){let f=await rT(),X=B0.resolveProviderModelCatalogKeys($),Y=Object.assign({},...X.map((B)=>f[B]??{})),V=Boolean(B0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),H=Object.keys(W).length>0;if(V&&H)return B0.sortModelsByReleaseDate({...W,...j});if($==="openai-codex")return B0.sortModelsByReleaseDate({...J,...B0.filterOpenAICodexModels(Q),...W,...j});return B0.sortModelsByReleaseDate({...Y,...J,...Q,...Z,...W,...j})}function nT($,J){let Q=B0.resolveProviderModelCatalogKeys($);return Object.assign({},...Q.map((Z)=>J[Z]??{}))}function AQ($){let J=$?.trim();return J&&J.length>0?J:""}function HW($){let J=$.apiKey?.trim()||$.accessToken?.trim();return J&&J.length>0?J:void 0}function aT($){let J=2166136261;for(let Q=0;Q<$.length;Q+=1)J^=$.charCodeAt(Q),J+=(J<<1)+(J<<4)+(J<<7)+(J<<8)+(J<<24);return(J>>>0).toString(16)}function sT($,J){return`${$}:${AQ(J.baseUrl)}:${aT(HW(J)??"")}`}async function KQ($,J,Q=pT){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await fetch($,{...J,signal:Z.signal})}finally{clearTimeout(W)}}function K2($,J,Q){if(Q&&!$.includes(J))$.push(J)}function GQ($,J){let Q=["streaming","tools"];return K2(Q,"images",Boolean(J.supportsImages)),K2(Q,"prompt-cache",Boolean(J.supportsPromptCache)),K2(Q,"reasoning",Boolean(J.supportsReasoning)),{id:$,name:J.name??$,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxTokens:J.maxTokens,capabilities:Q,releaseDate:J.releaseDate,status:"active"}}async function oT($,J){let Q=await KQ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"}});if(!Q.ok)throw Error(`Baseten model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let Y=f.supported_features??[];j[X]=GQ(X,{name:X,contextWindow:f.context_length,maxInputTokens:f.context_length,maxTokens:f.max_completion_tokens,supportsReasoning:Y.includes("reasoning")||Y.includes("reasoning_effort"),supportsImages:!1})}return j}function zH($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let J=Number($);return Number.isFinite(J)?J:void 0}return}async function tT($,J){let Q=await KQ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":J}});if(!Q.ok)throw Error(`Hicap model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;j[X]=GQ(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function eT($,J){let Z=`${(AQ($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,W=await KQ(Z,{method:"GET",headers:{Authorization:`Bearer ${J}`,accept:"application/json"}});if(!W.ok)throw Error(`Poolside model refresh failed: HTTP ${W.status}`);let f=(await W.json())?.data??[],X={};for(let Y of f){let V=Y.id?.trim();if(!V)continue;let H=Y.supported_features??[],B=Y.supported_sampling_parameters??[],A=Y.input_modalities??[],K=["streaming"];K2(K,"tools",H.includes("tools")),K2(K,"reasoning",H.includes("reasoning")),K2(K,"temperature",B.includes("temperature")),K2(K,"images",A.includes("image"));let G={input:zH(Y.pricing?.prompt),output:zH(Y.pricing?.completion)};X[V]={id:V,name:Y.name??V,description:Y.description,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function $M($){let J=AQ($);if(!J)return"http://localhost:4000";return J.endsWith("/v1")?J.slice(0,-3):J}async function JM($,J){let Z=`${$M($.baseUrl)}/v1/model/info`,W=async(V)=>KQ(Z,{method:"GET",headers:{accept:"application/json",...V}}),j=await W({"x-litellm-api-key":J});if(!j.ok)j=await W({Authorization:`Bearer ${J}`});if(!j.ok)throw Error(`LiteLLM model refresh failed: HTTP ${j.status}`);let X=(await j.json())?.data??[],Y={};for(let V of X){let H=V.model_name?.trim(),A=V.litellm_params?.model?.trim()||H;if(!A)continue;let K=V.model_info,G=GQ(A,{name:H??A,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(Y[A]=G,H)Y[H]={...G,id:H,name:H}}return Y}var TH={baseten:oT,hicap:tT,litellm:JM,poolside:eT},VW=new Map,VQ=new Map;function QM($,J){return`${$}:${AQ(J.baseUrl)}`}async function ZM($,J,Q){let Z=B0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=XQ(Q.baseUrl,Z?.provider.baseUrl,Z?.provider.modelsSourceUrl);if(!W)return{};let j=J?.cacheTtlMs??OH,f=QM($,Q),X=Date.now(),Y=VW.get(f);if(Y&&Y.expiresAt>X)return Y.data;let V=VQ.get(f);if(V)return V;let H=fQ(W,$).then((B)=>{let A=Object.fromEntries(B.map((K)=>[K,GQ(K,{name:K})]));return VW.set(f,{data:A,expiresAt:X+j}),A}).finally(()=>{VQ.delete(f)});return VQ.set(f,H),H}function WM(){VW.clear(),VQ.clear()}async function jM($,J){let Q=HW(J);if(!Q)return{};let Z=TH[$];if(!Z)return{};return Z(J,Q)}function fM($,J,Q){if(!Q)return!1;if(!TH[$])return!1;if(J?.loadPrivateOnAuth===!1)return!1;return Boolean(HW(Q))}async function XM($,J,Q){let Z=J?.cacheTtlMs??OH,W=sT($,Q),j=Date.now(),f=YW.get(W);if(f&&f.expiresAt>j)return f.data;let X=YQ.get(W);if(X)return X;let Y=jM($,Q).then((V)=>{return YW.set(W,{data:V,expiresAt:j+Z}),V}).finally(()=>{YQ.delete(W)});return YQ.set(W,Y),Y}async function YM($){return B0.fetchModelsDevProviderModels($,globalThis.fetch)}async function w8($={}){let J=$.url??BQ,Q=$.cacheTtlMs??lT,Z=Date.now(),W=HQ.get(J);if(W&&W.expiresAt>Z)return W.data;let j=w6.get(J);if(j)return j;let f=YM(J).then((X)=>{return HQ.set(J,{data:X,expiresAt:Z+Q}),X}).finally(()=>{w6.delete(J)});return w6.set(J,f),f}function BW($){if($){HQ.delete($),w6.delete($);return}HQ.clear(),w6.clear()}function AW(){YW.clear(),YQ.clear()}function VM($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{baseUrl:Q.baseUrl,modelId:Q.modelId,capabilities:_H(Q.capabilities)}]))}var S6=VM(dT());function FQ($){let J=uT($);if(!J)return;return{baseUrl:J.baseUrl||void 0,modelId:J.modelId,knownModels:J.knownModels,capabilities:_H(J.capabilities)}}async function C6($,J,Q){let Z=FQ($);if(!Z)return;try{let W=J?.loadLatestOnInit?await w8(J):void 0,j=W?nT($,W):{},f=Q&&fM($,J,Q)?await XM($,J,Q):{},Y=Boolean(B0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Q??{providerId:$,modelId:Z.modelId,baseUrl:Z.baseUrl}:Q,V=Y?await ZM($,J,Y).catch(()=>({})):{},H=await iT($,Z.knownModels,j,f,V,Q?.knownModels);return{...Z,knownModels:H}}catch(W){if(J?.failOnError)throw W;return Z}}var y6=u0.BUILT_IN_PROVIDER,KW=u0.BUILT_IN_PROVIDER_IDS,GW=u0.isBuiltInProviderId,S8=u0.normalizeProviderId,E6=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),DQ=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),UQ=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),RQ=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),HM=N.enum(["none","low","medium","high","xhigh"]),zQ=N.object({enabled:N.boolean().optional(),effort:HM.optional(),budgetTokens:N.number().int().positive().optional()}),LQ=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()}),_Q=N.object({projectId:N.string().optional(),region:N.string().optional()}),OQ=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),TQ=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()}),MQ=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),qQ=N.object({loadLatestOnInit:N.boolean().optional(),loadPrivateOnAuth:N.boolean().optional(),url:N.string().url().optional(),cacheTtlMs:N.number().int().positive().optional(),failOnError:N.boolean().optional()}),O$=N.object({provider:E6,apiKey:N.string().optional(),auth:RQ.optional(),model:N.string().optional(),protocol:DQ.optional(),client:UQ.optional(),routingProviderId:E6.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:zQ.optional(),aws:LQ.optional(),gcp:_Q.optional(),azure:OQ.optional(),sap:TQ.optional(),oca:MQ.optional(),region:N.string().optional(),apiLine:N.enum(["china","international"]).optional(),capabilities:N.array(N.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:qQ.optional()});function PQ($){return O$.parse($)}function NQ($){return O$.safeParse($)}function BM($){return $.protocol==="openai-responses"||$.client==="openai"}function d0($,J={}){let Q=$.provider,Z=S8(Q),W=J.includeKnownModels!==!1,j=$.reasoning?.effort||"none",f=j==="none"?void 0:j,X=S6[Z],Y=Object.assign({},...u0.resolveProviderModelCatalogKeys(Z).map((R)=>u0.getGeneratedModelsForProvider(R))),V=Object.keys(Y)[0],H=Q8(Z,$),B=$.baseUrl??(Z==="oca"?$.oca?.mode==="internal"?q5:P5:X?.baseUrl),A=$.routingProviderId??(BM($)&&Z!==y6.OPENAI_NATIVE?y6.OPENAI_NATIVE:void 0),K=W?X?.knownModels??(Object.keys(Y).length>0?Y:void 0):void 0,G={providerId:Q,clientType:$.client,routingProviderId:A,modelId:$.model??X?.modelId??V??"default",...W?{knownModels:K}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:B,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:f,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,D])=>D!==void 0))}function FW($){let J=PQ($);return d0(J)}function DW($){let J=NQ($);if(J.success)return{success:!0,config:d0(J.data)};return{success:!1,error:J.error}}var C8=O$;var wQ=T$.object({settings:O$,updatedAt:T$.string().datetime(),tokenSource:T$.enum(["manual","oauth","migration"]).default("manual")}),y8=T$.object({version:T$.literal(1),lastUsedProvider:T$.string().min(1).optional(),providers:T$.record(T$.string(),wQ)});function M$(){return{version:1,providers:{}}}t0();var NH={};w(NH,{InMemoryWorkspaceManager:()=>E8});import{upsertWorkspaceInfo as AM,WorkspaceManifestSchema as UW}from"@cline/shared";class E8{manifest;listeners=new Set;constructor($){this.manifest=UW.parse($??{workspaces:{}})}async addWorkspacePath($){let J=await v2($);return this.manifest=AM(this.manifest,J),this.emit({type:"workspace_added",workspace:J}),J}async switchWorkspace($){let J=P1($),Q=this.manifest.workspaces[J];if(Q)return this.manifest=UW.parse({...this.manifest,currentWorkspacePath:J}),this.emit({type:"workspace_switched",workspace:Q}),Q;let Z=await this.addWorkspacePath(J);return this.manifest=UW.parse({...this.manifest,currentWorkspacePath:Z.rootPath}),this.emit({type:"workspace_switched",workspace:Z}),Z}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let J=P1($);return this.manifest.workspaces[J]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let J of this.listeners)J($)}}O0();import{createHash as KM}from"node:crypto";var wH=new Set,SH=new Set;function GM($){return KM("sha256").update($).digest("hex")}function FM($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function CH($){if(!$.telemetry)return;let J=GM($.rootPath),Q=$.rootCount??1;if(!wH.has(J))wH.add(J),gJ($.telemetry,{root_count:Q,vcs_types:FM($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!SH.has(J)){SH.add(J);let Z=Error($.initError.message);Z.name=$.initError.errorType||"Error",mJ($.telemetry,Z,{fallback_to_single_root:!0,workspace_count:Q})}}function UM($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function RM($,J,Q){if(J.length>0)for(let j of J)Q?.log(j.message,{severity:"warn"});if($.length===0)return;let Z=$.slice(0,3).map(UM).join("; "),W=$.length>3?`; and ${$.length-3} more`:"";Q?.log(`Some plugins failed to initialize. ${Z}${W}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Q?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function zM($,J){let Q=typeof $.thinking==="boolean",Z=typeof $.reasoningEffort==="string";if(!Q&&!Z)return J;return{...J??{},...Q?{enabled:$.thinking}:{},...Z?{effort:$.reasoningEffort}:{}}}function yH($,J){return DM($,J)}function LM($){let J=0;for(let Q of $??[]){if(Q.role!=="user")continue;if(("metadata"in Q&&Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0)?.kind==="recovery_notice")continue;J+=1}return J}function _M($){let J={...$.storedHeaders??{},...$.configHeaders??{}},Q=$.accountId?.trim()||OM($.accessToken);if(J.originator="cline",J.session_id=$.sessionId,J["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,Q)J["ChatGPT-Account-Id"]=Q;return J}function OM($){let J=$?.trim();if(!J)return;let Q=q0(J),Z=Q?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let W=Q?.organizations?.[0]?.id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return}function TM($,J,Q,Z,W){let j=Q.getProviderSettings($.providerId),f=Z||j?.modelCatalog?{...Z??{},...j?.modelCatalog??{}}:void 0,X=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,Y={...j??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??j?.apiKey,baseUrl:$.baseUrl??j?.baseUrl,headers:$.providerId==="openai-codex"?_M({sessionId:J,configHeaders:$.headers,storedHeaders:j?.headers,accountId:j?.auth?.accountId,accessToken:$.apiKey??j?.auth?.accessToken??j?.apiKey}):$.headers??j?.headers,reasoning:zM($,j?.reasoning),modelCatalog:f},V={...d0(Y),...X??{}};if($.knownModels)V.knownModels=$.knownModels;if($.extensionContext)V.extensionContext=$.extensionContext;let B=$.fetch??V.fetch??W;if(B)V.fetch=B;return V}async function EH($){let{input:J,sessionId:Q,providerSettingsManager:Z,defaultTelemetry:W,defaultCapabilities:j,defaultToolPolicies:f,defaultFetch:X,onPluginEvent:Y,onTeamEvent:V,createSubAgentLifecycleCallbacks:H,createSpawnTool:B,localRuntime:A,readSessionMetadata:K,writeSessionMetadata:G}=$,R=R$(J.config),{modelCatalogDefaults:D,userInstructionService:U,configExtensions:F,onTeamRestored:O,...T}=A??{},L=Object.keys(T).length>0?T:void 0,{workspaceInfo:z,workspaceMetadata:P,durationMs:S,vcsType:b,initError:u}=await e9(R),o=L?.extensionContext,J0={...o??{},workspace:{...z,...o?.workspace??{}},session:{...o?.session??{},sessionId:Q},logger:o?.logger??L?.logger,telemetry:o?.telemetry??L?.telemetry??W};CH({telemetry:J0.telemetry,rootPath:z.rootPath,workspaceInfo:z,rootCount:1,vcsType:b,durationMs:S,initError:u,featureFlagEnabled:!0});let t=N8({cwd:J.config.cwd,workspacePath:R,rootSessionId:Q,logger:L?.logger,workspaceInfo:z}),o0=CV(L?.hooks)?void 0:P8({rootSessionId:Q,workspacePath:R,workspaceInfo:z}),b$=A2([L?.hooks,o0]),n;if(yH(F,"plugins"))try{n=await T8({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:J.config.cwd,onEvent:Y,providerId:J.config.providerId,modelId:J.config.modelId,workspaceInfo:z,session:J0.session,client:J0.client,user:J0.user,logger:J0.logger,telemetry:J0.telemetry,automation:J0.automation}),RM(n.failures,n.warnings,L?.logger)}catch(I2){let a9=I2 instanceof Error?I2.message:String(I2);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${a9})`)}let C=k7(t?[t]:void 0,k7(L?.extensions,j5(n?.extensions))),F0=yH(F,"plugins")?Y2(n?.pluginPaths??[]):void 0,f0={...J.config,...L??{},sessionId:Q,hooks:b$,extensions:C,extensionContext:J0,telemetry:J0.telemetry},w0=TM(f0,Q,Z,D,X),h2=A2([f0.hooks,f0.checkpoint?.enabled===!0?YH({cwd:f0.cwd,sessionId:Q,logger:f0.logger,createCheckpoint:f0.checkpoint?.createCheckpoint,initialRunCount:LM(J.initialMessages),readSessionMetadata:K,writeSessionMetadata:G}):void 0]),T1={...f0,providerConfig:w0,workspaceMetadata:P,hooks:h2},f1=J.toolPolicies??f0.toolPolicies??f,X4=_0(j,J.capabilities),k2=X4?.requestToolApproval,SJ=X4?.toolExecutors,M1=H?.(T1),CJ=new E8({currentWorkspacePath:z.rootPath,workspaces:{[z.rootPath]:z}});return{effectiveInput:J,config:T1,providerConfig:w0,workspaceMetadata:P,workspaceInfo:z,extensions:C,hooks:h2,toolPolicies:f1,requestToolApproval:k2,pluginSandboxShutdown:n?.shutdown,runtimeBuilderInput:{config:T1,hooks:h2,extensions:C,onTeamEvent:V,createSpawnTool:B,onTeamRestored:O,onSubAgentEvent:M1?.onSubAgentEvent,onSubAgentStart:M1?.onSubAgentStart,onSubAgentEnd:M1?.onSubAgentEnd,userInstructionService:U,pluginSkillDirectories:F0,configExtensions:F,toolExecutors:SJ,toolPolicies:f1,workspaceManager:CJ,logger:T1.logger,telemetry:T1.telemetry,requestToolApproval:k2}}}import{existsSync as CQ,mkdirSync as MM,readdirSync as qM,rmdirSync as PM,rmSync as NM,unlinkSync as wM}from"node:fs";import{dirname as bH,join as SQ}from"node:path";function e(){return new Date().toISOString()}function b6($){if(!$||!CQ($))return;try{wM($)}catch{}}function SM($){let J=F8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:`${J.agentId}__${J.teamTaskId}`};let Q=A6($);if(Q)return{rootSessionId:Q.rootSessionId,fileStem:Q.agentId};return{rootSessionId:$,fileStem:$}}class RW{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return SQ(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let J=this.sessionArtifactsDir($);if(!CQ(J))MM(J,{recursive:!0});return J}sessionMessagesPath($){return SQ(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,J=!1){let Q=J?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return SQ(Q,`${$}.json`)}removeSessionDirIfEmpty($){let J=this.sessionArtifactsDir($),Q=this.ensureSessionsDir();while(J.startsWith(Q)&&J!==Q){if(!CQ(J)){J=bH(J);continue}try{if(qM(J).length>0)break;PM(J)}catch{break}J=bH(J)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!CQ($))return;try{NM($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,J,Q){let{rootSessionId:Z,fileStem:W}=SM($),j=this.sessionArtifactsDir(Z);return{messagesPath:SQ(j,`${W}.messages.json`)}}}import{resolveDocumentsExtensionPath as CM}from"@cline/shared/storage";O0();function hH($,J,Q,Z,W){if(Q)cJ($.telemetry,{ulid:J,apiProvider:$.providerId,...W});else vJ($.telemetry,{ulid:J,apiProvider:$.providerId,...W});yM($.telemetry,{workspacePath:Z})}function yM($,J){let Q=CM("Hooks"),Z=L$(J.workspacePath),W=new Map;for(let j of Z){let f=j.hookEventName??"unknown",X=W.get(f)??{global:0,workspace:0};if(j.path===Q||j.path.startsWith(`${Q}/`))X.global+=1;else X.workspace+=1;W.set(f,X)}for(let[j,f]of W.entries())oJ($,j,f.global,f.workspace)}function kH($,J){for(let Q of J.mentions)aJ($,Q,J.matchedFiles.includes(Q)?1:0,"file",!J.matchedFiles.includes(Q));for(let Q of J.matchedFiles)iJ($,"file",Q.length);for(let Q of J.ignoredMentions)nJ($,"file","not_found",Q)}var aK={};w(aK,{ProviderSettingsManager:()=>_1});import{chmodSync as JG,existsSync as Gj,mkdirSync as VE,readFileSync as HE,writeFileSync as BE}from"node:fs";import{basename as QG,dirname as Fj}from"node:path";import{resolveProviderSettingsPath as AE}from"@cline/shared/storage";var M={};w(M,{writeHubDiscovery:()=>V5,writeGlobalSettings:()=>y1,withHubStartupLock:()=>H5,verifyHubConnection:()=>H1,updateMcpServerOAuthState:()=>R2,updateLocalProvider:()=>S9,uninstallPlugin:()=>k3,truncateNotificationBody:()=>OJ,toggleDisabledTool:()=>Z5,toTeamProgressLifecycleEvent:()=>r8,toProviderConfig:()=>d0,toHubStatusUrl:()=>UZ,toHubHealthUrl:()=>B5,toHookConfigFileName:()=>P6,syncPluginMcpServersToSettings:()=>P3,summarizeUsageFromMessages:()=>U8,stopLocalHubServerGracefully:()=>SZ,startLocalOAuthServer:()=>Q1,startHubWebSocketServer:()=>qJ,startHubServer:()=>tK,startClineDeviceAuth:()=>mZ,splitCoreSessionConfig:()=>q4,spawnDetachedHubServerWithRetry:()=>a2,spawnDetachedHubServer:()=>TZ,setTelemetryOptOutGlobally:()=>Ff,setMcpServerDisabled:()=>D2,setDisabledTools:()=>HZ,setDisabledPlugin:()=>_f,setAutoUpdateEnabledGlobally:()=>Uf,sendHubCommand:()=>$X,saveProviderOAuthCredentials:()=>p$,saveLocalProviderSettings:()=>d3,saveLocalProviderOAuthCredentials:()=>i3,sanitizeSessionToken:()=>Z2,safeParseSettings:()=>NQ,safeCreateProviderConfig:()=>DW,runSubprocessEvent:()=>s8,runHook:()=>t8,reviveTeamStateDates:()=>l5,restartLocalHubIfIdleAfterStartupTimeout:()=>D5,resolveWorkspaceHubOwnerContext:()=>If,resolveWorkflowsConfigSearchPaths:()=>l6,resolveSkillsConfigSearchPaths:()=>u6,resolveSharedHubOwnerContext:()=>$1,resolveSessionBackend:()=>B3,resolveRulesConfigSearchPaths:()=>d6,resolveProviderConfig:()=>C6,resolveProviderApiKeyFromSettings:()=>pZ,resolveProductionHubOwnerContext:()=>V1,resolvePluginSkillDirectoriesFromPaths:()=>Y2,resolvePluginConfigSearchPaths:()=>O6,resolveMcpServerRegistrations:()=>K1,resolveLocalClineAuthToken:()=>a3,resolveHubUrl:()=>CZ,resolveHubOwnerContext:()=>I1,resolveHubEndpointOptions:()=>Y1,resolveHubBuildId:()=>Y5,resolveHooksConfigSearchPaths:()=>M6,resolveDisabledToolNames:()=>X1,resolveDisabledPluginPaths:()=>L4,resolveDefaultMcpSettingsPath:()=>A0,resolveDefaultHubPort:()=>n2,resolveDefaultHubPathname:()=>OZ,resolveDefaultHubHost:()=>_Z,resolveCoreSelectedToolIds:()=>r5,resolveCoreDistinctId:()=>S0,resolveCompatibleLocalHubUrl:()=>S4,resolveClineDir:()=>Ef,resolveClineDataDir:()=>m$,resolveAndLoadAgentPlugins:()=>T8,resolveAgentPluginPaths:()=>X2,requestHubShutdown:()=>w4,requestDesktopToolApproval:()=>O3,removePluginMcpServersFromSettings:()=>UJ,rememberRecoverableLocalHubUrl:()=>W$,registerRemoteConfigSessionBlobUpload:()=>G9,registerMcpServersFromSettingsFile:()=>z2,registerDisposable:()=>jE,refreshProviderModelsFromSource:()=>l3,refreshOpenAICodexToken:()=>M5,refreshOcaToken:()=>w5,refreshClineToken:()=>O5,readSessionCheckpointHistory:()=>LJ,readRemoteConfigSessionBlobUploadMetadata:()=>K3,readHubDiscovery:()=>X0,readGlobalSettings:()=>T0,readBearerToken:()=>c9,probeHubServer:()=>x1,probeHubConnection:()=>ef,prewarmFileIndex:()=>I5,prewarmDetachedHubServer:()=>K5,prepareRemoteConfigCoreIntegration:()=>F3,parseWorkflowConfigFromMarkdown:()=>c6,parseUserCommandEnvelope:()=>WE,parseSkillConfigFromMarkdown:()=>m6,parseSettings:()=>PQ,parseRuleConfigFromMarkdown:()=>v6,parseHookEventPayload:()=>o8,parseConfiguredAgentConfig:()=>YJ,normalizeWorkspacePath:()=>P1,normalizeUserInput:()=>ZE,normalizeSdkError:()=>QE,normalizeRuntimeCapabilities:()=>_0,normalizeProviderId:()=>S8,normalizeOAuthProvider:()=>p3,normalizeHubWebSocketUrl:()=>j$,noopBasicLogger:()=>JE,migrateLegacyProviderSettings:()=>zJ,mergeRulesForSystemPrompt:()=>m2,mergeAgentHooks:()=>A2,makeTeamTaskSubSessionId:()=>B6,makeSubSessionId:()=>G8,loginOpenAICodex:()=>E4,loginOcaOAuth:()=>k4,loginLocalProvider:()=>r3,loginClineOAuth:()=>C4,loginAndSaveProviderOAuthCredentials:()=>x4,loginAndSaveLocalProviderOAuthCredentials:()=>n3,loadOpenTelemetryAdapter:()=>cy,loadMcpSettingsFile:()=>F2,loadLlmsConfigFromFile:()=>Bj,loadConfiguredAgentConfigs:()=>d8,loadAgentPluginsFromPathsWithDiagnostics:()=>f2,loadAgentPluginsFromPaths:()=>o5,loadAgentPluginFromPath:()=>L6,listSessionHistoryFromBackend:()=>pW,listPluginToolsWithDiagnostics:()=>aQ,listPluginTools:()=>e6,listMcpServerOAuthStatuses:()=>o6,listLocalProviders:()=>c3,listHookConfigFiles:()=>L$,isToolDisabledGlobally:()=>Rf,isTelemetryOptedOutGlobally:()=>Q5,isSessionNotFoundError:()=>k1,isRuleEnabled:()=>EJ,isPluginDisabledGlobally:()=>Lf,isOAuthProvider:()=>l$,isHubReconnectableTransportError:()=>NZ,isHubCommandTimeoutError:()=>F5,isDiscoveryFilePresent:()=>hf,isClineAccountActionRequest:()=>yQ,isBuiltInProviderId:()=>GW,isAutoUpdateEnabledGlobally:()=>Df,identifyAccount:()=>C1,hasMcpSettingsFile:()=>r1,getValidOpenAICodexCredentials:()=>b4,getValidOcaCredentials:()=>I4,getValidClineCredentials:()=>y4,getProviderOAuthCredentialsFromSettings:()=>g4,getProviderConfigFields:()=>s3,getProviderConfig:()=>FQ,getProviderAuthStorageId:()=>lZ,getProviderAuthHandler:()=>Z0,getPersistedProviderApiKey:()=>Q8,getMcpServerOAuthState:()=>U2,getLocalProviderModels:()=>u3,getLiveModelsCatalog:()=>w8,getFileIndex:()=>c1,getCurrentContextSize:()=>m7,getCoreHeadlessToolNames:()=>H6,getCoreDefaultEnabledToolIds:()=>p5,getCoreBuiltinToolCatalog:()=>J2,getCoreAcpToolNames:()=>i5,getClineDefaultSystemPrompt:()=>dy,generateWorkspaceInfoWithDiagnostics:()=>V4,generateWorkspaceInfo:()=>v2,formatRulesForSystemPrompt:()=>g2,formatProviderOAuthApiKey:()=>rZ,formatDisplayUserInput:()=>$E,filterExtensionToolRegistrations:()=>j5,filterDisabledTools:()=>E1,filterDisabledPluginPaths:()=>W5,fetchClineRecommendedModels:()=>Vj,executeClineAccountAction:()=>EQ,ensureHubWebSocketServer:()=>u9,ensureHubServer:()=>eK,ensureDetachedHubServer:()=>uf,ensureCustomProvidersLoaded:()=>P9,ensureCompatibleLocalHubUrl:()=>u$,enrichPromptWithMentions:()=>X8,emptyWorkspaceManifest:()=>oy,emptyStoredProviderSettings:()=>M$,discoverPluginModulePaths:()=>T6,disablePluginMcpServersInSettings:()=>N3,deriveSubsessionStatus:()=>K6,deleteLocalProvider:()=>C9,defineLlmsConfig:()=>Hj,createWorkflowsConfigDefinition:()=>i6,createUserInstructionConfigService:()=>q$,createToolPoliciesWithPreset:()=>g5,createTool:()=>sy,createTeamName:()=>U9,createSubprocessHooks:()=>H9,createSpawnAgentTool:()=>D$,createSkillsConfigDefinition:()=>p6,createSessionHost:()=>a8,createRuntimeHost:()=>a8,createRulesConfigDefinition:()=>r6,createRemoteConfigSessionMessagesArtifactUploader:()=>G3,createProviderConfig:()=>FW,createOpenTelemetryTelemetryService:()=>M4,createOAuthClientCallbacks:()=>b8,createMcpTools:()=>m8,createLocalHubScheduleRuntimeHandlers:()=>oK,createLlmsSdk:()=>Kj,createInitialAccumulatedUsage:()=>G0,createInMemoryHubOwnerContext:()=>bf,createHubServerUrl:()=>e0,createHubAuthToken:()=>X5,createHookConfigFileHooks:()=>N6,createHookConfigFileExtension:()=>N8,createHookAuditHooks:()=>P8,createDisabledMcpToolPolicy:()=>t6,createDisabledMcpToolPolicies:()=>nQ,createDelegatedAgentConfigProvider:()=>G$,createDelegatedAgent:()=>F$,createDefaultToolsWithPreset:()=>m5,createDefaultTools:()=>B$,createDefaultMcpServerClientFactory:()=>x8,createDefaultExecutors:()=>Y8,createCoreSettingsService:()=>_2,createCoreSessionSnapshot:()=>F1,createContributionRegistry:()=>ay,createContextCompactionPrepareTurn:()=>l4,createConfiguredTelemetryService:()=>b1,createConfiguredTelemetryHandle:()=>i2,createConfiguredAgentTools:()=>l8,createClineTelemetryServiceMetadata:()=>ny,createClineTelemetryServiceConfig:()=>iy,createBuiltinTools:()=>Q2,createAgentTeamsTools:()=>$2,createAgentRuntime:()=>YE,createAgentHooksExtension:()=>M8,connectToHub:()=>U5,completeClineDeviceAuth:()=>vZ,clearPrivateModelsCatalogCache:()=>AW,clearLiveModelsCatalogCache:()=>BW,clearHubDiscovery:()=>C0,captureWorkspacePathResolved:()=>Vf,captureWorkspaceInitialized:()=>gJ,captureWorkspaceInitError:()=>mJ,captureToolUsage:()=>lJ,captureTokenUsage:()=>uJ,captureTaskRestarted:()=>cJ,captureTaskCreated:()=>vJ,captureTaskCompleted:()=>D4,captureSubagentExecution:()=>R4,captureSkillUsed:()=>pJ,captureSdkError:()=>ry,captureProviderConfigured:()=>Hf,captureProviderApiError:()=>U4,captureModeSwitch:()=>dJ,captureMentionUsed:()=>iJ,captureMentionSearchResults:()=>aJ,captureMentionFailed:()=>nJ,captureHookDiscovery:()=>oJ,captureExtensionActivated:()=>Yf,captureDiffEditFailure:()=>rJ,captureConversationTurnEvent:()=>u2,captureCompactionSkipped:()=>eJ,captureCompactionExecuted:()=>tJ,captureAuthSucceeded:()=>w1,captureAuthStarted:()=>N1,captureAuthLoggedOut:()=>Q$,captureAuthFailed:()=>S1,captureAgentTeamCreated:()=>sJ,captureAgentCreated:()=>Z$,buildWorkspaceMetadata:()=>H4,buildTeamProgressSummary:()=>p8,buildSdkErrorProperties:()=>ly,buildRemoteConfigSessionBlobUploadMetadata:()=>A9,buildDelegatedAgentConfig:()=>t$,buildConfiguredAgentToolName:()=>VJ,buildConfiguredAgentToolDescriptors:()=>HJ,bootstrapAgentTeams:()=>K8,authorizeMcpServerOAuth:()=>lQ,addLocalProvider:()=>v3,accumulateUsageTotals:()=>H0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>g6,UnifiedConfigFileWatcher:()=>G2,ToolPresets:()=>c0,TelemetryService:()=>p2,TelemetryLoggerSink:()=>T4,TEAM_TOOL_NAMES:()=>A8,SubprocessSandbox:()=>L8,StoredProviderSettingsSchema:()=>y8,StoredProviderSettingsEntrySchema:()=>wQ,SqliteTeamStore:()=>w2,SqliteSessionStore:()=>U1,SessionVersioningService:()=>y$,SessionVersioningError:()=>h0,SessionSource:()=>R0,SessionNotFoundError:()=>h1,SapSettingsSchema:()=>TQ,SKILLS_CONFIG_DIRECTORY_NAME:()=>x6,SESSION_STATUSES:()=>G6,SESSION_NOT_FOUND_ERROR_CODE:()=>g$,SDK_ERROR_TELEMETRY_EVENT:()=>fE,RpcClineAccountService:()=>k6,RemoteRuntimeHost:()=>u8,ReasoningSettingsSchema:()=>zQ,RULES_CONFIG_DIRECTORY_NAME:()=>mQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>K9,ProviderSettingsSchema:()=>O$,ProviderSettingsManager:()=>_1,ProviderProtocolSchema:()=>DQ,ProviderIdSchema:()=>E6,ProviderClientSchema:()=>UQ,OpenTelemetryProvider:()=>r2,OcaSettingsSchema:()=>MQ,OPENAI_COMPATIBLE_PROVIDERS:()=>S6,NodeHubClient:()=>J1,NoOpFeatureFlagsProvider:()=>q2,NativeHubTransportAdapter:()=>MJ,ModelCatalogSettingsSchema:()=>qQ,LocalRuntimeHost:()=>L1,Llms:()=>uy,InMemoryWorkspaceManager:()=>E8,InMemoryMcpManager:()=>L2,HubUIClient:()=>bZ,HubTransportError:()=>M0,HubSessionClient:()=>EZ,HubServerTransport:()=>f4,HubScheduleService:()=>c2,HubScheduleCommandService:()=>x2,HubRuntimeHost:()=>i1,HubCommandError:()=>s2,HookEventPayloadSchema:()=>V9,HookEventNameSchema:()=>Y9,HookConfigFileName:()=>q8,HOOK_CONFIG_FILE_EVENT_MAP:()=>q6,HOOKS_CONFIG_DIRECTORY_NAME:()=>ZQ,GlobalSettingsSchema:()=>z4,GcpSettingsSchema:()=>_Q,FileTeamPersistenceStore:()=>h9,FeatureFlagsService:()=>M2,FeatureFlagDefaultValue:()=>ey,FEATURE_FLAGS:()=>ty,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>v9,DefaultToolNames:()=>K0,DefaultRuntimeBuilder:()=>J4,DefaultLlmsSdk:()=>_J,DEFAULT_MODELS_CATALOG_URL:()=>BQ,DEFAULT_HUB_PORT:()=>zZ,DEFAULT_HUB_PATHNAME:()=>LZ,DEFAULT_HUB_HOST:()=>RZ,CoreSettingsService:()=>P$,CoreSessionService:()=>z1,ContributionRegistry:()=>py,ClineCore:()=>FJ,ClineAccountService:()=>h6,ChatViewStateSchema:()=>fj,ChatSummarySchema:()=>m9,ChatSessionStatusSchema:()=>I9,ChatSessionConfigSchema:()=>k9,ChatMessageSchema:()=>g9,ChatMessageRoleSchema:()=>x9,CORE_TELEMETRY_EVENTS:()=>g,CORE_BUILD_VERSION:()=>Xj,BrowserWebSocketHubAdapter:()=>TJ,BUILT_IN_PROVIDER_IDS:()=>KW,BUILT_IN_PROVIDER:()=>y6,AzureSettingsSchema:()=>OQ,AwsSettingsSchema:()=>LQ,AuthSettingsSchema:()=>RQ,AgentTeamsRuntime:()=>T2,AgentTeam:()=>n8,Agent:()=>XE,ALL_DEFAULT_TOOL_NAMES:()=>e1});q(M,Ur);import*as uy from"@cline/llms";import{buildClineSystemPrompt as dy,buildSdkErrorProperties as ly,ContributionRegistry as py,captureSdkError as ry,createClineTelemetryServiceConfig as iy,createClineTelemetryServiceMetadata as ny,createContributionRegistry as ay,createTool as sy,emptyWorkspaceManifest as oy,FEATURE_FLAGS as ty,FeatureFlagDefaultValue as ey,formatDisplayUserInput as $E,noopBasicLogger as JE,normalizeSdkError as QE,normalizeUserInput as ZE,parseUserCommandEnvelope as WE,registerDisposable as jE,SDK_ERROR_TELEMETRY_EVENT as fE}from"@cline/shared";import"@cline/shared/storage";var xH={};w(xH,{isClineAccountActionRequest:()=>yQ,executeClineAccountAction:()=>EQ,RpcClineAccountService:()=>k6,ClineAccountService:()=>h6});function EM($){if(typeof $!=="object"||$===null||!("error"in $))return;let J=$.error;return typeof J==="string"&&J.trim()?J:void 0}function IH($,J,Q){let Z=EM(Q);if(Z)return Z;let W=J.trim();if(W){let j=W.length>200?`${W.slice(0,200)}...`:W;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class h6{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let J=$.apiBaseUrl.trim();if(!J)throw Error("apiBaseUrl is required");this.apiBaseUrl=J,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let J=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(J)}/balance`)}async fetchUsageTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/usages`)).items??[]}async fetchPaymentTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}`)}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}/balance`)}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");let Q=await this.resolveOrganizationMemberId(J,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(J)}/members/${encodeURIComponent(Q)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let J=$?.trim();if(J)return J;let Z=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Z)return Z;let W=await this.fetchMe();if(!W.id?.trim())throw Error("Unable to resolve current user id");return W.id}async resolveOrganizationMemberId($,J){let Q=J?.trim();if(Q)return Q;let W=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(W)return W;let f=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!f?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return f}async request($,J){let Q=(await this.getAuthTokenFn())?.trim();if(!Q)throw Error("No Cline account auth token found");let Z=this.getHeadersFn?await this.getHeadersFn():{},W=new AbortController,j=setTimeout(()=>W.abort(),this.requestTimeoutMs);try{let f=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:J?.method??"GET",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",...Z??{}},body:J?.body!==void 0?JSON.stringify(J.body):void 0,signal:W.signal});if(f.status===204||J?.expectNoContent){if(!f.ok)throw Error(`Cline account request failed with status ${f.status}`);return}let X=await f.text(),Y;if(X.trim())try{Y=JSON.parse(X)}catch{if(!f.ok)throw Error(IH(f.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!f.ok)throw Error(IH(f.status,X,Y));if(typeof Y==="object"&&Y!==null){let V=Y;if(typeof V.success==="boolean"){if(!V.success)throw Error(V.error||"Cline account request failed");if(V.data!==void 0)return V.data}}if(Y===void 0||Y===null)throw Error("Cline account response payload was empty");return Y}finally{clearTimeout(j)}}}function yQ($){return $.action==="clineAccount"}async function EQ($,J){switch($.operation){case"fetchMe":return J.fetchMe();case"fetchBalance":return J.fetchBalance($.userId);case"fetchUsageTransactions":return J.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return J.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return J.fetchUserOrganizations();case"fetchOrganizationBalance":return J.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return J.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await J.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return J.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class k6{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:J})}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:J,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var gH={};w(gH,{createOAuthClientCallbacks:()=>b8});function b8($){return{onAuth:({url:J,instructions:Q})=>{if($.onOutput?.(Q??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(J)).catch((Z)=>{$.onOpenUrlError?.({url:J,error:Z})})}catch(Z){$.onOpenUrlError?.({url:J,error:Z})}$.onOutput?.(J)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var mA={};w(mA,{ClineCore:()=>FJ});function mH($){if($===!0)return{};if(!$)return;return $}function vH($){if($==="user")return"global";return $}class zW{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let J=this.getService().ingestEvent($);return{event:J.event,duplicate:J.duplicate,matchedSpecIds:J.matchedSpecs.map((Q)=>Q.specId),queuedRuns:J.queuedRuns,suppressions:J.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function cH($){let{host:J}=$;return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||R0.CLI,interactive:!1,config:{providerId:S8(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:kM(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content),delivery:Z.delivery});if(!W)throw Error("ClineCore automation runtime returned no result");return{result:hM(W)}},async abortSession(Q){return await J.abort(Q,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}function bQ($){let J=bM($.automationService,$.automation),Q=$.context?.client??($.clientName?{name:$.clientName}:void 0),Z=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),W=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!J&&!Q&&!Z&&!W&&!j)return $.context;return{...$.context??{},...Q?{client:Q}:{},...Z?{user:Z}:{},...W?{logger:W}:{},...j?{telemetry:j}:{},...J?{automation:J}:{}}}function bM($,J){if(!$)return;return{ingestEvent:(Q)=>{J.ingestEvent(Q)}}}function hM($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function kM($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var SB={};w(SB,{createCoreSettingsService:()=>_2,CoreSettingsService:()=>P$});import{existsSync as sQ}from"node:fs";import{basename as PB,isAbsolute as YP,relative as VP}from"node:path";var $B={};w($B,{resolveWorkflowsConfigSearchPaths:()=>l6,resolveSkillsConfigSearchPaths:()=>u6,resolveRulesConfigSearchPaths:()=>d6,parseWorkflowConfigFromMarkdown:()=>c6,parseSkillConfigFromMarkdown:()=>m6,parseRuleConfigFromMarkdown:()=>v6,createWorkflowsConfigDefinition:()=>i6,createUserInstructionConfigService:()=>q$,createSkillsConfigDefinition:()=>p6,createRulesConfigDefinition:()=>r6,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>g6,UnifiedConfigFileWatcher:()=>G2,SKILLS_CONFIG_DIRECTORY_NAME:()=>x6,RULES_CONFIG_DIRECTORY_NAME:()=>mQ});import{createHash as IM}from"node:crypto";import{watch as xM}from"node:fs";import{readdir as gM,readFile as mM}from"node:fs/promises";import{join as vM}from"node:path";function cM($){return IM("sha1").update($).digest("hex")}function lH($){return Boolean($&&typeof $==="object"&&"code"in $)}function uH($){return lH($)&&$.code==="ENOENT"}function dH($){return lH($)&&($.code==="EACCES"||$.code==="EPERM")}class G2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,J){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=J?.debounceMs??75,this.emitParseErrors=J?.emitParseErrors??!1;for(let Q of $){if(this.definitionsByType.has(Q.type))throw Error(`Duplicate unified config definition type '${Q.type}'.`);this.definitionsByType.set(Q.type,Q),this.recordsByType.set(Q.type,new Map),this.discoveredDirectoriesByType.set(Q.type,new Set);for(let Z of Q.directories){let W=this.baseTypesByDirectory.get(Z);if(W)W.add(Q.type);else this.baseTypesByDirectory.set(Z,new Set([Q.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let J=this.definitionsByType.get($);if(!J)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(J)})}getSnapshot($){let J=this.recordsByType.get($);return new Map([...J?.entries()??[]].map(([Q,Z])=>[Q,{...Z}]))}getAllSnapshots(){let $=new Map;for(let[J,Q]of this.recordsByType.entries())$.set(J,new Map([...Q.entries()].map(([Z,W])=>[Z,{...W}])));return $}emit($){for(let J of this.listeners)J($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[J,Q]of this.watchersByDirectory.entries()){if($.has(J))continue;Q.close(),this.watchersByDirectory.delete(J)}this.watchedTypesByDirectory=$;for(let J of $.keys()){if(this.watchersByDirectory.has(J))continue;try{let Q=xM(J,()=>{let Z=this.watchedTypesByDirectory.get(J);if(!Z)return;for(let W of Z)this.pendingTypes.add(W);this.scheduleFlush()});this.watchersByDirectory.set(J,Q),Q.on("error",(Z)=>{let W=this.watchedTypesByDirectory.get(J);if(!W)return;for(let j of W)this.emit({kind:"error",type:j,error:Z,filePath:J})})}catch(Q){if(!uH(Q)&&!dH(Q)){let Z=$.get(J);if(!Z)continue;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:J})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let J of $){let Q=this.definitionsByType.get(J);if(!Q)continue;await this.refreshTypeInternal(Q)}})},this.debounceMs)}async refreshTypeInternal($){let{records:J,discoveredDirectories:Q}=await this.loadDefinition($),Z=this.recordsByType.get($.type)??new Map;for(let[W,j]of Z.entries()){if(J.has(W))continue;this.emit({kind:"remove",type:$.type,id:W,filePath:j.filePath})}for(let[W,j]of J.entries()){let f=Z.get(W);if(f&&f.filePath===j.filePath&&f.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:W,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,J),this.discoveredDirectoriesByType.set($.type,Q),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let J=new Map,Q=new Set;for(let Z of $.directories){Q.add(Z);let W=$.discoverFiles?await $.discoverFiles(Z):await this.readDirectoryFileCandidates(Z);for(let j of W){let{fileName:f,filePath:X}=j;if(Q.add(j.directoryPath),$.includeFile&&!$.includeFile(f,X))continue;try{let Y=await mM(X,"utf8"),V={type:$.type,directoryPath:j.directoryPath,fileName:f,filePath:X,content:Y},H=$.parseFile(V),B=$.resolveId(H,V).trim();if(!B)continue;J.set(B,{type:$.type,id:B,item:H,filePath:X,fingerprint:cM(Y)})}catch(Y){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Y,filePath:X})}}}return{records:J,discoveredDirectories:Q}}buildDesiredTypesByDirectory(){let $=new Map;for(let[J,Q]of this.baseTypesByDirectory.entries())$.set(J,new Set(Q));for(let[J,Q]of this.discoveredDirectoriesByType.entries())for(let Z of Q){let W=$.get(Z);if(W)W.add(J);else $.set(Z,new Set([J]))}return $}async readDirectoryFileCandidates($){try{return(await gM($,{withFileTypes:!0})).filter((Q)=>Q.isFile()).map((Q)=>({directoryPath:$,fileName:Q.name,filePath:vM($,Q.name)})).sort((Q,Z)=>Q.fileName.localeCompare(Z.fileName))}catch(J){if(uH(J)||dH(J))return[];throw J}}}import{readdir as _W,readFile as uM,stat as LW}from"node:fs/promises";import{basename as p1,dirname as dM,extname as kQ,join as E0,resolve as I6}from"node:path";import{AGENTS_RULES_FILE_NAME as pH,RULES_CONFIG_DIRECTORY_NAME as mQ,resolveGlobalAgentsRulesPath as lM,resolveRulesConfigSearchPaths as pM,resolveSkillsConfigSearchPaths as rM,resolveWorkflowsConfigSearchPaths as iM,SKILLS_CONFIG_DIRECTORY_NAME as x6,WORKFLOWS_CONFIG_DIRECTORY_NAME as g6}from"@cline/shared/storage";import nM from"yaml";var hQ="SKILL.md",aM="managed.json",sM=new Set([".md",".markdown",".txt"]);function OW($){return $.trim().toLowerCase()}function h8($){let J=$;return J?.code==="ENOENT"||J?.code==="EACCES"||J?.code==="EPERM"||J?.code==="ELOOP"}function IQ($){return sM.has(kQ($).toLowerCase())}function rH($){let J=[],Q=new Set;for(let Z of $){let W=I6(Z);if(Q.has(W))continue;Q.add(W),J.push(Z)}return J}function oM($){let J=[...$?.directories??u6($?.workspacePath)];if($?.pluginSkillDirectories)J.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)J.push(...fH({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return rH(J)}async function TW($){try{let J=await _W($,{withFileTypes:!0}),Q=[];for(let Z of J){if(!Z.isDirectory())continue;let W=E0($,Z.name),j=E0(W,aM);try{let f=await uM(j,"utf8"),X=JSON.parse(f);if(X&&typeof X==="object")Q.push(W)}catch(f){if(h8(f))continue;if(f?.name==="SyntaxError")continue;throw f}}return Q.sort((Z,W)=>Z.localeCompare(W))}catch(J){if(h8(J))return[];throw J}}function MW($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q;try{let j=nM.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}catch(j){let f=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:f}}}function xQ($,J,Q){if($===void 0||$===null){if(Q)throw Error(`Missing required frontmatter field '${J}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${J}' must be a string.`);let Z=$.trim();if(!Z&&Q)throw Error(`Frontmatter field '${J}' cannot be empty.`);return Z||void 0}function k8($,J){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${J}' must be a boolean.`);return $}function tM($,J){if(p1($.filePath).toLowerCase()!==pH.toLowerCase())return p1($.filePath,kQ($.filePath));if(J&&I6($.filePath)===I6(J,pH))return"Workspace AGENTS.md";if(I6($.filePath)===I6(lM()))return"Global AGENTS.md";return p1($.filePath,kQ($.filePath))}function m6($,J){let{data:Q,body:Z,parseError:W}=MW($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in skill file.");let X=xQ(Q.name,"name",!1)??J.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:xQ(Q.description,"description",!1),disabled:k8(Q.disabled,"disabled")??(k8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function v6($,J){let{data:Q,body:Z,parseError:W}=MW($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in rule file.");let f=xQ(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing rule name.");return{name:f,disabled:k8(Q.disabled,"disabled")??(k8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function c6($,J){let{data:Q,body:Z,parseError:W}=MW($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in workflow file.");let f=xQ(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing workflow name.");return{name:f,disabled:k8(Q.disabled,"disabled")??(k8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function u6($){return rM($)}function d6($){return pM($)}function l6($){return iM($)}async function iH($){if(p1($)===".cline"){let J=await TW($);return(await Promise.all(J.map((Z)=>iH(E0(Z,x6))))).flat()}try{let J=await _W($,{withFileTypes:!0}),Q=[];for(let Z of J){if(Z.isFile()&&Z.name===hQ){Q.push({directoryPath:$,fileName:Z.name,filePath:E0($,Z.name)});continue}let W=E0($,Z.name);if(Z.isDirectory()||Z.isSymbolicLink()&&await LW(W).then((f)=>f.isDirectory()).catch((f)=>{if(h8(f))return!1;throw f}))Q.push({directoryPath:W,fileName:hQ,filePath:E0(W,hQ)})}return Q}catch(J){if(h8(J))return[];throw J}}async function gQ($){if(p1($)===".cline"){let J=await TW($);return(await Promise.all(J.map((Z)=>gQ(E0(Z,"rules.md"))))).flat()}try{if((await LW($)).isFile())return[{directoryPath:dM($),fileName:p1($),filePath:$}]}catch(J){if(!h8(J))throw J}try{let Q=(await _W($,{withFileTypes:!0})).filter((W)=>W.isFile()&&IQ(W.name)).map((W)=>({directoryPath:$,fileName:W.name,filePath:E0($,W.name)})),Z=E0($,"AGENTS.md");try{if((await LW(Z)).isFile()){if(!Q.some((f)=>f.fileName==="AGENTS.md"))Q.push({directoryPath:$,fileName:"AGENTS.md",filePath:Z})}}catch{}return Q}catch(J){if(h8(J))return[];throw J}}async function eM($){if(p1($)===".cline"){let J=await TW($);return(await Promise.all(J.map((Z)=>gQ(E0(Z,g6))))).flat()}return gQ($)}function p6($){let J=oM($),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Q?rH([...J,Q]):J,discoverFiles:iH,includeFile:(Z)=>Z===hQ,parseFile:(Z)=>m6(Z.content,p1(Z.directoryPath)),resolveId:(Z)=>OW(Z.name)}}function r6($){let J=$?.directories??d6($?.workspacePath),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Q?[...J,Q]:J,discoverFiles:gQ,includeFile:(Z,W)=>Z===".clinerules"||IQ(Z)||IQ(W),parseFile:(Z)=>v6(Z.content,tM(Z,$?.workspacePath)),resolveId:(Z)=>OW(Z.name)}}function i6($){let J=$?.directories??l6($?.workspacePath),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Q?[...J,Q]:J,discoverFiles:eM,includeFile:(Z)=>IQ(Z),parseFile:(Z)=>c6(Z.content,p1(Z.filePath,kQ(Z.filePath))),resolveId:(Z)=>OW(Z.name)}}function nH($){let J=[p6($?.skills),r6($?.rules),i6($?.workflows)];return new G2(J,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as aH}from"@cline/shared";function $q($,J){if($.description?.trim())return aH($.description,".");if(J==="workflow")return;return aH($.instructions,".")}function Jq($){return $.disabled!==!0}function sH($,J){return[...$.getSnapshot(J).entries()].map(([Q,Z])=>({id:Q,record:Z})).filter(({record:Q})=>Jq(Q.item)).map(({id:Q,record:Z})=>({id:Q,name:Z.item.name,instructions:Z.item.instructions,description:$q(Z.item,J),kind:J})).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function n6($){let J=new Map;for(let Q of[...sH($,"workflow"),...sH($,"skill")])if(!J.has(Q.name))J.set(Q.name,Q);return[...J.values()].sort((Q,Z)=>Q.name.localeCompare(Z.name))}function oH($,J){if(!$.startsWith("/")||$.length<2)return $;let Q=$.match(/^\/(\S+)/);if(!Q)return $;let Z=Q[1];if(!Z)return $;let W=Z.length+1,j=$.slice(W),f=n6(J).find((X)=>X.name===Z);return f?`${f.instructions}${j}`:$}function vQ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function Qq($){if(!$||$.length===0)return;let J=$.map(vQ).filter((Q)=>Q.length>0);return J.length>0?new Set(J):void 0}function Zq($,J,Q){if(!Q)return!0;let Z=vQ($),W=vQ(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function a6($,J){let Q=Qq(J);return[...$.getSnapshot("skill").entries()].map(([W,j])=>{let f=j.item;return{id:W,name:f.name.trim(),description:f.description?.trim(),disabled:f.disabled===!0,skill:f}}).filter((W)=>Zq(W.id,W.name,Q))}function Wq($,J){return a6($,J).filter((Q)=>!Q.disabled).map((Q)=>Q.name.trim()).filter((Q)=>Q.length>0).sort((Q,Z)=>Q.localeCompare(Z))}function jq($,J,Q){let Z=vQ(J);if(!Z)return{error:"Missing skill name."};let W=a6($,Q),j=W.find((H)=>H.id===Z);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let f=Z.includes(":")?Z.split(":").at(-1)??Z:Z,X=W.filter(({id:H})=>{if(H===f)return!0;return H.endsWith(`:${f}`)}),Y=X.filter(({skill:H})=>H.disabled!==!0);if(Y.length===1){let{id:H,skill:B}=Y[0];return{id:H,skill:B}}if(Y.length>1)return{error:`Skill "${J}" is ambiguous. Use one of: ${Y.map(({id:H})=>H).join(", ")}`};if(X.length===1){let{skill:H}=X[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${J}" is ambiguous, and all matches are disabled: ${X.map(({id:H})=>H).join(", ")}`};let V=Wq($,Q);return{error:V.length>0?`Skill "${J}" not found. Available skills: ${V.join(", ")}`:"No skills are currently available."}}function qW($,J=Promise.resolve(),Q){let Z=new Set,W=async(j,f)=>{await J;let X=jq($,j,Q);if("error"in X)return X.error;let{id:Y,skill:V}=X;if(Z.has(Y))return`Skill "${V.name}" is already running.`;Z.add(Y);try{let H=f?.trim(),B=H?`
467
+ <command-args>${H}</command-args>`:"",A=V.description?.trim()?`Description: ${V.description.trim()}
460
468
 
461
- `:"";return`<command-name>${A.name}</command-name>${H}
469
+ `:"";return`<command-name>${V.name}</command-name>${B}
462
470
  <command-instructions>
463
- ${B}${A.instructions}
464
- </command-instructions>`}finally{Q.delete(Y)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>u4($,J).map(({skill:W,...j})=>j),enumerable:!0,configurable:!1}),Z}function OV($){let f=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await f,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>m9($.watcher)});if($.registerSkillsTool)Q.registerTool(n$(HW($.watcher,f,$.allowedSkillNames)));for(let Z of c4($.watcher).filter((W)=>W.kind==="skill"&&$.includeSkills||W.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:Z.name,description:Z.description,handler:(W)=>{let j=W.trim();return j?`${Z.instructions}
471
+ ${A}${V.instructions}
472
+ </command-instructions>`}finally{Z.delete(Y)}};return Object.defineProperty(W,"configuredSkills",{get:()=>a6($,Q).map(({skill:j,...f})=>f),enumerable:!0,configurable:!1}),W}function tH($){let J=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Z)=>Boolean(Z))},async setup(Z){if(await J,$.includeRules)Z.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>t9($.watcher)});if($.registerSkillsTool)Z.registerTool(n$(qW($.watcher,J,$.allowedSkillNames)));for(let W of n6($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Z.registerCommand({name:W.name,description:W.description,handler:(j)=>{let f=j.trim();return f?`${W.instructions}
465
473
 
466
- ${j}`:Z.instructions}})}}}class MV{watcher;ready;stopped=!1;constructor($){this.watcher=UV($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([f,J])=>({type:$,id:f,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return c4(this.watcher)}resolveRuntimeSlashCommand($){return zV($,this.watcher)}hasConfiguredSkills($){return u4(this.watcher,$).some((f)=>!f.disabled)}createSkillsExecutor($){return HW(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return OV({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function M$($){return new MV($)}import{readFile as HM,writeFile as BM}from"node:fs/promises";import qV from"yaml";function KM($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J,W=qV.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}function NV($,f){return`---
467
- ${qV.stringify($).trimEnd()}
474
+ ${f}`:W.instructions}})}}}class eH{watcher;ready;stopped=!1;constructor($){this.watcher=nH($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([J,Q])=>({type:$,id:J,filePath:Q.filePath,item:Q.item}))}listRuntimeCommands(){return n6(this.watcher)}resolveRuntimeSlashCommand($){return oH($,this.watcher)}hasConfiguredSkills($){return a6(this.watcher,$).some((J)=>!J.disabled)}createSkillsExecutor($){return qW(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return tH({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function q$($){return new eH($)}import{readFile as fq,writeFile as Xq}from"node:fs/promises";import QB from"yaml";function Yq($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q,j=QB.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}function JB($,J){return`---
475
+ ${QB.stringify($).trimEnd()}
468
476
  ---
469
- ${f}`}function GM($,f){let{data:J,body:Q,hadFrontmatter:Z}=KM($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return Q;return NV(J,Q)}return J.disabled=!0,NV(J,Q)}async function wV({filePath:$,enabled:f}){let J=await HM($,"utf8"),Q=GM(J,f);return await BM($,Q),{filePath:$,enabled:f,disabled:!f}}var rV={};q(rV,{updateMcpServerOAuthState:()=>Df,setMcpServerDisabled:()=>Pf,resolveMcpServerRegistrations:()=>B1,resolveDefaultMcpSettingsPath:()=>T0,registerMcpServersFromSettingsFile:()=>Uf,loadMcpSettingsFile:()=>Ff,listMcpServerOAuthStatuses:()=>l4,hasMcpSettingsFile:()=>p1,getMcpServerOAuthState:()=>Rf,createMcpTools:()=>E2,createDisabledMcpToolPolicy:()=>p4,createDisabledMcpToolPolicies:()=>m5,createDefaultMcpServerClientFactory:()=>S2,authorizeMcpServerOAuth:()=>I5,InMemoryMcpManager:()=>Lf});import{spawn as cM}from"node:child_process";import{StringDecoder as cV}from"node:string_decoder";import{UnauthorizedError as xV}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as uM}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as SM}from"node:crypto";import{UnauthorizedError as EM}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as hM}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as bM}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as kM}from"@modelcontextprotocol/sdk/client/streamableHttp.js";h5();var IM="/mcp/oauth/callback",xM=[1456,1457,1458],gM=300000;function mM($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function vM($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function k5($){let f={};try{f=Rf($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,Q,Z=async(j)=>{let X=y2(j(f))??{};try{f=Df($.serverName,()=>X,{filePath:$.settingsPath})}catch{f=X}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return vM(f.redirectUrl??$.redirectUrl)},state:()=>{return Q=SM(),Q},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((X)=>({...X,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((X)=>({...X,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((X)=>({...X,codeVerifier:j,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!f.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return f.codeVerifier},invalidateCredentials:async(j)=>{await Z((X)=>{if(j==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((X)=>({...X,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((X)=>({...X,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function b5($){let f=$.registration.transport;if(f.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=f.headers?{headers:f.headers}:void 0;if(f.type==="sse")return new bM(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new kM(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function IV($){return new hM({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function I5($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (h5(),kV)),Q=J({filePath:$.filePath}).find((Y)=>Y.name===f);if(!Q)throw Error(`MCP server "${f}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await $1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:xM,callbackPath:$.callbackPath??IM,timeoutMs:$.timeoutMs??gM,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let W=k5({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(Y)=>{await $.openUrl?.(Y)}});await W.resetInteractiveState();let j=IV($),X;try{let Y=b5({registration:Q,oauthProvider:W.provider,fetch:$.fetch});try{return await j.connect(Y),await j.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(A){if(!(A instanceof EM))throw A;if(!W.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let H=await Z.waitForCallback();if(!H)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(H.error)throw Error(`OAuth authorization failed: ${H.error}`);if(!H.code)throw Error("OAuth callback did not include an authorization code.");let B=W.getLastOAuthState();if(!B)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(H.state!==B)throw Error("OAuth authorization failed: state mismatch.");await Y.finishAuth(H.code),X=IV($);let K=b5({registration:Q,oauthProvider:W.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(Y){let A=mM(Y);throw await W.markError(A),Error(A)}finally{await j.close().catch(()=>{return}),await X?.close().catch(()=>{return}),Z.close()}}var dM="2024-11-05",lM=5000,pM=1500,gV="http://127.0.0.1:1456/mcp/oauth/callback";function x5($){return $ instanceof Error?$.message:String($)}function mV($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
477
+ ${J}`}function Vq($,J){let{data:Q,body:Z,hadFrontmatter:W}=Yq($);if(!W&&J)return $;if(J){if(delete Q.disabled,Q.enabled===!1)delete Q.enabled;if(Object.keys(Q).length===0)return Z;return JB(Q,Z)}return Q.disabled=!0,JB(Q,Z)}async function ZB({filePath:$,enabled:J}){let Q=await fq($,"utf8"),Z=Vq(Q,J);return await Xq($,Z),{filePath:$,enabled:J,disabled:!J}}var OB={};w(OB,{updateMcpServerOAuthState:()=>R2,setMcpServerDisabled:()=>D2,resolvePluginMcpServerRegistrations:()=>rQ,resolveMcpServerRegistrations:()=>K1,resolveDefaultMcpSettingsPath:()=>A0,registerMcpServersFromSettingsFile:()=>z2,normalizePluginMcpServerRegistration:()=>yW,loadMcpSettingsFile:()=>F2,listMcpServerOAuthStatuses:()=>o6,hasMcpSettingsFile:()=>r1,getMcpServerOAuthState:()=>U2,createMcpTools:()=>m8,createDisabledMcpToolPolicy:()=>t6,createDisabledMcpToolPolicies:()=>nQ,createDefaultMcpServerClientFactory:()=>x8,authorizeMcpServerOAuth:()=>lQ,InMemoryMcpManager:()=>L2});import{spawn as Iq}from"node:child_process";import{StringDecoder as DB}from"node:string_decoder";import{UnauthorizedError as AB}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as xq}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as Pq}from"node:crypto";import{UnauthorizedError as Nq}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as wq}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Sq}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as Cq}from"@modelcontextprotocol/sdk/client/streamableHttp.js";cQ();var yq="/mcp/oauth/callback",Eq=[1456,1457,1458],bq=300000;function hq($){if($ instanceof Error){let J=$.message.trim();if(J.length>0)return J}return String($)}function kq($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function dQ($){let J={};try{J=U2($.serverName,{filePath:$.settingsPath})??{}}catch{J={}}let Q,Z,W=async(f)=>{let X=I8(f(J))??{};try{J=R2($.serverName,()=>X,{filePath:$.settingsPath})}catch{J=X}};return{provider:{get redirectUrl(){return J.redirectUrl??$.redirectUrl},get clientMetadata(){return kq(J.redirectUrl??$.redirectUrl)},state:()=>{return Z=Pq(),Z},clientInformation:()=>J.clientInformation,saveClientInformation:async(f)=>{await W((X)=>({...X,clientInformation:f,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>J.tokens,saveTokens:async(f)=>{await W((X)=>({...X,tokens:f,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(f)=>{Q=f.toString(),await $.onAuthorizationUrl?.(Q)},saveCodeVerifier:async(f)=>{await W((X)=>({...X,codeVerifier:f,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!J.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return J.codeVerifier},invalidateCredentials:async(f)=>{await W((X)=>{if(f==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...f==="client"?{clientInformation:void 0}:{},...f==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...f==="verifier"?{codeVerifier:void 0}:{},...f==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(f)=>{await W((X)=>({...X,discoveryState:f}))},discoveryState:()=>J.discoveryState},getLastAuthorizationUrl:()=>Q,getLastOAuthState:()=>Z,resetInteractiveState:async()=>{await W((f)=>({...f,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(f)=>{await W((X)=>({...X,lastError:f}))},clearError:async()=>{await W((f)=>({...f,lastError:void 0}))}}}function uQ($){let J=$.registration.transport;if(J.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Q=J.headers?{headers:J.headers}:void 0;if(J.type==="sse")return new Sq(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch});return new Cq(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch})}function BB($){return new wq({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function lQ($){let J=$.serverName.trim();if(!J)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Q}=await Promise.resolve().then(() => (cQ(),HB)),Z=Q({filePath:$.filePath}).find((Y)=>Y.name===J);if(!Z)throw Error(`MCP server "${J}" is not configured.`);if(Z.disabled)throw Error(`MCP server "${J}" is disabled. Enable it before running OAuth.`);if(Z.transport.type==="stdio")throw Error(`MCP server "${J}" uses stdio transport and does not support OAuth browser flow.`);let W=await Q1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:Eq,callbackPath:$.callbackPath??yq,timeoutMs:$.timeoutMs??bq,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!W.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=dQ({settingsPath:$.filePath,serverName:J,redirectUrl:W.callbackUrl,onAuthorizationUrl:async(Y)=>{await $.openUrl?.(Y)}});await j.resetInteractiveState();let f=BB($),X;try{let Y=uQ({registration:Z,oauthProvider:j.provider,fetch:$.fetch});try{return await f.connect(Y),await f.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" is already authorized.`}}catch(V){if(!(V instanceof Nq))throw V;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${J}" did not provide an authorization URL.`);let B=await W.waitForCallback();if(!B)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(B.error)throw Error(`OAuth authorization failed: ${B.error}`);if(!B.code)throw Error("OAuth callback did not include an authorization code.");let A=j.getLastOAuthState();if(!A)throw Error(`MCP server "${J}" did not start an OAuth stateful authorization flow.`);if(B.state!==A)throw Error("OAuth authorization failed: state mismatch.");await Y.finishAuth(B.code),X=BB($);let K=uQ({registration:Z,oauthProvider:j.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" OAuth authorization completed.`}}}catch(Y){let V=hq(Y);throw await j.markError(V),Error(V)}finally{await f.close().catch(()=>{return}),await X?.close().catch(()=>{return}),W.close()}}var gq="2024-11-05",mq=5000,vq=1500,KB="http://127.0.0.1:1456/mcp/oauth/callback";function pQ($){return $ instanceof Error?$.message:String($)}function GB($){let J=Buffer.from(JSON.stringify($),"utf8"),Q=Buffer.from(`Content-Length: ${J.byteLength}\r
470
478
  \r
471
- `,"utf8");return Buffer.concat([J,f])}function vV($){return Buffer.from(`${JSON.stringify($)}
472
- `,"utf8")}class FW{buffer="";decoder=new cV("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
479
+ `,"utf8");return Buffer.concat([Q,J])}function FB($){return Buffer.from(`${JSON.stringify($)}
480
+ `,"utf8")}class SW{buffer="";decoder=new DB("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`\r
473
481
  \r
474
- `);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let W=Number.parseInt(Z[1],10),j=J+4,X=j+W;if(this.buffer.length<X)break;f.push(this.buffer.slice(j,X)),this.buffer=this.buffer.slice(X)}return f}}class PW{buffer="";decoder=new cV("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
475
- `);if(J<0)break;let Q=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),Q.length>0)f.push(Q)}return f}}class uV{registration;process;nextRequestId=1;pending=new Map;framedParser=new FW;newlineParser=new PW;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:dM,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},pM),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){f=Q instanceof Error?Q:Error(String(Q))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new FW,this.newlineParser=new PW,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=cM(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=Q,Q.stdout.on("data",(Z)=>this.handleStdout(Z)),Q.stderr.on("data",(Z)=>{if(this.process!==Q)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(Z)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${x5(Z)}`))}),Q.once("exit",(Z,W)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${W??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let Q=JSON.parse(J);if(typeof Q.id!=="number")continue;let Z=this.pending.get(Q.id);if(!Z)continue;if(this.pending.delete(Q.id),clearTimeout(Z.timeout),Q.error){let W=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;Z.reject(Error(W));continue}Z.resolve(Q.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${x5($)}.${J}`)),f.kill()}async request($,f,J=lM){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,W={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((X,Y)=>{let A=setTimeout(()=>{this.pending.delete(Z),Y(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:X,reject:Y,timeout:A})});try{Q.stdin.write(this.protocolMode==="framed"?mV(W):vV(W))}catch(X){let Y=this.pending.get(Z);if(Y)clearTimeout(Y.timeout),this.pending.delete(Z);throw X}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?mV(Q):vV(Q))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class dV{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=k5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??gV});this.authContext=$;try{let f=new uM({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=b5({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof xV?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):x5(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??k5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??gV}),J=$ instanceof xV?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):x5($);throw await f.markError(J),Error(J)}}function S2($={}){return(f)=>f.transport.type==="stdio"?new uV(f):new dV(f,$)}h5();function d0(){return Date.now()}function rM($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class Lf{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:d0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=d0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=d0(),f)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&d0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),Q=await(await this.ensureConnectedClient(f)).listTools(),Z=rM(Q);return f.toolCache=Z,f.toolCacheUpdatedAt=d0(),f.updatedAt=d0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=d0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=d0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=d0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=d0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=d0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=d0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,W),await J.catch(()=>{return});try{return await f()}finally{if(Q?.(),this.operationLocks.get($)===W)this.operationLocks.delete($)}}}import{createHash as iM}from"node:crypto";var lV=128,nM=/[^a-zA-Z0-9_-]+/g,pV=8,aM=1,tM="mcp_tool";function sM($){return iM("sha1").update($).digest("hex").slice(0,pV)}function oM($){return $.replace(nM,"_")}var g5=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,Q=oM(J);if(Q===J&&J.length<=lV)return J;let Z=sM(J),W=lV-aM-pV;return`${Q.slice(0,W)||tM}_${Z}`};function p4($){return{[($.nameTransform??g5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function m5($){let f={};for(let J of $.toolNames)Object.assign(f,p4({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as eM}from"@cline/shared";function $T($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function E2($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??g5;return f.map((Q)=>{let Z=J({serverName:$.serverName,toolName:Q.name});return eM({name:Z,description:$T($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(W,j)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}j1();var nV={};q(nV,{listPluginToolsWithDiagnostics:()=>v5,listPluginTools:()=>r4});import{stat as fT}from"node:fs/promises";j1();var JT=32,h2=new Map;function QT($,f){if(!h2.has($)&&h2.size>=JT){let J=h2.keys().next().value;if(J)h2.delete(J)}h2.set($,f)}async function ZT($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let Q=await fT(J);return`${J}:${Q.mtimeMs}:${Q.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function iV($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function WT($){return $.sort((f,J)=>{let Q=f.name.localeCompare(J.name);if(Q!==0)return Q;return f.path.localeCompare(J.path)})}function jT($,f){if(!$.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(Q,{workspaceInfo:f}),J}async function v5($){let f=Xf({workspacePath:$.workspacePath,cwd:$.cwd}),J=W1($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let Q=await ZT({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=h2.get(Q);if(Z)return{tools:iV(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let W=[],j=[],X=[],Y;try{Y=await l6({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...Y.failures],X=[...Y.warnings];for(let H of Y.extensions??[]){let B=H.__clinePluginPath;if(!B)continue;for(let K of jT(H,{rootPath:$.workspacePath}))W.push({name:K.name,pluginName:H.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(H){j=f.map((B)=>({pluginPath:B,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await Y?.shutdown().catch(()=>{})}let A=WT(W);return QT(Q,{tools:A,failures:j,warnings:X}),{tools:iV(A,J),failures:j,warnings:X}}async function r4($){return(await v5($)).tools}function u5($,f){if(!f)return"global";let J=YT(f,$);return!J.startsWith("..")&&!XT(J)?"workspace":"global"}function i4($){return[...$].sort((f,J)=>{let Q=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return Q(f.source)-Q(J.source);return f.name.localeCompare(J.name)})}function sV($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function tV($,f){if($.userInstructionService)return await f($.userInstructionService);let J=sV($);if(!J)return await f(void 0);let Q=$.cwd?.trim()||J,Z=M$({skills:{workspacePath:J,includePluginSkills:!0,cwd:Q},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await f(Z)}finally{Z.stop()}}function AT($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let Q=J.find((Z)=>Z.id===f.id);if(Q)return Q}for(let Q of J)if(Q.filePath===f.path||Q.item.name===f.name||Q.id===f.name)return Q;return}class T${async list($={}){return await tV($,async(f)=>{let J=sV($),Q=[],Z=[],W=[],j=[],X=[];if(f){for(let A of f.listRecords("workflow")){let V=A.item;Q.push({id:A.id,name:V.name,path:A.filePath,enabled:V.disabled!==!0,kind:"workflow",source:u5(A.filePath,J),description:V.instructions,toggleable:!1})}for(let A of f.listRecords("rule")){let V=A.item;Z.push({id:A.id,name:V.name,path:A.filePath,enabled:V.disabled!==!0,kind:"rule",source:u5(A.filePath,J),description:V.instructions,toggleable:!1})}for(let A of f.listRecords("skill")){let V=A.item;W.push({id:A.id,name:V.name,path:A.filePath,enabled:V.disabled!==!0,kind:"skill",source:u5(A.filePath,J),description:V.description,toggleable:!0})}}if(J)try{for(let A of await r4({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${A.pluginName}:${A.name}:${A.path}`,name:A.name,path:A.path,enabled:A.enabled,kind:"tool",source:A.source,description:A.description,toggleable:!0})}catch{}let Y=T0();if(p1({filePath:Y}))try{for(let A of B1({filePath:Y}))X.push({id:A.name,name:A.name,path:Y,enabled:A.disabled!==!0,kind:"mcp",source:u5(Y,J),description:A.transport.type,toggleable:!0})}catch{}return{workflows:i4(Q.filter((A)=>c5(A.path))),rules:i4(Z.filter((A)=>c5(A.path))),skills:i4(W.filter((A)=>c5(A.path))),tools:i4(j),mcp:i4(X.filter((A)=>c5(A.path)))}})}async toggle($){if($.type==="skills")return await tV($,async(f)=>{let J=AT(f,$),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??aV($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=$.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??aV($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await wV({filePath:Q,enabled:W}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)aJ($.name);else e3($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||T0(),Q=$.enabled;if(Q===void 0){let Z=B1({filePath:J}).find((W)=>W.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);Q=Z.disabled===!0}return Pf({filePath:J,name:f,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function _f(){return new T$}function eV($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await _f().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await _f().toggle(f)}}}function $H($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}function fH($){let f=$.config;return"providerId"in f?{...$,config:{...f,...VT($.localRuntime)},localRuntime:$.localRuntime}:$}function RW($,f={}){let J=U8($.config),Q=L0(f.defaultCapabilities,$.capabilities),Z=HT(J.localRuntime,$.localRuntime),W=f.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...$,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function VT($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=$;return W}function HT(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}_0();function JH($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:g.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??R0.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 n4($){return!!$&&typeof $==="object"&&!Array.isArray($)}function DW($){let f=$?.trim();return f?f:void 0}function BT($,f){let J=$?.trim();if(!J)return f;let Q=Date.parse(J);if(!Number.isFinite(Q))return f;return new Date(Q).toISOString()}function QH($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function ZH($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function KT($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function GT($,f){let J=$.eventId.trim(),Q=$.eventType.trim(),Z=$.source.trim(),W=DW($.subject),j=DW($.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:BT($.occurredAt,f),workspaceRoot:DW($.workspaceRoot),payload:n4($.payload)?$.payload:void 0,attributes:n4($.attributes)?$.attributes:void 0,dedupeKey:j}}function UW($,f){if(!f)return;let J=f.split("."),Q=$;for(let Z of J){if(!n4(Q))return;Q=Q[Z]}return Q}function FT($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=UW(J,f);if(Q!==void 0)return Q;if($.attributes){let Z=UW($.attributes,f);if(Z!==void 0)return Z}if($.payload)return UW($.payload,f);return}function d5($,f){if(Array.isArray(f))return f.some((J)=>d5($,J));if(Array.isArray($))return $.some((J)=>d5(J,f));if(n4(f)){if(!n4($))return!1;return Object.entries(f).every(([J,Q])=>d5($[J],Q))}return Object.is($,f)}function PT($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,Q])=>d5(FT($,J),Q))}class LW{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=GT($,f),Q=this.store.insertEventLog(J,{receivedAtIso:f});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),W=[],j=[],X=[];for(let V of Z){if(!PT(J,V.filters)){W.push({specId:V.specId,externalId:V.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(V);let H=this.materializeForSpec(V,J,Q.record.receivedAt);if(H.run)X.push(H.run);else W.push({specId:V.specId,externalId:V.externalId,reason:H.reason,dedupeKey:J.dedupeKey})}let Y=j.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:Y,matchedSpecCount:j.length,queuedRunCount:X.length,suppressedCount:W.filter((V)=>V.reason!=="filter_mismatch").length});let A=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:Y,matchedSpecCount:j.length,queuedRunCount:X.length}),{event:A??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:X,suppressions:W}}catch(Z){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let Q=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let Y=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(Y){let A=KT(Y.scheduledFor,QH(J,Z)),V=this.store.updateQueuedEventRunForDebounce({runId:Y.runId,triggerEventId:f.eventId,scheduledFor:A});if(V)return{run:V,reason:"dedupe_window"}}}let W=$.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:ZH(J,W)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:ZH(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?QH(J,Z):J}),reason:"dedupe_window"}}}import{existsSync as ET,readdirSync as hT,readFileSync as bT,statSync as kT}from"node:fs";import{relative as IT}from"node:path";import{resolveCronSpecsDir as xT}from"@cline/shared/storage";import{createHash as RT}from"node:crypto";import DT from"yaml";function UT($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function LT($){let f=$.replace(/\r\n/g,`
476
- `);if(!f.startsWith(`---
477
- `))return{frontmatter:void 0,body:$};let J=f.slice(4),Q=J.indexOf(`
478
- ---`);if(Q===-1)return{frontmatter:void 0,body:$};let Z=J.slice(0,Q),W=J.slice(Q+4);if(W.startsWith(`
479
- `))W=W.slice(1);return{frontmatter:Z,body:W}}function l0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function _T($){if(!Array.isArray($))return;let f=$.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return f.length>0?f:void 0}function OW($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function zT($){let f=OW($);if(!f)return;let J=l0(f.providerId),Q=l0(f.modelId);if(J===void 0&&Q===void 0)return;return{providerId:J,modelId:Q}}function OT($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function jH($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let Q=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var MT=new Set(o1);function TT($){let f=jH($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!MT.has(Q));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var NT=new Set(["rules","skills","plugins"]);function qT($){let f=jH($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!NT.has(Q));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function _W($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function zW($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function MW($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>MW(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[Q])=>J<Q?-1:J>Q?1:0),`{${f.map(([J,Q])=>`${JSON.stringify(J)}:${MW(Q)}`).join(",")}}`}function XH($,f){let J=RT("sha256");return J.update(MW($)),J.update(`
480
- `),J.update(f),J.digest("hex")}function wT($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var CT=["schedule","timezone"],yT=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],ST=["cwd"];function WH($,f,J,Q,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:XH(Q,J),error:Z}}function K1($,f,J,Q,Z,W){return{externalId:$,relativePath:f,triggerKind:J,body:Q,contentHash:Z,error:W}}function YH($){let f=$.relativePath.replace(/\\/g,"/"),J=UT(f),{frontmatter:Q,body:Z}=LT($.raw),W={};if(Q!==void 0&&Q.trim().length>0)try{let D=DT.parse(Q);if(D&&typeof D==="object"&&!Array.isArray(D))W=D;else if(D!==null&&D!==void 0)return WH(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(D){return WH(f,J,Z,{},D instanceof Error?`failed to parse frontmatter: ${D.message}`:"failed to parse frontmatter")}let j=XH(W,Z),X=l0(W.id),Y=X??f;if(J!=="schedule"){for(let D of CT)if(W[D]!==void 0)return K1(Y,f,J,Z,j,`field "${D}" is only allowed on *.cron.md specs`)}for(let D of ST)if(W[D]!==void 0)return K1(Y,f,J,Z,j,`field "${D}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let D of yT)if(W[D]!==void 0)return K1(Y,f,J,Z,j,`field "${D}" is only allowed on .event.md specs`)}let A=l0(W.prompt),V=Z.trim(),H=A??(V.length>0?V:void 0);if(!H)return K1(Y,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=l0(W.workspaceRoot);if(!B)return K1(Y,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=TT(W.tools),G=qT(W.extensions)}catch(D){return K1(Y,f,J,Z,j,D instanceof Error?D.message:String(D))}let R=OT(W.mode);if(W.mode!==void 0&&R===void 0)return K1(Y,f,J,Z,j,"mode must be one of: act, plan, yolo");let P={id:X,title:l0(W.title)??X??wT(f),prompt:H,workspaceRoot:B,mode:R??"yolo",systemPrompt:l0(W.systemPrompt),modelSelection:zT(W.modelSelection),maxIterations:_W(W.maxIterations),timeoutSeconds:_W(W.timeoutSeconds),tools:K,notesDirectory:l0(W.notesDirectory),extensions:G,source:l0(W.source)??"user",tags:_T(W.tags),enabled:typeof W.enabled==="boolean"?W.enabled:!0,metadata:OW(W.metadata)},F;if(J==="schedule"){let D=l0(W.schedule);if(!D)return K1(Y,f,J,Z,j,"schedule is required for *.cron.md specs");let z=l0(W.timezone);try{h3(D,z)}catch(L){return K1(Y,f,J,Z,j,L instanceof Error?L.message:String(L))}F={...P,triggerKind:"schedule",schedule:D,timezone:z}}else if(J==="event"){let D=l0(W.event);if(!D)return K1(Y,f,J,Z,j,"event is required for .event.md specs");F={...P,triggerKind:"event",event:D,filters:OW(W.filters),debounceSeconds:zW(W.debounceSeconds),dedupeWindowSeconds:zW(W.dedupeWindowSeconds),cooldownSeconds:zW(W.cooldownSeconds),maxParallel:_W(W.maxParallel)}}else F={...P,triggerKind:"one_off"};return{externalId:Y,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:F}}function gT($,f){return IT($,f).replace(/\\/g,"/")}function mT($){if(!ET($))return[];let f=[],J=[$];while(J.length>0){let Q=J.pop();if(!Q)continue;let Z;try{Z=hT(Q,{withFileTypes:!0})}catch{continue}for(let W of Z){let j=`${Q}/${W.name}`;if(W.isDirectory()){if(W.name==="reports")continue;J.push(j);continue}if(!W.isFile())continue;if(!W.name.endsWith(".md"))continue;f.push(j)}}return f}class TW{store;cronDir;constructor($){this.store=$.store,this.cronDir=xT($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=mT(this.cronDir),J=new Set;for(let Z of f){let W=gT(this.cronDir,Z);J.add(W),$.scanned+=1;let j=await this.reconcileFile(W,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of Q)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),Q,Z;try{Q=bT(f,"utf8"),Z=kT(f).mtimeMs}catch{return}let j=YH({relativePath:$,raw:Q}),X=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==X.record.scheduleExpr||J.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),Q=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=k$($.scheduleExpr,Q,$.timezone),W=new Date(Z).toISOString();if($.nextRunAt!==W)this.store.updateSpecNextRunAt($.specId,W)}catch{}}}import{existsSync as vT,mkdirSync as cT,watch as uT}from"node:fs";import{relative as dT,resolve as lT}from"node:path";var pT=250;class NW{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??pT),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{cT($,{recursive:!0}),this.watcher=uT($,{recursive:!0},(f,J)=>{if(!J)return;let Q=String(J).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=lT(this.reconciler.getCronDir(),$);if(!vT(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=dT(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}class a4{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new Y8({dbPath:$.dbPath});let f=$.specs;this.reconciler=new TW({store:this.store,specs:f}),this.materializer=new f8({store:this.store}),this.eventIngress=new LW({store:this.store,logger:$.logger}),this.runner=new Z8({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new NW({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:J});else Q.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var RH={};q(RH,{manifestToSessionRecord:()=>p5,listSessionHistoryFromBackend:()=>yW,listSessionHistory:()=>r5,hydrateSessionHistory:()=>PH});import{readdir as aT,readFile as KH}from"node:fs/promises";import{join as GH}from"node:path";import{formatDisplayUserInput as tT,normalizeUserInput as sT}from"@cline/shared";import{resolveSessionDataDir as FH}from"@cline/shared/storage";import{existsSync as rT}from"node:fs";import{readFile as iT}from"node:fs/promises";import{formatDisplayUserInput as AH}from"@cline/shared";class t4{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function N$($){let f=$?.trim();if(!f||!rT(f))return[];try{let J=(await iT(f,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return VH(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return VH(Z)}return[]}catch{return[]}}function nT($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:AH($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:AH(f.text)}})}}function VH($){return $.map(nT)}function qW($){return $?{...$}:void 0}async function HH($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let Q=await f.upsertSubagentSessionFromHook($);if(!Q)return;await f.appendSubagentHookAudit(Q,$),await f.applySubagentStatus(Q,$)}function s4($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function p0($){let f=s4($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function l5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function oT($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function CW($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function eT($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function $N($){return $.isSubagent!==!0&&!s4($.parentSessionId)}function fN($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let Q of f){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function p5($){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 JN($){let f=CW($);if(f===0)return[];let J=FH(),Z=(await aT(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:fN(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let Y=GH(J,X,`${X}.json`),A=await KH(Y,"utf8").catch(()=>{return});if(!A)return;let V;try{V=JSON.parse(A)}catch{return}let H=y0.safeParse(V);if(!H.success)return;return p5(H.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function QN($,f,J){let Q=CW(f);if(Q===0)return await $.listSessions(0),[];let Z=J.includeSubagents?Q:eT(Q),W=await $.listSessions(Z);return(J.includeSubagents?W:W.filter($N)).slice(0,Q)}function ZN($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)f.push(Z)}return f.join(`
481
- `).trim()}function BH($){return $.replace(/\s+/g," ").trim()}function WN($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function jN($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let Q=BH(ZN(J.content));if(!Q)continue;let Z=f==="user"?BH(tT(Q)):Q,W=sT(Z.split(`
482
- `)[0]??Z);return WN(W,50)}return}function XN($){let f=0;for(let J of $)f+=l5(J.metrics?.cost)??0;return f}function YN($){let f,J;for(let Q=$.length-1;Q>=0;Q-=1){let Z=$[Q];if(!f)f=p0(Z.modelInfo?.provider);if(!J)J=p0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function AN($){return p0($?.provider)??p0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function VN($){return p0($?.model)??p0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function wW($,f){let J=oT($.metadata),Q=s4(f?.title)??s4(J?.title),Z=l5(f?.totalCost)??l5(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:p0(f?.provider)??p0($.provider)??AN(J)??"",model:p0(f?.model)??p0($.model)??VN(J)??"",metadata:W}}function HN($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function BN($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!HN(J)}async function KN($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let Q=await $.readSessionMessages(J.sessionId);return BN(J,Q)?{...J,status:"idle"}:J}))}async function PH($,f){return await Promise.all(f.map(async(J)=>{let Q=wW(J),Z=Boolean(s4(Q.metadata?.title)),W=Boolean(p0(Q.provider)),j=Boolean(p0(Q.model)),X=l5(Q.metadata?.totalCost),Y=X!==void 0&&X>0;if(Z&&W&&j&&Y)return Q;let A=await $.readSessionMessages(J.sessionId);if(A.length===0)return Q;let V=YN(A),H=XN(A);return wW(J,{title:Z?void 0:jN(A),provider:W?void 0:V.provider,model:j?void 0:V.model,totalCost:Y||H<=0?void 0:H})}))}async function r5($,f={}){let J=CW(f.limit),Q=f.includeSubagents===!0,Z=await QN($,J,{includeSubagents:Q}),W=f.includeManifestFallback===!0&&Z.length<J?await JN(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let A of[...Z,...W]){if(j.has(A.sessionId))continue;j.set(A.sessionId,A)}let X=W.length===0?Z:Array.from(j.values()).sort((A,V)=>V.startedAt.localeCompare(A.startedAt)).slice(0,J),Y=await KN($,X);if(f.hydrate===!1)return Y.map((A)=>wW(A));return await PH($,Y)}async function GN($){let f=$.trim();if(!f)return;let J=GH(FH(),f,`${f}.json`),Q=await KH(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=y0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function yW($,f={}){let J=new Map;return await r5({listSessions:async(Z)=>{let W=await $.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map(X4)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await GN(Z);return await N$(W)}},f)}var ZB={};q(ZB,{resolveSessionBackend:()=>tW,createRuntimeHost:()=>u2});import{captureSdkError as JB}from"@cline/shared";var yH={};q(yH,{HubRuntimeHost:()=>r1});import{captureSdkError as UH,createSessionId as LH,HUB_CHECKPOINT_CAPABILITY as DN,HUB_COMPACTION_CAPABILITY as UN,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as LN,HUB_HOOK_CAPABILITY_PREFIX as _N,HUB_MISTAKE_LIMIT_CAPABILITY as zN,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ON,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as MN,isHubToolExecutorName as TN}from"@cline/shared";var DH={};q(DH,{createCoreSessionSnapshot:()=>G1,coreSessionSnapshotToRecord:()=>i5});function FN($){return $?JSON.parse(JSON.stringify($)):void 0}function PN($){return $?JSON.parse(JSON.stringify($)):void 0}function RN($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",Y=Number(j.createdAt),A=Number(j.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(A))return[];return[{ref:X,createdAt:Y,runCount:A,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=$?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function G1($){let{session:f}=$,J=FN(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:PN($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=RN(J);return Q?{checkpoint:Q}:{}})()}}function i5($){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 b2($){if(!$)return;return JSON.parse(JSON.stringify($))}var NN=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function _H($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function zH($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function OH($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function zf($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function MH($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(TN)){let W=f.toolExecutors?.[Z];if(typeof W!=="function")continue;zf(J,{kind:"toolExecutor",executor:Z,capabilityName:`${ON}${Z}`},async({payload:j,abortSignal:X})=>{let Y=Array.isArray(j.args)?[...j.args]:[],A={...OH(j.context),signal:X};return{result:await W(...Y,A)}})}for(let Z of $?.extraTools??[])zf(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:b2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:b2(Z.lifecycle)}:{},capabilityName:`${LN}${Z.name}`},async({payload:W,abortSignal:j,progress:X})=>{let Y={...OH(W.context),signal:j};return{result:await Z.execute(W.input,{...Y,emitUpdate:(V)=>{X({update:V})}})}});let Q=$?.hooks;if(Q)for(let Z of NN){let W=Q[Z];if(typeof W!=="function")continue;zf(J,{kind:"hook",name:Z,capabilityName:`${_N}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;zf(J,{kind:"compaction",capabilityName:UN,config:_H($.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;zf(J,{kind:"checkpoint",capabilityName:DN,config:_H($.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;zf(J,{kind:"mistakeLimit",capabilityName:zN},async({payload:W})=>({result:await Z(W.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;zf(J,{kind:"userInstructionService",capabilityName:MN},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function wH($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return}function qN($){return wH($)??"Capability request was cancelled."}function wN($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function CN($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function yN($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,Q=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function TH($){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 SW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function q$($,f){return SW($?.[f])??0}function SN($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:q$(f,"inputTokens"),outputTokens:q$(f,"outputTokens"),cacheReadTokens:q$(f,"cacheReadTokens"),cacheWriteTokens:q$(f,"cacheWriteTokens"),cost:SW(f?.totalCost),totalInputTokens:q$(J,"inputTokens"),totalOutputTokens:q$(J,"outputTokens"),totalCacheReadTokens:q$(J,"cacheReadTokens"),totalCacheWriteTokens:q$(J,"cacheWriteTokens"),totalCost:SW(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function EN($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,Q=CN(J)?J:J==="failed"?"error":"completed",Z=yN($?.usage??f?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function n5($,f){return $.error?.message??`hub command failed: ${f}`}function o4($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function CH($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:R0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:o4($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:o4($.status)==="completed"?0:o4($.status)==="failed"?1:void 0,status:o4($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function w$($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function hN($){let f=w$($?.snapshot);if(f)return i5(f);let J=$?.session;return J?CH(J):void 0}function NH($,f,J){let Q=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return y0.parse({version:1,session_id:$,source:f.source??R0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:o4(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:Q,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function qH($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class r1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new t4;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=L0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new e0({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!X6($,"session.create"))return!1;let f=await Y6({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=MH($.localRuntime,f),Q=$.config.sessionId?.trim()||LH(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:b2({...$.config,sessionId:Q}),metadata:{...$.sessionMetadata??{},source:$.source??R0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:b2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Q,f,J.handlers);let W;try{W=await Z()}catch(A){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(Q,f,J.handlers);try{W=await Z()}catch(V){throw this.cleanupPlannedSession(Q),V}}else throw A}let j=w$(W.payload?.snapshot),X=W.payload?.session,Y=(j?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(Y!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(Y,f,J.handlers);return{sessionId:Y,manifest:j?qH(j,$):NH(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?MH(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||LH():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:b2({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??R0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:b2(Q.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let Y=w$(X.payload?.snapshot),A=X.payload?.session,V=(Y?.sessionId??A?.sessionId)?.trim();if(J&&!V){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(V&&j&&V!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(V&&Z)this.sessionCapabilities.set(V,Z);if(V&&W.handlers.size>0)this.sessionClientContributionHandlers.set(V,W.handlers);if(V)this.ensureSessionSubscription(V);let H=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:Y?qH(Y,Q??{}):NH(V,Q??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:H,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=w$(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let Q=f.payload?.session,Z=TH(Q?.usage),W=TH(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:wH(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(b1(J))return;throw J}return hN(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let W=w$(Z);return W?[i5(W)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(CH)}async listSettings($){let f=await this.client.command("settings.list",zH($));if(!f.ok)throw Error(n5(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",zH($));if(!f.ok)throw Error(n5(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw UH(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(n5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(n5(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return L0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:EN($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,$)});return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=w$($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=SN($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=w$($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=w$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:Q}}),J?.interactive===!0&&J0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{UH(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Q,X);let Y=(A)=>{this.client.command("capability.progress",{requestId:Q,payload:A},f).catch((V)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",V,$)})};try{let A=await W({payload:j,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:A},f)}catch(A){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:A instanceof Error?A.message:String(A)},f)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(qN($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",W=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!Z||!W)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=wN($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:W,toolInput:X});let Y=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:W,input:X,policy:j})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:Y.approved,reason:Y.reason},f).catch(()=>{})}}var SH={};q(SH,{RemoteRuntimeHost:()=>k2});class k2 extends r1{constructor($){super({url:Z$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var EH={};q(EH,{SqliteSessionStore:()=>P1});import{existsSync as bN,mkdirSync as kN}from"node:fs";import{join as IN}from"node:path";import{asBool as e4,asOptionalString as F1,asString as i1,ensureSessionSchema as xN,loadSqliteDb as gN,nowIso as a5,toBoolInt as $J}from"@cline/shared/db";import{resolveDbDataDir as mN}from"@cline/shared/storage";class P1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??mN()}init(){this.getRawDb()}ensureSessionsDir(){if(!bN(this.sessionsDirPath))kN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return IN(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=gN(this.sessionDbPath());return xN($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=a5();this.run(`INSERT OR REPLACE INTO sessions (
482
+ `);if(Q<0)break;let W=this.buffer.slice(0,Q).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!W)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(W[1],10),f=Q+4,X=f+j;if(this.buffer.length<X)break;J.push(this.buffer.slice(f,X)),this.buffer=this.buffer.slice(X)}return J}}class CW{buffer="";decoder=new DB("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`
483
+ `);if(Q<0)break;let Z=this.buffer.slice(0,Q).trim();if(this.buffer=this.buffer.slice(Q+1),Z.length>0)J.push(Z)}return J}}class UB{registration;process;nextRequestId=1;pending=new Map;framedParser=new SW;newlineParser=new CW;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],J;for(let Q of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Q);try{await this.request("initialize",{protocolVersion:gq,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},vq),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Q;return}catch(Z){J=Z instanceof Error?Z:Error(String(Z))}}throw J??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((J)=>typeof J?.name==="string"&&typeof J.inputSchema==="object"&&J.inputSchema!==null).map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let J=this.registration.transport;if(J.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${J.type}`);this.framedParser=new SW,this.newlineParser=new CW,this.stderrBuffer="",this.protocolMode=$;let Q=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Z=Iq(J.command,J.args??[],{cwd:J.cwd,env:{...process.env,...J.env??{}},stdio:["pipe","pipe","pipe"],...Q});this.process=Z,Z.stdout.on("data",(W)=>this.handleStdout(W)),Z.stderr.on("data",(W)=>{if(this.process!==Z)return;if(this.stderrBuffer+=W.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Z.once("error",(W)=>{if(this.process!==Z)return;this.failAllPending(Error(`MCP process error: ${pQ(W)}`))}),Z.once("exit",(W,j)=>{if(this.process!==Z)return;this.connected=!1,this.process=void 0;let f=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${W??"null"}, signal=${j??"null"}).${f}`))})}handleStdout($){try{let J=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Q of J){let Z=JSON.parse(Q);if(typeof Z.id!=="number")continue;let W=this.pending.get(Z.id);if(!W)continue;if(this.pending.delete(Z.id),clearTimeout(W.timeout),Z.error){let j=Z.error.message||`MCP request failed with code ${Z.error.code??"unknown"}`;W.reject(Error(j));continue}W.resolve(Z.result)}}catch(J){this.handleProtocolFailure(J)}}handleProtocolFailure($){let J=this.process;if(!J)return;this.connected=!1,this.process=void 0;let Q=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${pQ($)}.${Q}`)),J.kill()}async request($,J,Q=mq){let Z=this.process;if(!Z?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let W=this.nextRequestId++,j={jsonrpc:"2.0",id:W,method:$,...J?{params:J}:{}},f=new Promise((X,Y)=>{let V=setTimeout(()=>{this.pending.delete(W),Y(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Q);this.pending.set(W,{resolve:X,reject:Y,timeout:V})});try{Z.stdin.write(this.protocolMode==="framed"?GB(j):FB(j))}catch(X){let Y=this.pending.get(W);if(Y)clearTimeout(Y.timeout),this.pending.delete(W);throw X}return f}notify($,J){let Q=this.process;if(!Q?.stdin.writable)return;let Z={jsonrpc:"2.0",method:$,...J?{params:J}:{}};Q.stdin.write(this.protocolMode==="framed"?GB(Z):FB(Z))}failAllPending($){for(let[J,Q]of this.pending)clearTimeout(Q.timeout),this.pending.delete(J),Q.reject($)}}class RB{registration;options;client;authContext;constructor($,J){this.registration=$;this.options=J}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=dQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??KB});this.authContext=$;try{let J=new xq({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Q=uQ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await J.connect(Q),await $.clearError(),this.client=J}catch(J){let Q=J instanceof AB?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):pQ(J);throw await $.markError(Q),Error(Q)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema&&typeof Q.inputSchema==="object"&&!Array.isArray(Q.inputSchema)?Q.inputSchema:{}}))}catch(J){return await this.handleOperationError(J)}}async callTool($){let J=await this.ensureConnectedClient();try{return await J.callTool({name:$.name,arguments:$.arguments??{}})}catch(Q){return await this.handleOperationError(Q)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let J=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${J} Run authorizeMcpServerOAuth for this server.`;return`${J} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let J=this.authContext??dQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??KB}),Q=$ instanceof AB?this.formatUnauthorizedMessage(J.getLastAuthorizationUrl()):pQ($);throw await J.markError(Q),Error(Q)}}function x8($={}){return(J)=>J.transport.type==="stdio"?new UB(J):new RB(J,$)}cQ();function l0(){return Date.now()}function cq($){return $.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}class L2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let J=this.servers.get($.name);if(!J){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:l0()});return}let Q=JSON.stringify(J.registration.transport)!==JSON.stringify($.transport);if(J.registration={...$},J.updatedAt=l0(),Q)await this.disconnectState(J),J.client=void 0,J.toolCache=void 0,J.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.connectState(J)})}async disconnectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J)})}async setServerDisabled($,J){await this.runExclusive($,async()=>{let Q=this.requireServer($);if(Q.registration={...Q.registration,disabled:J},Q.updatedAt=l0(),J)await this.disconnectState(Q)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,J)=>$.name.localeCompare(J.name))}async listTools($){let J=this.requireServer($),Q=J.toolCacheUpdatedAt??0;if(J.toolCache&&l0()-Q<=this.toolsCacheTtlMs)return J.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let J=this.requireServer($),Z=await(await this.ensureConnectedClient(J)).listTools(),W=cq(Z);return J.toolCache=W,J.toolCacheUpdatedAt=l0(),J.updatedAt=l0(),W})}async callTool($){return this.runExclusive($.serverName,async()=>{let J=this.requireServer($.serverName),Q=await this.ensureConnectedClient(J);return J.updatedAt=l0(),Q.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let J of $)await this.unregisterServer(J)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=l0();try{let J=$.client??await this.clientFactory($.registration);await J.connect(),$.client=J,$.status="connected",$.lastError=void 0,$.updatedAt=l0()}catch(J){throw $.status="disconnected",$.lastError=J instanceof Error?J.message:String(J),$.updatedAt=l0(),J}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=l0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=l0()}}requireServer($){let J=this.servers.get($);if(!J)throw Error(`Unknown MCP server: ${$}`);return J}async runExclusive($,J){let Q=this.operationLocks.get($)??Promise.resolve(),Z,W=new Promise((f)=>{Z=f}),j=Q.catch(()=>{return}).then(()=>W);this.operationLocks.set($,j),await Q.catch(()=>{return});try{return await J()}finally{if(Z?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function g8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function zB($){return g8($)&&Object.values($).every((J)=>typeof J==="string")}function uq($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function dq($){if(!g8($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function lq($){let J=$.env?Object.entries($.env):[];if(J.length===0)return{ok:!0};let Q={};for(let[Z,W]of J){if(typeof W==="string"){Q[Z]=W;continue}let j=W.fromEnv?.trim()||Z,f=process.env[j];if(typeof f==="string"&&f.length>0){Q[Z]=f;continue}if(typeof W.value==="string"){Q[Z]=W.value;continue}if(W.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Q).length>0?Q:void 0}}function yW($){if(!g8($))return{name:"",loadError:"invalid MCP server registration"};let J=typeof $.name==="string"?$.name.trim():"";if(!J)return{name:J,loadError:"empty MCP server name"};let Q=$.env,Z=Q===void 0?void 0:Q;if(Z!==void 0){if(!g8(Z))return{name:J,loadError:"invalid env"};for(let[Y,V]of Object.entries(Z))if(typeof V!=="string"&&!dq(V))return{name:J,loadError:`invalid env "${Y}"`}}let W=$.transport;if(!g8(W))return{name:J,loadError:"invalid MCP transport"};let j=W.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:J,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Z!==void 0)return{name:J,loadError:"top-level env is only supported for stdio MCP transports"};let f=g8($.metadata)?$.metadata:void 0;if(j==="stdio"){let Y=W.command;if(typeof Y!=="string"||!Y.trim())return{name:J,loadError:"stdio MCP transport requires command"};let V=W.args;if(V!==void 0&&!uq(V))return{name:J,loadError:"stdio MCP transport args must be strings"};let H=W.cwd;if(H!==void 0&&typeof H!=="string")return{name:J,loadError:"stdio MCP transport cwd must be a string"};let B=W.env;if(B!==void 0&&!zB(B))return{name:J,loadError:"stdio MCP transport env must be strings"};let A=lq({name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:B},env:Z,metadata:f});if(!A.ok)return{name:J,loadError:A.reason};let K=B||A.env?{...B??{},...A.env??{}}:void 0;return{name:J,registration:{name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:K},metadata:f}}}if(typeof W.url!=="string"||!W.url.trim())return{name:J,loadError:`${j} MCP transport requires url`};let X=W.headers;if(X!==void 0&&!zB(X))return{name:J,loadError:`${j} MCP transport headers must be strings`};return{name:J,registration:{name:J,transport:j==="sse"?{type:"sse",url:W.url,headers:X}:{type:"streamableHttp",url:W.url,headers:X},metadata:f}}}function rQ($){let J=new Map;return $.map(({server:Q,owner:Z,ownerLabel:W})=>{let j=yW(Q);if(!j.registration)return{owner:Z,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let f=J.get(j.registration.name);if(J.has(j.registration.name)){let X=f?` already registered by ${f}`:"";return{owner:Z,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${X}`}}return J.set(j.registration.name,W),{owner:Z,name:j.registration.name,registration:j.registration}})}import{createHash as pq}from"node:crypto";var LB=128,rq=/[^a-zA-Z0-9_-]+/g,_B=8,iq=1,nq="mcp_tool";function aq($){return pq("sha1").update($).digest("hex").slice(0,_B)}function sq($){return $.replace(rq,"_")}var iQ=({serverName:$,toolName:J})=>{let Q=`${$}__${J}`,Z=sq(Q);if(Z===Q&&Q.length<=LB)return Q;let W=aq(Q),j=LB-iq-_B;return`${Z.slice(0,j)||nq}_${W}`};function t6($){return{[($.nameTransform??iQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function nQ($){let J={};for(let Q of $.toolNames)Object.assign(J,t6({serverName:$.serverName,toolName:Q,nameTransform:$.nameTransform}));return J}import{createTool as oq}from"@cline/shared";function tq($,J){let Q=J.description?.trim();if(Q)return Q;return`Execute MCP tool "${J.name}" from server "${$}".`}async function m8($){let J=await $.provider.listTools($.serverName),Q=$.nameTransform??iQ;return J.map((Z)=>{let W=Q({serverName:$.serverName,toolName:Z.name});return oq({name:W,description:tq($.serverName,Z),inputSchema:Z.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,f)=>$.provider.callTool({serverName:$.serverName,toolName:Z.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:f})})})}t0();var qB={};w(qB,{listPluginToolsWithDiagnostics:()=>aQ,listPluginTools:()=>e6});import{stat as eq}from"node:fs/promises";import{isAbsolute as $P,relative as JP,resolve as TB}from"node:path";t0();function QP($,J){let Q=JP(TB($),TB(J));return Q===""||!Q.startsWith("..")&&!$P(Q)}var ZP=32,v8=new Map;function WP($,J){if(!v8.has($)&&v8.size>=ZP){let Q=v8.keys().next().value;if(Q)v8.delete(Q)}v8.set($,J)}async function jP($){let J=await Promise.all($.pluginPaths.map(async(Q)=>{try{let Z=await eq(Q);return`${Q}:${Z.mtimeMs}:${Z.size}`}catch{return`${Q}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:J})}function MB($,J){return $.map((Q)=>({...Q,enabled:!J.has(Q.name)}))}function fP($){return $.sort((J,Q)=>{let Z=J.name.localeCompare(Q.name);if(Z!==0)return Z;return J.path.localeCompare(Q.path)})}async function XP($,J){if(!$.setup)return{tools:[]};let Q=[],Z={registerTool:(W)=>Q.push(W),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(W)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Z,{workspaceInfo:J}),{tools:Q}}async function aQ($){let J=X2({workspacePath:$.workspacePath,cwd:$.cwd}),Q=X1($.disabledToolNames);if(J.length===0)return{tools:[],failures:[],warnings:[]};let Z=await jP({pluginPaths:J,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),W=v8.get(Z);if(W)return{tools:MB(W.tools,Q),failures:W.failures,warnings:W.warnings};let j=[],f=[],X=[],Y;try{Y=await O8({pluginPaths:J,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),f=[...Y.failures],X=[...Y.warnings];for(let H of Y.extensions??[]){let B=H.__clinePluginPath;if(!B)continue;let A=QP($.workspacePath,B)?"workspace-plugin":"global-plugin",K;try{K=await XP(H,{rootPath:$.workspacePath})}catch(G){f.push({pluginPath:B,pluginName:H.name,phase:"setup",message:G instanceof Error?G.message:String(G),stack:G instanceof Error?G.stack:void 0});continue}for(let G of K.tools)j.push({name:G.name,pluginName:H.name,path:B,source:A,description:G.description?.trim()||void 0})}}catch(H){f=J.map((B)=>({pluginPath:B,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await Y?.shutdown().catch(()=>{})}let V=fP(j);return WP(Z,{tools:V,failures:f,warnings:X}),{tools:MB(V,Q),failures:f,warnings:X}}async function e6($){return(await aQ($)).tools}function oQ($,J){if(!J)return"global";let Q=VP(J,$);return!Q.startsWith("..")&&!YP(Q)?"workspace":"global"}function $J($){return[...$].sort((J,Q)=>{let Z=(W)=>{switch(W){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(J.source!==Q.source)return Z(J.source)-Z(Q.source);return J.name.localeCompare(Q.name)})}function wB($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function NB($,J){if($.userInstructionService)return await J($.userInstructionService);let Q=wB($);if(!Q)return await J(void 0);let Z=$.cwd?.trim()||Q,W=q$({skills:{workspacePath:Q,includePluginSkills:!0,cwd:Z},rules:{workspacePath:Q},workflows:{workspacePath:Q}});try{return await W.start(),await J(W)}finally{W.stop()}}function HP($,J){if(!$)return;let Q=$.listRecords("skill");if(J.id){let Z=Q.find((W)=>W.id===J.id);if(Z)return Z}for(let Z of Q)if(Z.filePath===J.path||Z.item.name===J.name||Z.id===J.name)return Z;return}class P${async list($={}){return await NB($,async(J)=>{let Q=wB($),Z=[],W=[],j=[],f=[],X=[];if(J){for(let V of J.listRecords("workflow")){let H=V.item;Z.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"workflow",source:oQ(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("rule")){let H=V.item;W.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"rule",source:oQ(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("skill")){let H=V.item;j.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"skill",source:oQ(V.filePath,Q),description:H.description,toggleable:!0})}}if(Q)try{for(let V of await e6({workspacePath:Q,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))f.push({id:`${V.pluginName}:${V.name}:${V.path}`,name:V.name,path:V.path,enabled:V.enabled,kind:"tool",source:V.source,description:V.description,toggleable:!0})}catch{}let Y=A0();if(r1({filePath:Y}))try{for(let V of K1({filePath:Y}))X.push({id:V.name,name:V.name,path:Y,enabled:V.disabled!==!0,kind:"mcp",source:oQ(Y,Q),description:V.transport.type,toggleable:!0})}catch{}return{workflows:$J(Z.filter((V)=>sQ(V.path))),rules:$J(W.filter((V)=>sQ(V.path))),skills:$J(j.filter((V)=>sQ(V.path))),tools:$J(f),mcp:$J(X.filter((V)=>sQ(V.path)))}})}async toggle($){if($.type==="skills")return await NB($,async(J)=>{let Q=HP(J,$),Z=Q?.filePath;if(!Z)throw Error(`Unable to resolve skill setting '${$.id??$.name??PB($.path??"")}'.`);let W=Q?.item&&"disabled"in Q.item?Q.item.disabled!==!0:void 0,j=$.enabled??(W!==void 0?!W:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??PB($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await ZB({filePath:Z,enabled:j}),await J?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:J}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)Z5($.name);else zf($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let J=$.name?.trim()||$.id?.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=$.path?.trim()||A0(),Z=$.enabled;if(Z===void 0){let W=K1({filePath:Q}).find((j)=>j.name===J);if(!W)throw Error(`Unknown MCP server: ${J}`);Z=W.disabled===!0}return D2({filePath:Q,name:J,disabled:!Z}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function _2(){return new P$}function CB($){return{async list(J){let Q=$;if(Q.listSettings)return await Q.listSettings(J);return await _2().list(J)},async toggle(J){let Q=$;if(Q.toggleSetting)return await Q.toggleSetting(J);return await _2().toggle(J)}}}function yB($){function J(){let Q=$.pendingPrompts;if(!Q)throw Error("Pending prompt service is not available.");return Q}return{list(Q){return J().list(Q)},update(Q){return J().update(Q)},delete(Q){return J().delete(Q)}}}function EB($){let J=$.config;return"providerId"in J?{...$,config:{...J,...BP($.localRuntime)},localRuntime:$.localRuntime}:$}function EW($,J={}){let Q=q4($.config),Z=_0(J.defaultCapabilities,$.capabilities),W=AP(Q.localRuntime,$.localRuntime),j=J.withExtensionContext?.(W?.extensionContext);if(j)W={...W??{},extensionContext:j};return{...$,...Q,...W?{localRuntime:W}:{},...Z?{capabilities:Z}:{}}}function BP($){if(!$)return{};let{modelCatalogDefaults:J,userInstructionService:Q,configExtensions:Z,onTeamRestored:W,...j}=$;return j}function AP(...$){let J={};for(let Q of $)if(Q)Object.assign(J,Q);return Object.keys(J).length>0?J:void 0}O0();function bB($){let J=$.input.config.telemetry??$.telemetry;if(!J)return;J.capture({event:g.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??R0.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 JJ($){return!!$&&typeof $==="object"&&!Array.isArray($)}function bW($){let J=$?.trim();return J?J:void 0}function KP($,J){let Q=$?.trim();if(!Q)return J;let Z=Date.parse(Q);if(!Number.isFinite(Z))return J;return new Date(Z).toISOString()}function hB($,J){return new Date(new Date($).getTime()+Math.max(0,Math.floor(J))*1000).toISOString()}function kB($,J){return new Date(new Date($).getTime()-Math.max(0,Math.floor(J))*1000).toISOString()}function GP($,J){if(!$)return J;return new Date($).getTime()>=new Date(J).getTime()?$:J}function FP($,J){let Q=$.eventId.trim(),Z=$.eventType.trim(),W=$.source.trim(),j=bW($.subject),f=bW($.dedupeKey)??`${Z}:${W}:${j??Q}`;return{eventId:Q,eventType:Z,source:W,subject:j,occurredAt:KP($.occurredAt,J),workspaceRoot:bW($.workspaceRoot),payload:JJ($.payload)?$.payload:void 0,attributes:JJ($.attributes)?$.attributes:void 0,dedupeKey:f}}function hW($,J){if(!J)return;let Q=J.split("."),Z=$;for(let W of Q){if(!JJ(Z))return;Z=Z[W]}return Z}function DP($,J){if($.attributes&&Object.hasOwn($.attributes,J))return $.attributes[J];if($.payload&&Object.hasOwn($.payload,J))return $.payload[J];let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Z=hW(Q,J);if(Z!==void 0)return Z;if($.attributes){let W=hW($.attributes,J);if(W!==void 0)return W}if($.payload)return hW($.payload,J);return}function tQ($,J){if(Array.isArray(J))return J.some((Q)=>tQ($,Q));if(Array.isArray($))return $.some((Q)=>tQ(Q,J));if(JJ(J)){if(!JJ($))return!1;return Object.entries(J).every(([Q,Z])=>tQ($[Q],Z))}return Object.is($,J)}function UP($,J){if(!J||Object.keys(J).length===0)return!0;return Object.entries(J).every(([Q,Z])=>tQ(DP($,Q),Z))}class kW{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let J=new Date(this.nowFn()).toISOString(),Q=FP($,J),Z=this.store.insertEventLog(Q,{receivedAtIso:J});if(!Z.created)return this.logger?.debug("cron.event.duplicate",{eventId:Z.record.eventId,eventType:Z.record.eventType,source:Z.record.source}),{event:Z.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Z.record.dedupeKey}]};try{let W=this.store.listEventSpecsForType(Q.eventType),j=[],f=[],X=[];for(let H of W){if(!UP(Q,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Q.dedupeKey});continue}f.push(H);let B=this.materializeForSpec(H,Q,Z.record.receivedAt);if(B.run)X.push(B.run);else j.push({specId:H.specId,externalId:H.externalId,reason:B.reason,dedupeKey:Q.dedupeKey})}let Y=f.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Z.record.eventId,{status:Y,matchedSpecCount:f.length,queuedRunCount:X.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let V=this.store.getEventLog(Z.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Z.record.eventId,eventType:Z.record.eventType,status:Y,matchedSpecCount:f.length,queuedRunCount:X.length}),{event:V??Z.record,duplicate:!1,matchedSpecs:f,queuedRuns:X,suppressions:j}}catch(W){if(this.store.updateEventLogProcessing(Z.record.eventId,{status:"failed",error:W instanceof Error?W.message:String(W)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Z.record.eventId,eventType:Z.record.eventType,error:W});throw W}}materializeForSpec($,J,Q){let Z=J.dedupeKey??J.eventId,W=$.debounceSeconds??0;if(W>0){let Y=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Z});if(Y){let V=GP(Y.scheduledFor,hB(Q,W)),H=this.store.updateQueuedEventRunForDebounce({runId:Y.runId,triggerEventId:J.eventId,scheduledFor:V});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Z,sinceIso:kB(Q,j)}))return{reason:"dedupe_window"};let f=$.cooldownSeconds??0;if(f>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:kB(Q,f)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:J.eventId,scheduledFor:W>0?hB(Q,W):Q}),reason:"dedupe_window"}}}import{existsSync as bP,readdirSync as hP,readFileSync as kP,statSync as IP}from"node:fs";import{relative as xP}from"node:path";import{resolveCronSpecsDir as gP}from"@cline/shared/storage";import{createHash as RP}from"node:crypto";import zP from"yaml";function LP($){let J=$.replace(/\\/g,"/");if(J.startsWith("events/")&&J.endsWith(".event.md"))return"event";if(J.endsWith(".cron.md"))return"schedule";return"one_off"}function _P($){let J=$.replace(/\r\n/g,`
484
+ `);if(!J.startsWith(`---
485
+ `))return{frontmatter:void 0,body:$};let Q=J.slice(4),Z=Q.indexOf(`
486
+ ---`);if(Z===-1)return{frontmatter:void 0,body:$};let W=Q.slice(0,Z),j=Q.slice(Z+4);if(j.startsWith(`
487
+ `))j=j.slice(1);return{frontmatter:W,body:j}}function p0($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function OP($){if(!Array.isArray($))return;let J=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);return J.length>0?J:void 0}function gW($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function TP($){let J=gW($);if(!J)return;let Q=p0(J.providerId),Z=p0(J.modelId);if(Q===void 0&&Z===void 0)return;return{providerId:Q,modelId:Z}}function MP($){if(typeof $!=="string")return;let J=$.trim().toLowerCase();if(J==="act"||J==="plan"||J==="yolo")return J;return}function xB($,J={}){let Q=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Q)return;let Z=[...new Set(Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0))];if(Array.isArray($)&&J.preserveEmptyArray)return Z;return Z.length>0?Z:void 0}var qP=new Set(e1);function PP($){let J=xB($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!qP.has(Z));if(Q.length>0)throw Error(`unknown tool(s): ${Q.join(", ")}`);return J}var NP=new Set(["rules","skills","plugins"]);function wP($){let J=xB($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!NP.has(Z));if(Q.length>0)throw Error(`unknown extension(s): ${Q.join(", ")}`);return J}function IW($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function xW($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function mW($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Q)=>mW(Q)).join(",")}]`;let J=Object.entries($).filter(([,Q])=>Q!==void 0);return J.sort(([Q],[Z])=>Q<Z?-1:Q>Z?1:0),`{${J.map(([Q,Z])=>`${JSON.stringify(Q)}:${mW(Z)}`).join(",")}}`}function gB($,J){let Q=RP("sha256");return Q.update(mW($)),Q.update(`
488
+ `),Q.update(J),Q.digest("hex")}function SP($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var CP=["schedule","timezone"],yP=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],EP=["cwd"];function IB($,J,Q,Z,W){return{externalId:$,relativePath:$,triggerKind:J,body:Q,contentHash:gB(Z,Q),error:W}}function G1($,J,Q,Z,W,j){return{externalId:$,relativePath:J,triggerKind:Q,body:Z,contentHash:W,error:j}}function mB($){let J=$.relativePath.replace(/\\/g,"/"),Q=LP(J),{frontmatter:Z,body:W}=_P($.raw),j={};if(Z!==void 0&&Z.trim().length>0)try{let F=zP.parse(Z);if(F&&typeof F==="object"&&!Array.isArray(F))j=F;else if(F!==null&&F!==void 0)return IB(J,Q,W,{},"frontmatter must be a YAML mapping")}catch(F){return IB(J,Q,W,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let f=gB(j,W),X=p0(j.id),Y=X??J;if(Q!=="schedule"){for(let F of CP)if(j[F]!==void 0)return G1(Y,J,Q,W,f,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of EP)if(j[F]!==void 0)return G1(Y,J,Q,W,f,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Q!=="event"){for(let F of yP)if(j[F]!==void 0)return G1(Y,J,Q,W,f,`field "${F}" is only allowed on .event.md specs`)}let V=p0(j.prompt),H=W.trim(),B=V??(H.length>0?H:void 0);if(!B)return G1(Y,J,Q,W,f,"prompt is required (frontmatter `prompt` or markdown body)");let A=p0(j.workspaceRoot);if(!A)return G1(Y,J,Q,W,f,"workspaceRoot is required");let K,G;try{K=PP(j.tools),G=wP(j.extensions)}catch(F){return G1(Y,J,Q,W,f,F instanceof Error?F.message:String(F))}let R=MP(j.mode);if(j.mode!==void 0&&R===void 0)return G1(Y,J,Q,W,f,"mode must be one of: act, plan, yolo");let D={id:X,title:p0(j.title)??X??SP(J),prompt:B,workspaceRoot:A,mode:R??"yolo",systemPrompt:p0(j.systemPrompt),modelSelection:TP(j.modelSelection),maxIterations:IW(j.maxIterations),timeoutSeconds:IW(j.timeoutSeconds),tools:K,notesDirectory:p0(j.notesDirectory),extensions:G,source:p0(j.source)??"user",tags:OP(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:gW(j.metadata)},U;if(Q==="schedule"){let F=p0(j.schedule);if(!F)return G1(Y,J,Q,W,f,"schedule is required for *.cron.md specs");let O=p0(j.timezone);try{ej(F,O)}catch(L){return G1(Y,J,Q,W,f,L instanceof Error?L.message:String(L))}U={...D,triggerKind:"schedule",schedule:F,timezone:O}}else if(Q==="event"){let F=p0(j.event);if(!F)return G1(Y,J,Q,W,f,"event is required for .event.md specs");U={...D,triggerKind:"event",event:F,filters:gW(j.filters),debounceSeconds:xW(j.debounceSeconds),dedupeWindowSeconds:xW(j.dedupeWindowSeconds),cooldownSeconds:xW(j.cooldownSeconds),maxParallel:IW(j.maxParallel)}}else U={...D,triggerKind:"one_off"};return{externalId:Y,relativePath:J,triggerKind:Q,body:W,contentHash:f,spec:U}}function mP($,J){return xP($,J).replace(/\\/g,"/")}function vP($){if(!bP($))return[];let J=[],Q=[$];while(Q.length>0){let Z=Q.pop();if(!Z)continue;let W;try{W=hP(Z,{withFileTypes:!0})}catch{continue}for(let j of W){let f=`${Z}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Q.push(f);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;J.push(f)}}return J}class vW{store;cronDir;constructor($){this.store=$.store,this.cronDir=gP($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},J=vP(this.cronDir),Q=new Set;for(let W of J){let j=mP(this.cronDir,W);Q.add(j),$.scanned+=1;let f=await this.reconcileFile(j,W);if(f){if($.changes.push(f),$.upserted+=1,f.parse.error)$.invalidParses+=1}}let Z=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let W of Z)if(!Q.has(W.sourcePath))this.handleFileDeleted(W),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,J){let Q=this.store.getSpecBySourcePath($),Z,W;try{Z=kP(J,"utf8"),W=IP(J).mtimeMs}catch{return}let f=mB({relativePath:$,raw:Z}),X=this.store.upsertSpec({externalId:f.externalId,sourcePath:$,triggerKind:f.triggerKind,sourceMtimeMs:W,sourceHash:f.contentHash,parseStatus:f.error?"invalid":"valid",parseError:f.error,spec:f.spec});if(!f.error&&f.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!Q||Q.removed||!Q.enabled||Q.scheduleExpr!==X.record.scheduleExpr||Q.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:f}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let J of $)this.applyScheduleNextRunAt(J,{forceReset:!1})}applyScheduleNextRunAt($,J){if(!$.scheduleExpr)return;if(!J.forceReset&&$.nextRunAt)return;try{let Q=Date.now(),Z=$.lastRunAt?Math.max(Q,new Date($.lastRunAt).getTime()):Q,W=I$($.scheduleExpr,Z,$.timezone),j=new Date(W).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as cP,mkdirSync as uP,watch as dP}from"node:fs";import{relative as lP,resolve as pP}from"node:path";var rP=250;class cW{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??rP),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{uP($,{recursive:!0}),this.watcher=dP($,{recursive:!0},(J,Q)=>{if(!Q)return;let Z=String(Q).replace(/\\/g,"/");if(!Z.endsWith(".md"))return;if(Z.startsWith("reports/"))return;this.scheduleReconcile(Z)}),this.watcher.on("error",this.onError)}catch(J){this.onError(J)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let J=this.pending.get($);if(J)clearTimeout(J);let Q=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Q)}async reconcileNow($){try{let J=pP(this.reconciler.getCronDir(),$);if(!cP(J)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Q=lP(this.reconciler.getCronDir(),J).replace(/\\/g,"/");await this.reconciler.reconcileFile(Q,J),await this.onReconciled()}catch(J){this.onError(J)}}}class QJ{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new F4({dbPath:$.dbPath});let J=$.specs;this.reconciler=new vW({store:this.store,specs:J}),this.materializer=new Y4({store:this.store}),this.eventIngress=new kW({store:this.store,logger:$.logger}),this.runner=new B4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:J,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new cW({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let Z=$.logger;if(Z)if(Z.error)Z.error("cron.watcher.failed",{error:Q});else Z.log("cron.watcher.failed",{error:Q})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var nB={};w(nB,{manifestToSessionRecord:()=>$9,listSessionHistoryFromBackend:()=>pW,listSessionHistory:()=>J9,hydrateSessionHistory:()=>iB});import{readdir as sP,readFile as lB}from"node:fs/promises";import{join as pB}from"node:path";import{formatDisplayUserInput as oP,normalizeUserInput as tP}from"@cline/shared";import{resolveSessionDataDir as rB}from"@cline/shared/storage";import{existsSync as iP}from"node:fs";import{readFile as nP}from"node:fs/promises";import{formatDisplayUserInput as vB}from"@cline/shared";class ZJ{listeners=new Set;subscribe($,J){let Q={listener:$,sessionId:J?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let J=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J)continue;Q.listener($)}}get size(){return this.listeners.size}}async function N$($){let J=$?.trim();if(!J||!iP(J))return[];try{let Q=(await nP(J,"utf8")).trim();if(!Q)return[];let Z=JSON.parse(Q);if(Array.isArray(Z))return cB(Z);if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let W=Z.messages;if(Array.isArray(W))return cB(W)}return[]}catch{return[]}}function aP($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:vB($.content)};return{...$,content:$.content.map((J)=>{if(J.type!=="text"||typeof J.text!=="string")return J;return{...J,text:vB(J.text)}})}}function cB($){return $.map(aP)}function uW($){return $?{...$}:void 0}async function uB($,J){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await J.queueSpawnRequest($);let Z=await J.upsertSubagentSessionFromHook($);if(!Z)return;await J.appendSubagentHookAudit(Z,$),await J.applySubagentStatus(Z,$)}function WJ($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function r0($){let J=WJ($);if(!J)return;return J.toLowerCase()==="unknown"?void 0:J}function eQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function eP($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function lW($){let J=$??200;return Number.isFinite(J)?Math.max(0,Math.floor(J)):200}function $N($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function JN($){return $.isSubagent!==!0&&!WJ($.parentSessionId)}function QN($){let J=$.match(/\d{13,}/g);if(!J||J.length===0)return 0;let Q=0;for(let Z of J){let W=Number.parseInt(Z,10);if(Number.isFinite(W)&&W>Q)Q=W}return Q}function $9($){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 ZN($){let J=lW($);if(J===0)return[];let Q=rB(),W=(await sP(Q,{withFileTypes:!0}).catch(()=>[])).filter((f)=>f.isDirectory()).map((f)=>({entry:f,recency:QN(f.name.trim())})).sort((f,X)=>X.recency-f.recency||X.entry.name.localeCompare(f.entry.name));return(await Promise.all(W.map(async({entry:f})=>{let X=f.name.trim();if(!X)return;let Y=pB(Q,X,`${X}.json`),V=await lB(Y,"utf8").catch(()=>{return});if(!V)return;let H;try{H=JSON.parse(V)}catch{return}let B=y0.safeParse(H);if(!B.success)return;return $9(B.data)}))).filter((f)=>Boolean(f)).sort((f,X)=>X.startedAt.localeCompare(f.startedAt)).slice(0,J)}async function WN($,J,Q){let Z=lW(J);if(Z===0)return await $.listSessions(0),[];let W=Q.includeSubagents?Z:$N(Z),j=await $.listSessions(W);return(Q.includeSubagents?j:j.filter(JN)).slice(0,Z)}function jN($){if(typeof $==="string")return $.trim();let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q;if(Z.type!=="text")continue;let W=Z.text?.trim();if(W)J.push(W)}return J.join(`
489
+ `).trim()}function dB($){return $.replace(/\s+/g," ").trim()}function fN($,J){if($.length<=J)return $;return`${$.slice(0,Math.max(0,J-3)).trimEnd()}...`}function XN($){for(let J of["user","assistant"])for(let Q of $){if(Q.role!==J)continue;let Z=dB(jN(Q.content));if(!Z)continue;let W=J==="user"?dB(oP(Z)):Z,j=tP(W.split(`
490
+ `)[0]??W);return fN(j,50)}return}function YN($){let J=0;for(let Q of $)J+=eQ(Q.metrics?.cost)??0;return J}function VN($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=r0(W.modelInfo?.provider);if(!Q)Q=r0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function HN($){return r0($?.provider)??r0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function BN($){return r0($?.model)??r0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function dW($,J){let Q=eP($.metadata),Z=WJ(J?.title)??WJ(Q?.title),W=eQ(J?.totalCost)??eQ(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:r0(J?.provider)??r0($.provider)??HN(Q)??"",model:r0(J?.model)??r0($.model)??BN(Q)??"",metadata:j}}function AN($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function KN($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!AN(Q)}async function GN($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return KN(Q,Z)?{...Q,status:"idle"}:Q}))}async function iB($,J){return await Promise.all(J.map(async(Q)=>{let Z=dW(Q),W=Boolean(WJ(Z.metadata?.title)),j=Boolean(r0(Z.provider)),f=Boolean(r0(Z.model)),X=eQ(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=VN(V),B=YN(V);return dW(Q,{title:W?void 0:XN(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||B<=0?void 0:B})}))}async function J9($,J={}){let Q=lW(J.limit),Z=J.includeSubagents===!0,W=await WN($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await ZN(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await GN($,X);if(J.hydrate===!1)return Y.map((V)=>dW(V));return await iB($,Y)}async function FN($){let J=$.trim();if(!J)return;let Q=pB(rB(),J,`${J}.json`),Z=await lB(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=y0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function pW($,J={}){let Q=new Map;return await J9({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map(F6)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await FN(W);return await N$(j)}},J)}var kA={};w(kA,{resolveSessionBackend:()=>B3,createRuntimeHost:()=>a8});import{captureSdkError as bA}from"@cline/shared";var XA={};w(XA,{HubRuntimeHost:()=>i1});import{captureSdkError as sB,createSessionId as oB,HUB_CHECKPOINT_CAPABILITY as zN,HUB_COMPACTION_CAPABILITY as LN,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as _N,HUB_HOOK_CAPABILITY_PREFIX as ON,HUB_MISTAKE_LIMIT_CAPABILITY as TN,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as MN,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as qN,isHubToolExecutorName as PN}from"@cline/shared";var aB={};w(aB,{createCoreSessionSnapshot:()=>F1,coreSessionSnapshotToRecord:()=>Q9});function DN($){return $?JSON.parse(JSON.stringify($)):void 0}function UN($){return $?JSON.parse(JSON.stringify($)):void 0}function RN($){let J=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Z=(Array.isArray(J?.history)?J.history:[]).filter((f)=>!!f&&typeof f==="object"&&!Array.isArray(f)).flatMap((f)=>{let X=typeof f.ref==="string"?f.ref.trim():"",Y=Number(f.createdAt),V=Number(f.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...f.kind==="stash"||f.kind==="commit"?{kind:f.kind}:{}}]}),W=Z.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Z.length===0)return;return{...j?{enabled:j}:{},...W?{latest:W}:{},history:Z}}function F1($){let{session:J}=$,Q=DN(J.metadata);return{version:1,sessionId:J.sessionId,source:J.source,status:J.status,createdAt:J.startedAt,updatedAt:J.updatedAt,endedAt:J.endedAt??null,exitCode:J.exitCode??null,interactive:J.interactive,workspace:{cwd:J.cwd,root:J.workspaceRoot},model:{providerId:J.provider,modelId:J.model},capabilities:{enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams},lineage:{...J.parentSessionId?{parentSessionId:J.parentSessionId}:{},...J.parentAgentId?{parentAgentId:J.parentAgentId}:{},...J.agentId?{agentId:J.agentId}:{},...J.conversationId?{conversationId:J.conversationId}:{},isSubagent:J.isSubagent},...J.teamName?{team:{name:J.teamName}}:{},...J.prompt?{prompt:J.prompt}:{},...Q?{metadata:Q}:{},...J.messagesPath?{artifacts:{messagesPath:J.messagesPath}}:{},...$.messages?{messages:UN($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Z=RN(Q);return Z?{checkpoint:Z}:{}})()}}function Q9($){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 c8($){if(!$)return;return JSON.parse(JSON.stringify($))}var NN=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function tB($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function eB($){if(!$)return;let{userInstructionService:J,...Q}=$;return JSON.parse(JSON.stringify(Q))}function $A($){let J=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof J.agentId==="string"?J.agentId:"",conversationId:typeof J.conversationId==="string"?J.conversationId:"",iteration:typeof J.iteration==="number"?J.iteration:0,metadata:J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}}function O2($,J,Q){$.manifest.push(J),$.handlers.set(J.capabilityName,Q)}function JA($,J){let Q={manifest:[],handlers:new Map};for(let W of Object.keys(J.toolExecutors??{}).filter(PN)){let j=J.toolExecutors?.[W];if(typeof j!=="function")continue;O2(Q,{kind:"toolExecutor",executor:W,capabilityName:`${MN}${W}`},async({payload:f,abortSignal:X})=>{let Y=Array.isArray(f.args)?[...f.args]:[],V={...$A(f.context),signal:X};return{result:await j(...Y,V)}})}for(let W of $?.extraTools??[])O2(Q,{kind:"tool",name:W.name,description:W.description,inputSchema:c8(W.inputSchema)??{},...W.lifecycle?{lifecycle:c8(W.lifecycle)}:{},capabilityName:`${_N}${W.name}`},async({payload:j,abortSignal:f,progress:X})=>{let Y={...$A(j.context),signal:f};return{result:await W.execute(j.input,{...Y,emitUpdate:(H)=>{X({update:H})}})}});let Z=$?.hooks;if(Z)for(let W of NN){let j=Z[W];if(typeof j!=="function")continue;O2(Q,{kind:"hook",name:W,capabilityName:`${ON}${W}`},async({payload:f})=>({control:await j(f.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;O2(Q,{kind:"compaction",capabilityName:LN,config:tB($.compaction)},async({payload:j})=>({result:await W(j.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;O2(Q,{kind:"checkpoint",capabilityName:zN,config:tB($.checkpoint)},async({payload:j})=>({result:await W(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;O2(Q,{kind:"mistakeLimit",capabilityName:TN},async({payload:j})=>({result:await W(j.context)}))}if($?.userInstructionService){let W=$.userInstructionService;O2(Q,{kind:"userInstructionService",capabilityName:qN},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Q}function jA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let J=$.message;if(typeof J==="string"&&J.trim())return J.trim()}return}function wN($){return jA($)??"Capability request was cancelled."}function SN($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function CN($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function yN($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=typeof J.inputTokens==="number"?J.inputTokens:void 0,Z=typeof J.outputTokens==="number"?J.outputTokens:void 0;if(Q===void 0||Z===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:typeof J.cacheReadTokens==="number"?J.cacheReadTokens:0,cacheWriteTokens:typeof J.cacheWriteTokens==="number"?J.cacheWriteTokens:0,totalCost:typeof J.totalCost==="number"?J.totalCost:0}}function QA($){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 rW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function w$($,J){return rW($?.[J])??0}function EN($){let J=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Z=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=Z?.teamRole==="teammate"||Z?.teamRole==="lead"?Z.teamRole:void 0;return{event:{type:"usage",agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,inputTokens:w$(J,"inputTokens"),outputTokens:w$(J,"outputTokens"),cacheReadTokens:w$(J,"cacheReadTokens"),cacheWriteTokens:w$(J,"cacheWriteTokens"),cost:rW(J?.totalCost),totalInputTokens:w$(Q,"inputTokens"),totalOutputTokens:w$(Q,"outputTokens"),totalCacheReadTokens:w$(Q,"cacheReadTokens"),totalCacheWriteTokens:w$(Q,"cacheWriteTokens"),totalCost:rW(Q?.totalCost)},teamAgentId:typeof Z?.teamAgentId==="string"?Z.teamAgentId:void 0,teamRole:W}}function bN($){let J=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??J?.finishReason,Z=CN(Q)?Q:Q==="failed"?"error":"completed",W=yN($?.usage??J?.usage);return{type:"done",reason:Z,text:typeof $?.text==="string"?$.text:typeof J?.text==="string"?J.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof J?.iterations==="number"?J.iterations:0,usage:W}}function Z9($,J){return $.error?.message??`hub command failed: ${J}`}function jJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function fA($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof J?.agentId==="string"?J.agentId:void 0),parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,isSubagent:typeof J?.isSubagent==="boolean"?J.isSubagent:!1,source:typeof J?.source==="string"?J.source:R0.CORE,pid:typeof J?.pid==="number"?J.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:jJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:jJ($.status)==="completed"?0:jJ($.status)==="failed"?1:void 0,status:jJ($.status),interactive:J?.interactive===!0,provider:typeof J?.provider==="string"?J.provider:"hub",model:typeof J?.model==="string"?J.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof J?.teamName==="string"?J.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??J?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??J?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??J?.enableTeams===!0,prompt:typeof J?.prompt==="string"?J.prompt:void 0,metadata:J,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,hookPath:typeof J?.hookPath==="string"?J.hookPath:void 0}}function S$($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;return J.version===1&&typeof J.sessionId==="string"?JSON.parse(JSON.stringify(J)):void 0}function hN($){let J=S$($?.snapshot);if(J)return Q9(J);let Q=$?.session;return Q?fA(Q):void 0}function ZA($,J,Q){let Z=Q?.workspaceRoot?.trim()||J.config.workspaceRoot||J.config.cwd;return y0.parse({version:1,session_id:$,source:J.source??R0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:jJ(Q?.status),interactive:J.interactive===!0,provider:J.config.providerId,model:J.config.modelId,cwd:Q?.cwd?.trim()||J.config.cwd,workspace_root:Z,team_name:J.config.teamName,enable_tools:J.config.enableTools,enable_spawn:J.config.enableSpawnAgent,enable_teams:J.config.enableAgentTeams,prompt:J.prompt?.trim()||void 0,metadata:J.sessionMetadata&&Object.keys(J.sessionMetadata).length>0?J.sessionMetadata:void 0})}function WA($,J){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??J.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class i1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new ZJ;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,J){this.clientContext=J,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd},this.defaultCapabilities=_0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new J1({...this.clientOptions,url:$})}async replaceClient($){let J=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(J.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!F5($,"session.create"))return!1;let J=await D5({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!J)return!1;return await this.replaceClient(J),!0}registerPlannedSession($,J,Q){if(this.sessionCapabilities.set($,J),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let J=this.resolveCapabilities($),Q=JA($.localRuntime,J),Z=$.config.sessionId?.trim()||oB(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:c8({...$.config,sessionId:Z}),metadata:{...$.sessionMetadata??{},source:$.source??R0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:c8($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Z,J,Q.handlers);let j;try{j=await W()}catch(V){if(this.cleanupPlannedSession(Z),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Z,J,Q.handlers);try{j=await W()}catch(H){throw this.cleanupPlannedSession(Z),H}}else throw V}let f=S$(j.payload?.snapshot),X=j.payload?.session,Y=(f?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Z),Error("Hub runtime did not return a session id.");if(Y!==Z)this.cleanupPlannedSession(Z),this.registerPlannedSession(Y,J,Q.handlers);return{sessionId:Y,manifest:f?WA(f,$):ZA(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let Z=$.start,W=Z?this.resolveCapabilities(Z):void 0,j=Z?JA(Z.localRuntime,W??{}):{manifest:[],handlers:new Map},f=Z?Z.config.sessionId?.trim()||oB():void 0;if(f&&W)this.sessionCapabilities.set(f,W);if(f&&j.handlers.size>0)this.sessionClientContributionHandlers.set(f,j.handlers),this.ensureSessionSubscription(f);let X;try{X=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.config.workspaceRoot?.trim()||Z.config.cwd,cwd:Z.config.cwd??$.cwd,sessionConfig:c8({...Z.config,sessionId:f}),metadata:{...Z.sessionMetadata??{},source:Z.source??R0.CORE,provider:Z.config.providerId,model:Z.config.modelId,enableTools:Z.config.enableTools,enableSpawn:Z.config.enableSpawnAgent,enableTeams:Z.config.enableAgentTeams,teamName:Z.config.teamName,prompt:Z.prompt,interactive:Z.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Z.localRuntime?.configExtensions?{configExtensions:Z.localRuntime.configExtensions}:{}},toolPolicies:c8(Z.toolPolicies)}:{}},J)}catch(K){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error(K)}let Y=S$(X.payload?.snapshot),V=X.payload?.session,H=(Y?.sessionId??V?.sessionId)?.trim();if(Q&&!H){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error("Hub checkpoint restore returned no session id")}if(H&&f&&H!==f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&j.handlers.size>0)this.sessionClientContributionHandlers.set(H,j.handlers);if(H)this.ensureSessionSubscription(H);let B=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,A=X.payload?.checkpoint;if(!A)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:Y?WA(Y,Z??{}):ZA(H,Z??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:B,checkpoint:A}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(J.payload?.prompts)?J.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,updated:J.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,removed:J.payload?.removed===!0}}async getAccumulatedUsage($){let J=await this.client.command("session.get",{includeSnapshot:!0},$),Q=S$(J.payload?.snapshot);if(Q){let f=Q.usage?{...Q.usage}:void 0,X=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return f||X?{usage:f,aggregateUsage:X}:void 0}let Z=J.payload?.session,W=QA(Z?.usage),j=QA(Z?.aggregateUsage);return W||j?{usage:W,aggregateUsage:j}:void 0}async abort($,J){await this.client.command("run.abort",{sessionId:$,reason:jA(J)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,J]of this.sessionSubscriptions){J();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(k1(Q))return;throw Q}return hN(J.payload)}async listSessions($=100){let J=await this.client.command("session.list",{limit:$}),Q=Array.isArray(J.payload?.snapshots)?J.payload.snapshots.flatMap((W)=>{let j=S$(W);return j?[Q9(j)]:[]}):[];if(Q.length>0)return Q;return(J.payload?.sessions??[]).map(fA)}async listSettings($){let J=await this.client.command("settings.list",eB($));if(!J.ok)throw Error(Z9(J,"settings.list"));return J.payload?.snapshot}async toggleSetting($){let J=await this.client.command("settings.toggle",eB($));if(!J.ok)throw Error(Z9(J,"settings.toggle"));return{snapshot:J.payload?.snapshot,changedTypes:Array.isArray(J.payload?.changedTypes)?J.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,J){let Q={...J.metadata??{}};if(typeof J.prompt==="string")Q.prompt=J.prompt;if(typeof J.title==="string")Q.title=J.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw sB(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(Z9(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:J,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(Z9(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,J){return this.events.subscribe($,J)}ensureSessionSubscription($){let J=$.trim();if(!J||this.sessionSubscriptions.has(J))return;let Q=this.client.subscribe((Z)=>{this.handleHubEvent(Z)},{sessionId:J});this.sessionSubscriptions.set(J,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let J=$.trim();if(!J)return;this.sessionSubscriptions.get(J)?.(),this.sessionSubscriptions.delete(J),this.agentDoneEmittedForCurrentRunBySession.delete(J)}resolveCapabilities($){return _0(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:bN($.payload)}})}handleHubEvent($){let J=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!J)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(J);let Q=S$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",Z=$.payload?.redacted===!0;if(!Q&&!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:Z}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:J,payload:$.payload});return}case"usage.updated":{let Q=EN($.payload);this.events.emit({type:"agent_event",payload:{sessionId:J,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:J,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"tool",toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Q=S$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:J,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:J,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=S$($.payload?.snapshot),Z=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:J,payload:{...$.payload,reason:Z}}),Q?.interactive===!0&&j0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:J,reason:Z,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,J,Q){try{sB(this.telemetry,{component:"core",operation:$,error:J,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let J=$.sessionId?.trim();if(!J)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let Z=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Z)return;let j=this.sessionClientContributionHandlers.get(J)?.get(W);if(!j){await this.client.command("capability.respond",{requestId:Z,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${J}.`},J).catch(()=>{});return}let f=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Z,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Z,payload:V},J).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let V=await j({payload:f,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!0,payload:V},J)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!1,error:V instanceof Error?V.message:String(V)},J)}finally{this.activeCapabilityAbortControllers.delete(Z)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let J=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!J)return;let Q=this.activeCapabilityAbortControllers.get(J);if(!Q)return;Q.abort(wN($.payload.error))}async handleApprovalRequested($){let J=$.sessionId?.trim();if(!J)return;let Q=this.sessionCapabilities.get(J)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let Z=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Z||!W||!j)return;let f=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=SN($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:J,toolCallId:W,toolName:j,toolInput:X});let Y=await Promise.resolve(Q({sessionId:J,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:J,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:j,input:X,policy:f})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Z,approved:Y.approved,reason:Y.reason},J).catch(()=>{})}}var YA={};w(YA,{RemoteRuntimeHost:()=>u8});class u8 extends i1{constructor($){super({url:j$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var VA={};w(VA,{SqliteSessionStore:()=>U1});import{existsSync as kN,mkdirSync as IN}from"node:fs";import{join as xN}from"node:path";import{asBool as fJ,asOptionalString as D1,asString as n1,ensureSessionSchema as gN,loadSqliteDb as mN,nowIso as W9,toBoolInt as XJ}from"@cline/shared/db";import{resolveDbDataDir as vN}from"@cline/shared/storage";class U1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??vN()}init(){this.getRawDb()}ensureSessionsDir(){if(!kN(this.sessionsDirPath))IN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return xN(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=mN(this.sessionDbPath());return gN($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}create($){let J=W9();this.run(`INSERT OR REPLACE INTO sessions (
483
491
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
484
492
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
485
493
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
486
494
  metadata_json, transcript_path, hook_path, messages_path, updated_at
487
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,$J($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$J($.enableTools),$J($.enableSpawn),$J($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$J($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,f])}update($){let f=[],J=[];if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId);if(f.length===0)return;f.push("updated_at = ?"),J.push(a5()),J.push($.sessionId),this.run(`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`,J)}updateStatus($,f,J){this.update({sessionId:$,status:f,endedAt:J0(f)?null:a5(),exitCode:J0(f)?null:J??(f==="failed"?1:0)})}get($){let f=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
495
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,XJ($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,XJ($.enableTools),XJ($.enableSpawn),XJ($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,XJ($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,J])}update($){let J=[],Q=[];if($.endedAt!==void 0)J.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)J.push("exit_code = ?"),Q.push($.exitCode);if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.prompt!==void 0)J.push("prompt = ?"),Q.push($.prompt);if($.metadata!==void 0)J.push("metadata_json = ?"),Q.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)J.push("parent_session_id = ?"),Q.push($.parentSessionId);if($.parentAgentId!==void 0)J.push("parent_agent_id = ?"),Q.push($.parentAgentId);if($.agentId!==void 0)J.push("agent_id = ?"),Q.push($.agentId);if($.conversationId!==void 0)J.push("conversation_id = ?"),Q.push($.conversationId);if(J.length===0)return;J.push("updated_at = ?"),Q.push(W9()),Q.push($.sessionId),this.run(`UPDATE sessions SET ${J.join(", ")} WHERE session_id = ?`,Q)}updateStatus($,J,Q){this.update({sessionId:$,status:J,endedAt:j0(J)?null:W9(),exitCode:j0(J)?null:Q??(J==="failed"?1:0)})}get($){let J=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
488
496
  provider, model, cwd, workspace_root, team_name,
489
497
  enable_tools, enable_spawn, enable_teams,
490
498
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
491
499
  prompt, metadata_json, hook_path, messages_path, updated_at
492
- FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:i1(f.session_id),source:i1(f.source),pid:Number(f.pid??0),startedAt:i1(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:i1(f.status),interactive:e4(f.interactive),provider:i1(f.provider),model:i1(f.model),cwd:i1(f.cwd),workspaceRoot:i1(f.workspace_root),teamName:F1(f.team_name),enableTools:e4(f.enable_tools),enableSpawn:e4(f.enable_spawn),enableTeams:e4(f.enable_teams),parentSessionId:F1(f.parent_session_id),parentAgentId:F1(f.parent_agent_id),agentId:F1(f.agent_id),conversationId:F1(f.conversation_id),isSubagent:e4(f.is_subagent),prompt:F1(f.prompt),metadata:(()=>{let J=F1(f.metadata_json);if(!J)return;try{let Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:F1(f.hook_path),messagesPath:F1(f.messages_path),updatedAt:F1(f.updated_at)??a5()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let Q of f){let Z=this.get(i1(Q.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}G8();import{existsSync as lW,mkdirSync as Uq,readFileSync as nH,renameSync as Lq,writeFileSync as _q}from"node:fs";import{join as aH}from"node:path";import{resolveSessionDataDir as zq}from"@cline/shared/storage";import{dirname as Rq}from"node:path";import{nanoid as Dq}from"nanoid";import{appendFileSync as vN,existsSync as cN,mkdirSync as hH,readFileSync as uN,writeFileSync as bH}from"node:fs";import{dirname as kH,join as dN}from"node:path";import{ensureHookLogDir as lN}from"@cline/shared/storage";class EW{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new ZW(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){QA(f,J,OZ($))}writeSessionManifest($,f){hH(kH($),{recursive:!0}),bH($,`${JSON.stringify(y0.parse(f),null,2)}
493
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!cN(f))return{path:f};try{return{path:f,manifest:y0.parse(JSON.parse(uN(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let Q=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=MZ({updatedAt:s(),context:OZ($),messages:f,systemPrompt:J}),W=`${JSON.stringify(Z,null,2)}
494
- `;if(hH(kH(Q),{recursive:!0}),bH(Q,W,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:W,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,Q,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??dN(lN(),"hooks.jsonl");vN(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:f,pid:J,source:Z})}
495
- `,"utf8")}}import{appendFileSync as pN}from"node:fs";import{join as rN}from"node:path";import{resolveRootSessionId as IH}from"@cline/shared";import{ensureHookLogDir as iN}from"@cline/shared/storage";import{z as hW}from"zod";var nN="subagent",aN=hW.looseObject({task:hW.string().optional(),systemPrompt:hW.string().optional()});class t5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,Q){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:nN,pid:process.ppid,startedAt:f.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:f.parentSessionId,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId??null,isSubagent:!0,prompt:f.prompt,metadata:Y4({prompt:f.prompt}),hookPath:"",messagesPath:f.messagesPath,updatedAt:f.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let f=IH($.sessionContext);if(!f)return;let J=aN.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let Q=V2(f,$.agentId),Z=await this.adapter.getSession(Q),W=s(),j=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),X=$.prompt??Z?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:Q,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:W,...j})),this.manifestStore.initializeMessagesFile(Q,j.messagesPath,W),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??X??null,metadata:Y4({metadata:Z.metadata??void 0,prompt:Z.prompt??X??null}),expectedStatusLock:Z.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=IH($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=V2(f,$.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:f})}async applySubagentStatus($,f){await this.applySubagentStatusBySessionId($,W4(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let Q=J0(f)?null:s(),Z=J0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:Q,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of J)await this.applySubagentStatusBySessionId(Q.sessionId,f)}async onTeamTaskStart($,f,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=Q4($,f),W=s(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:W,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,W);let X=this.teamTaskQueueKey($,f),Y=this.teamTaskSessionsByAgent.get(X)??[];Y.push(Z),this.teamTaskSessionsByAgent.set(X,Y)}async onTeamTaskEnd($,f,J,Q,Z,W){let j=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(j);if(!X||X.length===0)return;let Y=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(j);if(!Y)return;let A=Z?.messages??W,V=this.toPersistedMessages(A,Z,W);if(V)await this.manifestStore.persistSessionMessages(Y,V);await this.applySubagentStatusBySessionId(Y,J),this.teamTaskLastHeartbeatBySession.delete(Y),this.teamTaskLastProgressLineBySession.delete(Y)}async onTeamTaskProgress($,f,J,Q){let Z=this.teamTaskQueueKey($,f),W=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!W)return;let j=J.trim();if(!j)return;let X=Q?.kind??"progress";if(X==="heartbeat"){let A=Date.now(),V=this.teamTaskLastHeartbeatBySession.get(W)??0;if(A-V<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(W,A)}let Y=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(W)===Y)return;this.teamTaskLastProgressLineBySession.set(W,Y)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let Q=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(Q)await this.manifestStore.persistSessionMessages(J,Q);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??rN(iN(),"hooks.jsonl");pN(J,`${JSON.stringify({ts:s(),...$})}
496
- `,"utf8")}}import{formatUserInputBlock as Pq}from"@cline/shared";var iH={};q(iH,{toTeamProgressLifecycleEvent:()=>m2,sanitizeTeamName:()=>iY,reviveTeamStateDates:()=>k6,parseConfiguredAgentConfig:()=>fJ,loadConfiguredAgentConfigs:()=>I2,createWorkerReviewerTeam:()=>rH,createSpawnAgentTool:()=>F$,createDelegatedAgentConfigProvider:()=>K$,createDelegatedAgent:()=>G$,createConfiguredAgentTools:()=>x2,createAgentTeamsTools:()=>$f,createAgentTeam:()=>IW,buildTeamProgressSummary:()=>g2,buildDelegatedAgentConfig:()=>o$,buildConfiguredAgentToolName:()=>JJ,buildConfiguredAgentToolDescriptors:()=>QJ,bootstrapAgentTeams:()=>A2,AgentTeamsRuntime:()=>Of,AgentTeam:()=>c2});import{existsSync as tN,readdirSync as sN,readFileSync as oN}from"node:fs";import{basename as xH,extname as eN,join as $q}from"node:path";import{resolveAgentConfigSearchPaths as fq}from"@cline/shared/storage";import mH from"yaml";import{z as N0}from"zod";var vH=N0.object({name:N0.string().trim().min(1),description:N0.string().trim().min(1),tools:N0.union([N0.string(),N0.array(N0.string())]).optional(),skills:N0.union([N0.string(),N0.array(N0.string())]).optional(),providerId:N0.string().trim().min(1).optional(),modelId:N0.string().trim().min(1).optional(),maxIterations:N0.number().int().positive().optional()});function Jq($){let f=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!f)throw Error("Missing YAML frontmatter block in agent config file.");let J=f[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=J;let Z,W=Array.from($.matchAll(Q)).filter((j)=>j.index>=J);for(let j of W){let X=j.index,Y=$.slice(J,X);try{let A=mH.parse(Y);if(!A||typeof A!=="object"||Array.isArray(A))continue;vH.parse(A);let V=$.slice(X+j[0].length);Z={frontmatter:Y,body:V}}catch{}}if(Z)return Z;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function gH($){if($===void 0)return;let f=Array.isArray($)?$:$.split(",");return Array.from(new Set(f.map((J)=>J.trim()).filter((J)=>J.length>0)))}function Qq($){return $.trim().toLowerCase()}function Zq($){let f=eN($).toLowerCase();return f===".yml"||f===".yaml"}function fJ($,f={}){let{frontmatter:J,body:Q}=Jq($),Z=mH.parse(J);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Agent config frontmatter must be a YAML mapping.");let W=vH.parse(Z),j=Q.trim();if(!j)throw Error("Missing system prompt body in agent config file.");return{name:W.name,description:W.description,tools:gH(W.tools),skills:gH(W.skills),providerId:W.providerId,modelId:W.modelId,maxIterations:W.maxIterations,systemPrompt:j,path:f.path}}function I2($){let f=$.searchPaths??fq($.workspaceRoot),J=new Map,Q=[];for(let W of f.filter(Boolean)){if(!tN(W))continue;let j;try{j=sN(W,{withFileTypes:!0})}catch(X){Q.push({path:W,error:X instanceof Error?X:Error(String(X))});continue}for(let X of j){if(!X.isFile()||!Zq(X.name))continue;let Y=$q(W,X.name);try{let A=oN(Y,"utf8"),V=fJ(A,{path:Y}),H=Qq(V.name);if(!J.has(H))J.set(H,V)}catch(A){Q.push({path:Y,error:A instanceof Error?A:Error(String(A))})}}}return{configs:Array.from(J.values()).sort((W,j)=>(W.path?xH(W.path):W.name).localeCompare(j.path?xH(j.path):j.name)),errors:Q}}import{createTool as Wq,zodToJsonSchema as jq}from"@cline/shared";import{z as cH}from"zod";var bW="subagent_",s5=64,Xq=cH.object({prompt:cH.string().trim().min(1).describe("Task for the subagent to perform")});function Yq($){let f="",J=!0;for(let Q of $.trim().toLowerCase()){let Z=Q.charCodeAt(0);if(!(Z>=97&&Z<=122||Z>=48&&Z<=57||Q==="_")||Q==="_"){if(!J)f+="_",J=!0;continue}f+=Q,J=!1}return J?f.slice(0,-1):f}function Aq($){let f=2166136261;for(let J=0;J<$.length;J++)f^=$.charCodeAt(J),f=Math.imul(f,16777619);return(f>>>0).toString(36)}function JJ($){let f=Yq($)||"agent",J=Aq($).slice(0,6),Q=`${bW}${f}`;if(Q.length<=s5)return Q;let Z=s5-bW.length-J.length-1,W=f.slice(0,Math.max(1,Z));return`${bW}${W}_${J}`.slice(0,s5)}function QJ($){let f=new Set,J=[];for(let Q of[...$].sort((Z,W)=>Z.name.localeCompare(W.name))){let Z=JJ(Q.name),W=Z,j=2;while(f.has(W)){let X=`_${j++}`,Y=Math.max(1,s5-X.length);W=`${Z.slice(0,Y)}${X}`}f.add(W),J.push({toolName:W,config:Q})}return J}function Vq($,f){return{...$,providerId:f.providerId??$.providerId,modelId:f.modelId??$.modelId,maxIterations:f.maxIterations??$.maxIterations}}function x2($){return QJ($.agents).map(({toolName:f,config:J})=>{return Wq({name:f,description:`Use the "${J.name}" subagent: ${J.description}`,inputSchema:jq(Xq),execute:async(Z,W)=>{let j=$.configProvider.getRuntimeConfig(),X=K$(Vq(j,J)),Y=$.createSubAgentTools?await $.createSubAgentTools(J,Z,W):[],A=G$({kind:"subagent",prompt:J.systemPrompt,configProvider:X,tools:Y,maxIterations:J.maxIterations,parentAgentId:W.agentId,abortSignal:W.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),V=A.getAgentId(),H=A.getConversationId(),B=W.agentId,K={systemPrompt:J.systemPrompt,task:Z.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:V,conversationId:H,parentAgentId:B,input:K})}catch{}try{let G=await A.run(Z.prompt),R={text:G.text,iterations:G.iterations,finishReason:G.finishReason,usage:{inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:V,conversationId:H,parentAgentId:B,input:K,result:R,agentResult:G})}catch{}return R}catch(G){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:V,conversationId:H,parentAgentId:B,input:K,error:G instanceof Error?G:Error(String(G))})}catch{}throw G}},timeoutMs:300000,retryable:!1})})}function R1(){return new Date().toISOString()}function uH($,f){if(f<=0)return 0;return Math.round($/f*100)}function Hq($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let Q=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let W of Z.requiredSections)if(!J.has(`${Z.id}:${W}`))Q.add(`${Z.id}:${W}`)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function g2($,f){let J={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},W={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},X=0,Y=0;for(let P of f.members)if(J[P.status]+=1,P.role==="lead")X+=1;else Y+=1;let A=[],V=[],H=f.tasks.filter((P)=>P.status==="completed").length,B=new Map(f.tasks.map((P)=>[P.id,P]));for(let P of f.tasks){if(Q[P.status]+=1,P.status==="blocked"){A.push(P.id);continue}if(P.status!=="pending")continue;if(P.dependsOn.every((D)=>{return B.get(D)?.status==="completed"}))V.push(P.id)}let K=[],G,R=0;for(let P of f.runs){if(Z[P.status]+=1,P.status==="queued"||P.status==="running")K.push(P.id);let F=P.startedAt.getTime();if(F>=R)R=F,G=P.id}for(let P of f.outcomes)W[P.status]+=1;for(let P of f.outcomeFragments)j[P.status]+=1;return{teamName:$,updatedAt:R1(),members:{total:f.members.length,byStatus:J,leadCount:X,teammateCount:Y},tasks:{total:f.tasks.length,byStatus:Q,blockedTaskIds:A,readyTaskIds:V,completionPct:uH(H,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:W,finalizedPct:uH(W.finalized,f.outcomes.length),missingRequiredSections:Hq(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function m2($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),taskId:f.task.id,agentId:f.task.assignee??f.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),taskId:f.message.taskId,agentId:f.message.fromAgentId,message:f.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),taskId:f.entry.taskId,agentId:f.entry.agentId,message:f.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1()}}import{sanitizeFileName as Bq,TeamMessageType as k}from"@cline/shared";import{nanoid as Kq}from"nanoid";import{TeamMessageType as rc}from"@cline/shared";function kW($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function dH($,f){return $?.status==="stopped"&&kW(f)}var Gq=600000,lH="recovered_queued";function Fq($){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.
500
+ FROM sessions WHERE session_id = ?`,[$]);if(!J)return;return{sessionId:n1(J.session_id),source:n1(J.source),pid:Number(J.pid??0),startedAt:n1(J.started_at),endedAt:J.ended_at??null,exitCode:J.exit_code??null,status:n1(J.status),interactive:fJ(J.interactive),provider:n1(J.provider),model:n1(J.model),cwd:n1(J.cwd),workspaceRoot:n1(J.workspace_root),teamName:D1(J.team_name),enableTools:fJ(J.enable_tools),enableSpawn:fJ(J.enable_spawn),enableTeams:fJ(J.enable_teams),parentSessionId:D1(J.parent_session_id),parentAgentId:D1(J.parent_agent_id),agentId:D1(J.agent_id),conversationId:D1(J.conversation_id),isSubagent:fJ(J.is_subagent),prompt:D1(J.prompt),metadata:(()=>{let Q=D1(J.metadata_json);if(!Q)return;try{let Z=JSON.parse(Q);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return})(),hookPath:D1(J.hook_path),messagesPath:D1(J.messages_path),updatedAt:D1(J.updated_at)??W9()}}list($=200){let J=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Q=[];for(let Z of J){let W=this.get(n1(Z.session_id));if(W)Q.push(W)}return Q}delete($,J=!1){let Q=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}}l2();import{existsSync as j3,mkdirSync as Lw,readFileSync as qA,renameSync as _w,writeFileSync as Ow}from"node:fs";import{join as PA}from"node:path";import{resolveSessionDataDir as Tw}from"@cline/shared/storage";import{dirname as Rw}from"node:path";import{nanoid as zw}from"nanoid";import{appendFileSync as cN,existsSync as uN,mkdirSync as HA,readFileSync as dN,writeFileSync as BA}from"node:fs";import{dirname as AA,join as lN}from"node:path";import{ensureHookLogDir as pN}from"@cline/shared/storage";class iW{adapter;messagesArtifactUploader;logger;artifacts;constructor($,J,Q){this.adapter=$;this.messagesArtifactUploader=J;this.logger=Q;this.artifacts=new RW(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,J,Q){EV(J,Q,x7($))}writeSessionManifest($,J){HA(AA($),{recursive:!0}),BA($,`${JSON.stringify(y0.parse(J),null,2)}
501
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let J=this.artifacts.sessionManifestPath($,!1);if(!uN(J))return{path:J};try{return{path:J,manifest:y0.parse(JSON.parse(dN(J,"utf8")))}}catch{return{path:J}}}async resolveArtifactPath($,J,Q){let W=(await this.adapter.getSession($))?.[J];return typeof W==="string"&&W.trim().length>0?W:Q($)}async persistSessionMessages($,J,Q){let Z=await this.resolveArtifactPath($,"messagesPath",(f)=>this.artifacts.sessionMessagesPath(f)),W=g7({updatedAt:e(),context:x7($),messages:J,systemPrompt:Q}),j=`${JSON.stringify(W,null,2)}
502
+ `;if(HA(AA(Z),{recursive:!0}),BA(Z,j,"utf8"),!this.messagesArtifactUploader)return;try{let f=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Z,contents:j,row:f})}catch(f){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:f})}}appendStaleSessionHookLog($,J,Q,Z,W){let f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??lN(pN(),"hooks.jsonl");cN(f,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Z,sessionId:J,pid:Q,source:W})}
503
+ `,"utf8")}}import{appendFileSync as rN}from"node:fs";import{join as iN}from"node:path";import{resolveRootSessionId as KA}from"@cline/shared";import{ensureHookLogDir as nN}from"@cline/shared/storage";import{z as nW}from"zod";var aN="subagent",sN=nW.looseObject({task:nW.string().optional(),systemPrompt:nW.string().optional()});class j9{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,J,Q,Z){this.adapter=$;this.manifestStore=J;this.toPersistedMessages=Q;this.heartbeatLogIntervalMs=Z}teamTaskQueueKey($,J){return`${$}::${J}`}activeTeamTaskSessionId($,J){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,J))?.at(-1)}buildSubsessionRow($,J){return{sessionId:J.sessionId,source:aN,pid:process.ppid,startedAt:J.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:J.parentSessionId,parentAgentId:J.parentAgentId,agentId:J.agentId,conversationId:J.conversationId??null,isSubagent:!0,prompt:J.prompt,metadata:D6({prompt:J.prompt}),hookPath:"",messagesPath:J.messagesPath,updatedAt:J.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let J=KA($.sessionContext);if(!J)return;let Q=sN.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:J,parentAgentId:$.agent_id,task:Q.success?Q.data.task:void 0,systemPrompt:Q.success?Q.data.systemPrompt:void 0})}async upsertSubagentSession($){let J=$.rootSessionId;if(!J)return;let Q=await this.adapter.getSession(J);if(!Q)return;let Z=G8(J,$.agentId),W=await this.adapter.getSession(Z),j=e(),f=this.manifestStore.artifacts.subagentArtifactPaths(Z,$.agentId,this.activeTeamTaskSessionId(J,$.parentAgentId)),X=$.prompt??W?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(J,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!W)return await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:j,...f})),this.manifestStore.initializeMessagesFile(Z,f.messagesPath,j),Z;return await this.adapter.updateSession({sessionId:Z,setRunning:!0,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:W.prompt??X??null,metadata:D6({metadata:W.metadata??void 0,prompt:W.prompt??X??null}),expectedStatusLock:W.statusLock}),Z}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let J=KA($.sessionContext);if(!J)return;if($.hookName==="session_shutdown"){let Q=G8(J,$.agent_id);return await this.adapter.getSession(Q)?Q:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:J})}async applySubagentStatus($,J){await this.applySubagentStatusBySessionId($,K6(J))}async applySubagentStatusBySessionId($,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=j0(J)?null:e(),W=j0(J)?null:J==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:J,endedAt:Z,exitCode:W,expectedStatusLock:Q.statusLock})}async applyStatusToRunningChildSessions($,J){if(!$)return;let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Z of Q)await this.applySubagentStatusBySessionId(Z.sessionId,J)}async onTeamTaskStart($,J,Q){let Z=await this.adapter.getSession($);if(!Z)return;let W=B6($,J),j=e(),{messagesPath:f}=this.manifestStore.artifacts.subagentArtifactPaths(W,J);await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:W,parentSessionId:$,parentAgentId:"lead",agentId:J,prompt:Q||`Team task for ${J}`,startedAt:j,messagesPath:f})),this.manifestStore.initializeMessagesFile(W,f,j);let X=this.teamTaskQueueKey($,J),Y=this.teamTaskSessionsByAgent.get(X)??[];Y.push(W),this.teamTaskSessionsByAgent.set(X,Y)}async onTeamTaskEnd($,J,Q,Z,W,j){let f=this.teamTaskQueueKey($,J),X=this.teamTaskSessionsByAgent.get(f);if(!X||X.length===0)return;let Y=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(f);if(!Y)return;let V=W?.messages??j,H=this.toPersistedMessages(V,W,j);if(H)await this.manifestStore.persistSessionMessages(Y,H);await this.applySubagentStatusBySessionId(Y,Q),this.teamTaskLastHeartbeatBySession.delete(Y),this.teamTaskLastProgressLineBySession.delete(Y)}async onTeamTaskProgress($,J,Q,Z){let W=this.teamTaskQueueKey($,J),j=this.teamTaskSessionsByAgent.get(W)?.[0];if(!j)return;let f=Q.trim();if(!f)return;let X=Z?.kind??"progress";if(X==="heartbeat"){let V=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(V-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,V)}let Y=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${f}`:`[progress] ${f}`;if(this.teamTaskLastProgressLineBySession.get(j)===Y)return;this.teamTaskLastProgressLineBySession.set(j,Y)}async handleSubAgentStart($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;await this.applySubagentStatusBySessionId(Q,"running")}async handleSubAgentEnd($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;if(J.error){await this.applySubagentStatusBySessionId(Q,"failed");return}let Z=this.toPersistedMessages(J.agentResult?.messages,J.agentResult);if(Z)await this.manifestStore.persistSessionMessages(Q,Z);let W=J.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Q,W==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Q=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??iN(nN(),"hooks.jsonl");rN(Q,`${JSON.stringify({ts:e(),...$})}
504
+ `,"utf8")}}import{formatUserInputBlock as Uw}from"@cline/shared";var MA={};w(MA,{toTeamProgressLifecycleEvent:()=>r8,sanitizeTeamName:()=>OV,reviveTeamStateDates:()=>l5,parseConfiguredAgentConfig:()=>YJ,loadConfiguredAgentConfigs:()=>d8,createWorkerReviewerTeam:()=>TA,createSpawnAgentTool:()=>D$,createDelegatedAgentConfigProvider:()=>G$,createDelegatedAgent:()=>F$,createConfiguredAgentTools:()=>l8,createAgentTeamsTools:()=>$2,createAgentTeam:()=>oW,buildTeamProgressSummary:()=>p8,buildDelegatedAgentConfig:()=>t$,buildConfiguredAgentToolName:()=>VJ,buildConfiguredAgentToolDescriptors:()=>HJ,bootstrapAgentTeams:()=>K8,AgentTeamsRuntime:()=>T2,AgentTeam:()=>n8});import{existsSync as oN,readdirSync as tN,readFileSync as eN}from"node:fs";import{basename as GA,extname as $w,join as Jw}from"node:path";import{resolveAgentConfigSearchPaths as Qw}from"@cline/shared/storage";import DA from"yaml";import{z as P0}from"zod";var UA=P0.object({name:P0.string().trim().min(1),description:P0.string().trim().min(1),tools:P0.union([P0.string(),P0.array(P0.string())]).optional(),skills:P0.union([P0.string(),P0.array(P0.string())]).optional(),providerId:P0.string().trim().min(1).optional(),modelId:P0.string().trim().min(1).optional(),maxIterations:P0.number().int().positive().optional()});function Zw($){let J=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!J)throw Error("Missing YAML frontmatter block in agent config file.");let Q=J[0].length,Z=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Z.lastIndex=Q;let W,j=Array.from($.matchAll(Z)).filter((f)=>f.index>=Q);for(let f of j){let X=f.index,Y=$.slice(Q,X);try{let V=DA.parse(Y);if(!V||typeof V!=="object"||Array.isArray(V))continue;UA.parse(V);let H=$.slice(X+f[0].length);W={frontmatter:Y,body:H}}catch{}}if(W)return W;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function FA($){if($===void 0)return;let J=Array.isArray($)?$:$.split(",");return Array.from(new Set(J.map((Q)=>Q.trim()).filter((Q)=>Q.length>0)))}function Ww($){return $.trim().toLowerCase()}function jw($){let J=$w($).toLowerCase();return J===".yml"||J===".yaml"}function YJ($,J={}){let{frontmatter:Q,body:Z}=Zw($),W=DA.parse(Q);if(!W||typeof W!=="object"||Array.isArray(W))throw Error("Agent config frontmatter must be a YAML mapping.");let j=UA.parse(W),f=Z.trim();if(!f)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:FA(j.tools),skills:FA(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:f,path:J.path}}function d8($){let J=$.searchPaths??Qw($.workspaceRoot),Q=new Map,Z=[];for(let j of J.filter(Boolean)){if(!oN(j))continue;let f;try{f=tN(j,{withFileTypes:!0})}catch(X){Z.push({path:j,error:X instanceof Error?X:Error(String(X))});continue}for(let X of f){if(!X.isFile()||!jw(X.name))continue;let Y=Jw(j,X.name);try{let V=eN(Y,"utf8"),H=YJ(V,{path:Y}),B=Ww(H.name);if(!Q.has(B))Q.set(B,H)}catch(V){Z.push({path:Y,error:V instanceof Error?V:Error(String(V))})}}}return{configs:Array.from(Q.values()).sort((j,f)=>(j.path?GA(j.path):j.name).localeCompare(f.path?GA(f.path):f.name)),errors:Z}}import{createTool as fw,zodToJsonSchema as Xw}from"@cline/shared";import{z as RA}from"zod";var aW="subagent_",f9=64,Yw=RA.object({prompt:RA.string().trim().min(1).describe("Task for the subagent to perform")});function Vw($){let J="",Q=!0;for(let Z of $.trim().toLowerCase()){let W=Z.charCodeAt(0);if(!(W>=97&&W<=122||W>=48&&W<=57||Z==="_")||Z==="_"){if(!Q)J+="_",Q=!0;continue}J+=Z,Q=!1}return Q?J.slice(0,-1):J}function Hw($){let J=2166136261;for(let Q=0;Q<$.length;Q++)J^=$.charCodeAt(Q),J=Math.imul(J,16777619);return(J>>>0).toString(36)}function VJ($){let J=Vw($)||"agent",Q=Hw($).slice(0,6),Z=`${aW}${J}`;if(Z.length<=f9)return Z;let W=f9-aW.length-Q.length-1,j=J.slice(0,Math.max(1,W));return`${aW}${j}_${Q}`.slice(0,f9)}function HJ($){let J=new Set,Q=[];for(let Z of[...$].sort((W,j)=>W.name.localeCompare(j.name))){let W=VJ(Z.name),j=W,f=2;while(J.has(j)){let X=`_${f++}`,Y=Math.max(1,f9-X.length);j=`${W.slice(0,Y)}${X}`}J.add(j),Q.push({toolName:j,config:Z})}return Q}function Bw($,J){return{...$,providerId:J.providerId??$.providerId,modelId:J.modelId??$.modelId,maxIterations:J.maxIterations??$.maxIterations}}function l8($){return HJ($.agents).map(({toolName:J,config:Q})=>{return fw({name:J,description:`Use the "${Q.name}" subagent: ${Q.description}`,inputSchema:Xw(Yw),execute:async(W,j)=>{let f=$.configProvider.getRuntimeConfig(),X=G$(Bw(f,Q)),Y=$.createSubAgentTools?await $.createSubAgentTools(Q,W,j):[],V=F$({kind:"subagent",prompt:Q.systemPrompt,configProvider:X,tools:Y,maxIterations:Q.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=V.getAgentId(),B=V.getConversationId(),A=j.agentId,K={systemPrompt:Q.systemPrompt,task:W.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:B,parentAgentId:A,input:K})}catch{}try{let G=await V.run(W.prompt),R={text:G.text,iterations:G.iterations,finishReason:G.finishReason,usage:{inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,result:R,agentResult:G})}catch{}return R}catch(G){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,error:G instanceof Error?G:Error(String(G))})}catch{}throw G}},timeoutMs:300000,retryable:!1})})}function R1(){return new Date().toISOString()}function zA($,J){if(J<=0)return 0;return Math.round($/J*100)}function Aw($,J){let Q=new Set;for(let W of J)if(W.status==="reviewed")Q.add(`${W.outcomeId}:${W.section}`);let Z=new Set;for(let W of $){if(W.status==="finalized")continue;for(let j of W.requiredSections)if(!Q.has(`${W.id}:${j}`))Z.add(`${W.id}:${j}`)}return[...Z].sort((W,j)=>W.localeCompare(j))}function p8($,J){let Q={idle:0,running:0,stopped:0},Z={pending:0,in_progress:0,blocked:0,completed:0},W={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},f={draft:0,reviewed:0,rejected:0},X=0,Y=0;for(let D of J.members)if(Q[D.status]+=1,D.role==="lead")X+=1;else Y+=1;let V=[],H=[],B=J.tasks.filter((D)=>D.status==="completed").length,A=new Map(J.tasks.map((D)=>[D.id,D]));for(let D of J.tasks){if(Z[D.status]+=1,D.status==="blocked"){V.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((F)=>{return A.get(F)?.status==="completed"}))H.push(D.id)}let K=[],G,R=0;for(let D of J.runs){if(W[D.status]+=1,D.status==="queued"||D.status==="running")K.push(D.id);let U=D.startedAt.getTime();if(U>=R)R=U,G=D.id}for(let D of J.outcomes)j[D.status]+=1;for(let D of J.outcomeFragments)f[D.status]+=1;return{teamName:$,updatedAt:R1(),members:{total:J.members.length,byStatus:Q,leadCount:X,teammateCount:Y},tasks:{total:J.tasks.length,byStatus:Z,blockedTaskIds:V,readyTaskIds:H,completionPct:zA(B,J.tasks.length)},runs:{total:J.runs.length,byStatus:W,activeRunIds:K,latestRunId:G},outcomes:{total:J.outcomes.length,byStatus:j,finalizedPct:zA(j.finalized,J.outcomes.length),missingRequiredSections:Aw(J.outcomes,J.outcomeFragments)},fragments:{total:J.outcomeFragments.length,byStatus:f}}}function r8($){let{event:J}=$;switch(J.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.task.id,agentId:J.task.assignee??J.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),outcomeId:J.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),outcomeId:J.fragment.outcomeId,fragmentId:J.fragment.id,agentId:J.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.message.taskId,agentId:J.message.fromAgentId,message:J.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.entry.taskId,agentId:J.entry.agentId,message:J.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),agentId:J.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1()}}import{sanitizeFileName as Kw,TeamMessageType as I}from"@cline/shared";import{nanoid as Gw}from"nanoid";import{TeamMessageType as Md}from"@cline/shared";function sW($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function LA($,J){return $?.status==="stopped"&&sW(J)}var Fw=600000,_A="recovered_queued";function Dw($){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.
497
505
 
498
- ${$.message}`}class c2{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,Q]of Object.entries($))this.addAgent(J,Q)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:k.AgentEvent,agentId:$,event:Z})}},Q=new B$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);this.agents.set($,Q),this.configs.set($,f)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:k.TaskStart,agentId:$,message:f});try{let Q=await J.run(f);return this.emitEvent({type:k.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:k.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:k.TaskStart,agentId:$,message:f});try{let Q=await J.continue(f);return this.emitEvent({type:k.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:k.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async runParallel($){let f=$.map(async(J)=>{let Q=this.agents.get(J.agentId);if(!Q)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:k.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);return this.emitEvent({type:k.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:k.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),{agentId:J.agentId,result:void 0,error:W,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let Q=this.agents.get(J.agentId);if(!Q){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:k.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);this.emitEvent({type:k.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:k.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:W,metadata:J.metadata})}}return f}async runPipeline($,f,J){let Q=[],Z=f;for(let W of $){let j=this.agents.get(W);if(!j){Q.push({agentId:W,result:void 0,error:Error(`Agent "${W}" not found in team`)});break}this.emitEvent({type:k.TaskStart,agentId:W,message:Z});try{let X=await j.run(Z);this.emitEvent({type:k.TaskEnd,agentId:W,result:X}),Q.push({agentId:W,result:X});let Y=$.indexOf(W)+1;if(Y<$.length){let A=$[Y];Z=J?J(X,A):`Previous agent output:
506
+ ${$.message}`}class n8{agents=new Map;configs=new Map;onTeamEvent;constructor($,J){if(this.onTeamEvent=J,$)for(let[Q,Z]of Object.entries($))this.addAgent(Q,Z)}addAgent($,J){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Q={...J,onEvent:(W)=>{J.onEvent?.(W),this.emitEvent({type:I.AgentEvent,agentId:$,event:W})}},Z=new K$(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);this.agents.set($,Z),this.configs.set($,J)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,J){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:I.TaskStart,agentId:$,message:J});try{let Z=await Q.run(J);return this.emitEvent({type:I.TaskEnd,agentId:$,result:Z}),Z}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));throw this.emitEvent({type:I.TaskEnd,agentId:$,error:W,messages:Q.getMessages()}),Z}}async continueTo($,J){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:I.TaskStart,agentId:$,message:J});try{let Z=await Q.continue(J);return this.emitEvent({type:I.TaskEnd,agentId:$,result:Z}),Z}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));throw this.emitEvent({type:I.TaskEnd,agentId:$,error:W,messages:Q.getMessages()}),Z}}async runParallel($){let J=$.map(async(Q)=>{let Z=this.agents.get(Q.agentId);if(!Z)return{agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata};this.emitEvent({type:I.TaskStart,agentId:Q.agentId,message:Q.message});try{let W=await Z.run(Q.message);return this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,result:W}),{agentId:Q.agentId,result:W,metadata:Q.metadata}}catch(W){let j=W instanceof Error?W:Error(String(W));return this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,error:j,messages:Z.getMessages()}),{agentId:Q.agentId,result:void 0,error:j,metadata:Q.metadata}}});return Promise.all(J)}async runSequential($){let J=[];for(let Q of $){let Z=this.agents.get(Q.agentId);if(!Z){J.push({agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata});continue}this.emitEvent({type:I.TaskStart,agentId:Q.agentId,message:Q.message});try{let W=await Z.run(Q.message);this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,result:W}),J.push({agentId:Q.agentId,result:W,metadata:Q.metadata})}catch(W){let j=W instanceof Error?W:Error(String(W));this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,error:j,messages:Z.getMessages()}),J.push({agentId:Q.agentId,result:void 0,error:j,metadata:Q.metadata})}}return J}async runPipeline($,J,Q){let Z=[],W=J;for(let j of $){let f=this.agents.get(j);if(!f){Z.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:I.TaskStart,agentId:j,message:W});try{let X=await f.run(W);this.emitEvent({type:I.TaskEnd,agentId:j,result:X}),Z.push({agentId:j,result:X});let Y=$.indexOf(j)+1;if(Y<$.length){let V=$[Y];W=Q?Q(X,V):`Previous agent output:
499
507
  ${X.text}
500
508
 
501
- Please continue from here.`}}catch(X){let Y=X instanceof Error?X:Error(String(X));this.emitEvent({type:k.TaskEnd,agentId:W,error:Y,messages:j.getMessages()}),Q.push({agentId:W,result:void 0,error:Y});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 IW($,f){return new c2($,f)}function rH($){let f=IW({worker:$.worker,reviewer:$.reviewer}),J=f;return J.doAndReview=async(Q)=>{let Z=await f.routeTo("worker",Q),W=await f.routeTo("reviewer",`Please review this work:
509
+ Please continue from here.`}}catch(X){let Y=X instanceof Error?X:Error(String(X));this.emitEvent({type:I.TaskEnd,agentId:j,error:Y,messages:f.getMessages()}),Z.push({agentId:j,result:void 0,error:Y});break}}return Z}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function oW($,J){return new n8($,J)}function TA($){let J=oW({worker:$.worker,reviewer:$.reviewer}),Q=J;return Q.doAndReview=async(Z)=>{let W=await J.routeTo("worker",Z),j=await J.routeTo("reviewer",`Please review this work:
502
510
 
503
- ${Z.text}`);return{workerResult:Z,reviewResult:W}},J}class Of{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_${Bq(Kq(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,Q=f?.markRead??!0,Z=f?.limit,W=this.mailbox.filter((X)=>X.toAgentId===$&&(!J||!X.readAt)),j=typeof Z==="number"&&Z>0?W.slice(Math.max(0,W.length-Z)):W;if(Q){let X=new Date;for(let Y of j)if(!Y.readAt)Y.readAt=X}return j.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,v2($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,v2($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,v2($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,v2(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,v2(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,v2(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...f,apiTimeoutMs:Gq,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let X=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,X},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:k.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new B$(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);let W={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,W),this.emitEvent({type:k.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:W.agentId,role:W.role,description:W.description,status:W.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(Q){if(!kW(Q))throw Q}J.status="stopped",this.emitEvent({type:k.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,Q={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,Q),this.emitEvent({type:k.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:k.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=J,this.emitEvent({type:k.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...Q}}completeTask($,f,J){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=J,!Q.assignee)Q.assignee=f;return this.emitEvent({type:k.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...Q}}async routeToTeammate($,f,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:k.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),W=Z.length>0?`${this.buildMailboxNotification(Z)}
511
+ ${W.text}`);return{workerResult:W,reviewResult:j}},Q}class T2{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${Kw(Gw(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let J=$.leadAgentId??"lead";this.members.set(J,{agentId:J,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((J)=>{let Q=this.getUnresolvedDependencies(J);return{...J,blockedBy:Q,isReady:J.status==="pending"&&!J.assignee&&Q.length===0}}).filter((J)=>{if($?.status&&J.status!==$.status)return!1;if($?.assignee&&J.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,J){let Q=J?.unreadOnly??!0,Z=J?.markRead??!0,W=J?.limit,j=this.mailbox.filter((X)=>X.toAgentId===$&&(!Q||!X.readAt)),f=typeof W==="number"&&W>0?j.slice(Math.max(0,j.length-W)):j;if(Z){let X=new Date;for(let Y of f)if(!Y.readAt)Y.readAt=X}return f.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Q of this.tasks.values())$[Q.status]++;let J={draft:0,in_review:0,finalized:0};for(let Q of this.outcomes.values())J[Q.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Q)=>({agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Q)=>!Q.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").length,outcomeCounts:J}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Q of $.tasks)this.tasks.set(Q.id,{...Q});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Q)=>({...Q}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Q)=>({...Q}))),this.runs.clear();for(let Q of $.runs??[])this.runs.set(Q.id,{...Q});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").map((Q)=>Q.id)),this.outcomes.clear();for(let Q of $.outcomes??[])this.outcomes.set(Q.id,{...Q});this.outcomeFragments.clear();for(let Q of $.outcomeFragments??[])this.outcomeFragments.set(Q.id,{...Q});let J=Array.from(this.members.values()).filter((Q)=>Q.role==="lead");this.members.clear();for(let Q of J)this.members.set(Q.agentId,{...Q,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Q of $.members){if(Q.role!=="teammate")continue;this.members.set(Q.agentId,{agentId:Q.agentId,role:"teammate",description:Q.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,i8($.tasks.map((Q)=>Q.id),"task_")),this.messageCounter=Math.max(this.messageCounter,i8($.mailbox.map((Q)=>Q.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,i8($.missionLog.map((Q)=>Q.id),"log_")),this.runCounter=Math.max(this.runCounter,i8(($.runs??[]).map((Q)=>Q.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,i8(($.outcomes??[]).map((Q)=>Q.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,i8(($.outcomeFragments??[]).map((Q)=>Q.id),"frag_"))}isTeammateActive($){let J=this.members.get($);return!!J&&J.role==="teammate"&&!!J.agent}spawnTeammate({agentId:$,config:J}){let Q=this.members.get($);if(Q&&Q.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Q&&Q.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Z={...J,apiTimeoutMs:Fw,consumePendingUserMessage:()=>{let f=this.members.get($);if(!f||!f.pendingSteerMessage)return;let X=f.pendingSteerMessage;return f.pendingSteerMessage=void 0,X},onEvent:(f)=>{J.onEvent?.(f),this.emitEvent({type:I.AgentEvent,agentId:$,event:f}),this.trackMeaningfulEvent($,f)}},W=new K$(Z);if(Z.onEvent)W.subscribeEvents(Z.onEvent);let j={agentId:$,role:"teammate",description:J.role,status:"idle",agent:W,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:I.TeammateSpawned,agentId:$,role:J.role,teammate:{rolePrompt:J.systemPrompt,modelId:J.modelId,maxIterations:J.maxIterations,runtimeAgentId:W.getAgentId(),conversationId:W.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Q.agent?.abort()}catch(Z){if(!sW(Z))throw Z}Q.status="stopped",this.emitEvent({type:I.TeammateShutdown,agentId:$,reason:J})}updateTeammateConnections($){for(let J of this.members.values()){if(J.role!=="teammate"||!J.agent)continue;J.agent.updateConnection($)}}createTask($){let J=`task_${String(++this.taskCounter).padStart(4,"0")}`,Q=new Date,Z={id:J,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Q,updatedAt:Q,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(J,Z),this.emitEvent({type:I.TeamTaskUpdated,task:{...Z}}),{...Z}}claimTask($,J){let Q=this.requireTask($);return this.assertDependenciesResolved(Q),Q.status="in_progress",Q.assignee=J,Q.updatedAt=new Date,this.emitEvent({type:I.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:J,taskId:$,kind:"progress",summary:`Claimed task "${Q.title}"`}),{...Q}}blockTask($,J,Q){let Z=this.requireTask($);return Z.status="blocked",Z.updatedAt=new Date,Z.summary=Q,this.emitEvent({type:I.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"blocked",summary:Q}),{...Z}}completeTask($,J,Q){let Z=this.requireTask($);if(Z.status="completed",Z.updatedAt=new Date,Z.summary=Q,!Z.assignee)Z.assignee=J;return this.emitEvent({type:I.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"done",summary:Q}),{...Z}}async routeToTeammate($,J,Q){let Z=this.members.get($);if(!Z||Z.role!=="teammate"||!Z.agent)throw Error(`Teammate "${$}" was not found`);if(!Z.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Z.runningCount++,Z.status="running",this.emitEvent({type:I.TaskStart,agentId:$,message:J});try{let W=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=W.length>0?`${this.buildMailboxNotification(W)}
504
512
 
505
- ${f}`:f,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:k.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:k.TaskEnd,agentId:$,error:W,messages:Q.agent.getMessages()}),!dH(Q,W))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,f,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,Z),this.runQueue.push(Q),this.emitEvent({type:k.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(J,1),Z=Q?this.runs.get(Q):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,Q=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let W=this.runs.get(this.runQueue[Z]);if(!W||W.status!=="queued")continue;if(W.nextAttemptAt&&W.nextAttemptAt.getTime()>Q){if(!J||W.nextAttemptAt<J)J=W.nextAttemptAt;continue}if(W.priority>f)f=W.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===lH;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:k.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=f?Fq($):$.message,Z=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:k.RunCompleted,run:{...$}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=Z,$.endedAt=new Date;let W=this.members.get($.agentId);if(dH(W,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:k.RunCancelled,run:{...$},reason:Z});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:k.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await pH(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await pH($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:k.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let Q=this.members.get(J.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:k.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=lH,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:k.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:k.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,Q,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let W=this.members.get(f);if(!W)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:k.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,Q){let Z=[];for(let W of this.members.values()){if(W.agentId===$)continue;if(W.role==="lead")continue;Z.push(this.sendMessage($,W.agentId,f,J,Q?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:k.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(f.id,f),this.emitEvent({type:k.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:k.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:k.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let Q of f.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:k.OutcomeFinalized,outcome:{...f}}),{...f}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(f){if(!kW(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:k.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${Q}`}recordProgressStep($,f,J,Q=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let W=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!Q&&W<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
506
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function pH($){return new Promise((f)=>setTimeout(f,$))}function v2($,f){let J=0;for(let Q of $){if(!Q.startsWith(f))continue;let Z=Number.parseInt(Q.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function xW($,f){switch(f.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(f.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(f.type==="run_failed")J=f.run.error;else if(f.type==="run_cancelled"||f.type==="run_interrupted")J=f.run.error??f.reason;$.activeTeamRunIds.delete(f.run.id),$.pendingTeamRunUpdates.push({runId:f.run.id,agentId:f.run.agentId,taskId:f.run.taskId,status:f.type.replace("run_",""),error:J,iterations:f.run.result?.iterations}),o5($);break}default:break}}async function gW($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let Q=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await J("onTeamTaskProgress",$,f.agentId,Q,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function mW($,f,J,Q){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:m2({teamName:Z,sessionId:f,event:J}),summary:g2(Z,$.runtime.teamRuntime.exportState())}})}function ZJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function vW($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&ZJ($)}function o5($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function cW($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let f=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,f}if($.activeTeamRunIds.size===0)return[];await new Promise((f)=>{$.teamRunWaiters.push(f)})}}function uW($,f){let J=f.map((W)=>{let j=[`- ${W.runId} (${W.agentId}) -> ${W.status}`];if(W.taskId)j.push(` task=${W.taskId}`);if(typeof W.iterations==="number")j.push(` iterations=${W.iterations}`);if(W.error)j.push(` error=${W.error}`);return j.join("")}),Q=$.activeTeamRunIds.size,Z=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return WJ(`System-delivered teammate async run updates:
507
- ${J.join(`
513
+ ${J}`:J,f=Q?.continueConversation?await Z.agent.continue(j):await Z.agent.run(j);return this.emitEvent({type:I.TaskEnd,agentId:$,result:f}),this.recordProgressStep($,`Completed a delegated run (${f.iterations} iterations)`,Q?.taskId,!0),f}catch(W){let j=W instanceof Error?W:Error(String(W));if(this.emitEvent({type:I.TaskEnd,agentId:$,error:j,messages:Z.agent.getMessages()}),!LA(Z,j))this.appendMissionLog({agentId:$,taskId:Q?.taskId,kind:"error",summary:j.message});throw j}finally{if(Z.runningCount--,Z.runningCount<=0&&this.members.get($)?.status!=="stopped")Z.status="idle"}}startTeammateRun($,J,Q){let Z=`run_${String(++this.runCounter).padStart(5,"0")}`,W={id:Z,agentId:$,taskId:Q?.taskId,status:"queued",message:J,priority:Q?.priority??0,retryCount:0,maxRetries:Math.max(0,Q?.maxRetries??0),continueConversation:Q?.continueConversation,startedAt:new Date(0),leaseOwner:Q?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Z,W),this.runQueue.push(Z),this.emitEvent({type:I.RunQueued,run:{...W}}),this.dispatchQueuedRuns(),{...W}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let J=this.selectNextDispatchableQueuedRun();$=J.nextDelayedAttemptAt;let Q=J.index;if(Q<0){this.scheduleQueuedRunDispatch($);return}let[Z]=this.runQueue.splice(Q,1),W=Z?this.runs.get(Z):void 0;if(!W||W.status!=="queued")continue;this.executeQueuedRun(W)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,J=Number.NEGATIVE_INFINITY,Q,Z=Date.now();for(let W=0;W<this.runQueue.length;W++){let j=this.runs.get(this.runQueue[W]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Z){if(!Q||j.nextAttemptAt<Q)Q=j.nextAttemptAt;continue}if(j.priority>J)J=j.priority,$=W}return{index:$,nextDelayedAttemptAt:Q}}scheduleQueuedRunDispatch($){if(!$)return;let J=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},J)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let J of this.runs.values())if(J.status==="running")$++;return $}async executeQueuedRun($){let J=$.currentActivity===_A;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:I.RunStarted,run:{...$}});let Q=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Z=J?Dw($):$.message,W=await this.routeToTeammate($.agentId,Z,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=W,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:I.RunCompleted,run:{...$}})}catch(Z){let W=Z instanceof Error?Z.message:String(Z??"Unknown error");$.error=W,$.endedAt=new Date;let j=this.members.get($.agentId);if(LA(j,Z))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:I.RunCancelled,run:{...$},reason:W});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:I.RunFailed,run:{...$}})}finally{clearInterval(Q),this.dispatchQueuedRuns()}}listRuns($){let J=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Q)=>{if(!J&&!["running","queued"].includes(Q.status))return!1;if($?.status&&Q.status!==$.status)return!1;if($?.agentId&&Q.agentId!==$.agentId)return!1;return!0}).map((Q)=>({...Q}))}getRun($){let J=this.runs.get($);return J?{...J}:void 0}async awaitRun($,J=250){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);while(Q.status==="queued"||Q.status==="running")await OA(J);return{...Q}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((J)=>["queued","running"].includes(J.status)))await OA($);return this.listRuns()}cancelRun($,J){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);if(Q.status==="completed"||Q.status==="failed")return{...Q};Q.status="cancelled",Q.error=J,Q.endedAt=new Date,Q.currentActivity="cancelled";let Z=this.runQueue.indexOf($);if(Z>=0)this.runQueue.splice(Z,1);return this.emitEvent({type:I.RunCancelled,run:{...Q},reason:J}),{...Q}}recoverActiveRuns($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;let Z=this.members.get(Q.agentId);if(!Z||Z.role!=="teammate"||!Z.agent){Q.status="interrupted",Q.error="teammate_unavailable_after_recovery",Q.endedAt=new Date,Q.currentActivity="interrupted",this.emitEvent({type:I.RunInterrupted,run:{...Q},reason:Q.error});continue}let W=new Date;if(Q.status="queued",Q.error=void 0,Q.endedAt=void 0,Q.heartbeatAt=W,Q.lastProgressAt=W,Q.lastProgressMessage=$,Q.currentActivity=_A,!this.runQueue.includes(Q.id))this.runQueue.push(Q.id);J.push({...Q}),this.emitEvent({type:I.RunQueued,run:{...Q}})}return this.dispatchQueuedRuns(),J}markStaleRunsInterrupted($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;Q.status="interrupted",Q.error=$,Q.endedAt=new Date,Q.currentActivity="interrupted",J.push({...Q}),this.emitEvent({type:I.RunInterrupted,run:{...Q},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),J}sendMessage($,J,Q,Z,W){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(J);if(!j)throw Error(`Unknown recipient "${J}"`);let f={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:J,subject:Q,body:Z,taskId:W,sentAt:new Date};if(this.mailbox.push(f),this.emitEvent({type:I.TeamMessage,message:{...f}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Q}". Use the team_read_mailbox tool to read it at your convenience.`;return{...f}}broadcast($,J,Q,Z){let W=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;W.push(this.sendMessage($,j.agentId,J,Q,Z?.taskId))}return W}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let J={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(J);let Q=this.members.get($.agentId);if(Q)Q.lastMissionAt=Date.now(),Q.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:I.TeamMissionLog,entry:{...J}}),{...J}}createOutcome($){let J={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(J.id,J),this.emitEvent({type:I.OutcomeCreated,outcome:{...J}}),{...J}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let J=this.outcomes.get($.outcomeId);if(!J)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!J.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Q={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Q.id,Q),J.status==="draft")J.status="in_review";return this.emitEvent({type:I.OutcomeFragmentAttached,fragment:{...Q}}),{...Q}}reviewOutcomeFragment($){let J=this.outcomeFragments.get($.fragmentId);if(!J)throw Error(`Fragment "${$.fragmentId}" was not found`);return J.status=$.approved?"reviewed":"rejected",J.reviewedBy=$.reviewedBy,J.reviewedAt=new Date,this.emitEvent({type:I.OutcomeFragmentReviewed,fragment:{...J}}),{...J}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((J)=>J.outcomeId===$).map((J)=>({...J}))}finalizeOutcome($){let J=this.outcomes.get($);if(!J)throw Error(`Outcome "${$}" was not found`);let Q=this.listOutcomeFragments($);for(let Z of J.requiredSections)if(!Q.some((j)=>j.section===Z&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Z}" is missing a reviewed fragment.`);return J.status="finalized",J.finalizedAt=new Date,this.emitEvent({type:I.OutcomeFinalized,outcome:{...J}}),{...J}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(J){if(!sW(J))throw J}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,J]of this.members.entries())if(J.role==="teammate")this.members.delete($)}requireTask($){let J=this.tasks.get($);if(!J)throw Error(`Task "${$}" was not found`);return J}assertDependenciesResolved($){let J=this.getUnresolvedDependencies($);if(J.length>0)throw Error(`Task "${$.id}" is blocked by "${J[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((J)=>{let Q=this.tasks.get(J);return!Q||Q.status!=="completed"})}trackMeaningfulEvent($,J){if(this.recordRunActivityFromAgentEvent($,J),J.type==="iteration_end"&&J.hadToolCalls){this.recordProgressStep($,`Completed iteration ${J.iteration} with ${J.toolCallCount} tool call(s)`);return}if(J.type==="content_end"&&J.contentType==="tool"&&!J.error){this.recordProgressStep($,`Finished tool "${J.toolName??"unknown"}"`);return}if(J.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${J.iterations} iterations)`});return}if(J.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:J.error.message})}recordRunActivityFromAgentEvent($,J){let Q;switch(J.type){case"iteration_start":Q=`iteration_${J.iteration}_started`;break;case"content_start":if(J.contentType==="tool")Q=`running_tool_${J.toolName??"unknown"}`;break;case"content_end":if(J.contentType==="tool")Q=J.error?this.formatProgressErrorActivity(`tool_${J.toolName??"unknown"}_error`,J.error):`finished_tool_${J.toolName??"unknown"}`;break;case"done":Q="finalizing_response";break;case"error":Q=this.formatProgressErrorActivity("run_error",J.error.message);break;default:break}if(!Q)return;for(let Z of this.runs.values()){if(Z.agentId!==$||Z.status!=="running")continue;this.recordRunProgress(Z,Q)}}recordRunProgress($,J){let Q=new Date;$.heartbeatAt=Q,$.lastProgressAt=Q,$.lastProgressMessage=J,$.currentActivity=J,this.emitEvent({type:I.RunProgress,run:{...$},message:J})}formatProgressErrorActivity($,J){let Q=J.replace(/\s+/g," ").trim();if(Q.length===0)return $;let Z=Q.length>240?`${Q.slice(0,237).trimEnd()}...`:Q;return`${$}: ${Z}`}recordProgressStep($,J,Q,Z=!1){this.missionStepCounter++;let W=this.members.get($);if(!W)return;let j=this.missionStepCounter-W.lastMissionStep,f=Date.now()-W.lastMissionAt;if(!Z&&j<this.missionLogIntervalSteps&&f<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Q,kind:"progress",summary:J})}buildMailboxNotification($){if($.length===0)return"";let J=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Q of $)J.push(`--- Message from ${Q.fromAgentId} | subject: ${Q.subject} ---`),J.push(Q.body);return J.push("---"),J.join(`
514
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function OA($){return new Promise((J)=>setTimeout(J,$))}function i8($,J){let Q=0;for(let Z of $){if(!Z.startsWith(J))continue;let W=Number.parseInt(Z.slice(J.length),10);if(Number.isFinite(W))Q=Math.max(Q,W)}return Q}function tW($,J){switch(J.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(J.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Q;if(J.type==="run_failed")Q=J.run.error;else if(J.type==="run_cancelled"||J.type==="run_interrupted")Q=J.run.error??J.reason;$.activeTeamRunIds.delete(J.run.id),$.pendingTeamRunUpdates.push({runId:J.run.id,agentId:J.run.agentId,taskId:J.run.taskId,status:J.type.replace("run_",""),error:Q,iterations:J.run.result?.iterations}),X9($);break}default:break}}async function eW($,J,Q){switch(J.type){case"run_progress":await Q("onTeamTaskProgress",$,J.run.agentId,J.message,{kind:J.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(J.event.type==="content_start"&&J.event.contentType==="text"&&typeof J.event.text==="string"){let Z=J.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Z)await Q("onTeamTaskProgress",$,J.agentId,Z,{kind:"text"})}break;case"task_start":await Q("onTeamTaskStart",$,J.agentId,J.message);break;case"task_end":{if(J.error)await Q("onTeamTaskEnd",$,J.agentId,"failed",`[error] ${J.error.message}`,void 0,J.messages);else if(J.result?.finishReason==="aborted")await Q("onTeamTaskEnd",$,J.agentId,"cancelled","[done] aborted",J.result,J.result.messages);else await Q("onTeamTaskEnd",$,J.agentId,"completed",`[done] ${J.result?.finishReason??"completed"}`,J.result,J.result?.messages);break}default:break}}function $3($,J,Q,Z){if(!$.runtime.teamRuntime)return;let W=$.runtime.teamRuntime.getTeamName();Z({type:"team_progress",payload:{sessionId:J,teamName:W,lifecycle:r8({teamName:W,sessionId:J,event:Q}),summary:p8(W,$.runtime.teamRuntime.exportState())}})}function BJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function J3($,J){if($.aborting)return!1;if(!(J==="completed"||J==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&BJ($)}function X9($){let J=$.teamRunWaiters.splice(0);for(let Q of J)Q()}async function Q3($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let J=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,J}if($.activeTeamRunIds.size===0)return[];await new Promise((J)=>{$.teamRunWaiters.push(J)})}}function Z3($,J){let Q=J.map((j)=>{let f=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)f.push(` task=${j.taskId}`);if(typeof j.iterations==="number")f.push(` iterations=${j.iterations}`);if(j.error)f.push(` error=${j.error}`);return f.join("")}),Z=$.activeTeamRunIds.size,W=Z>0?`There are still ${Z} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return AJ(`System-delivered teammate async run updates:
515
+ ${Q.join(`
508
516
  `)}
509
517
 
510
- ${Z}`,$.config.mode)}function WJ($,f){return Pq($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var dW=4;class n1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,f={}){this.adapter=$;this.manifestStore=new EW($,f.messagesArtifactUploader,f.logger),this.teamChildren=new t5($,this.manifestStore,(J,Q,Z)=>this.toPersistedMessages(J,Q,Z),n1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?v6(f.messages,f,J):m6($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,f){this.manifestStore.writeSessionManifest($,f)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let f=$.startedAt??s(),J=$.sessionId.trim(),Q=J.length>0?J:`${Date.now()}_${Dq(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(Q),W=this.manifestStore.artifacts.sessionManifestPath(Q),j=Y4({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:f,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:f,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:X.prompt??null,metadata:P$(X.metadata),hookPath:"",messagesPath:Z,updatedAt:s()}),this.manifestStore.initializeMessagesFile(Q,Z,f),this.manifestStore.writeSessionManifest(W,X),{manifestPath:W,messagesPath:Z,manifest:X}}async updateSessionStatus($,f,J){let Q;if((await WA(()=>this.adapter.getSession($),async(W)=>{return Q=J0(f)?void 0:s(),this.adapter.updateSession({sessionId:$,status:f,endedAt:Q??null,exitCode:J0(f)?null:typeof J==="number"?J:null,expectedStatusLock:W.statusLock})},dW)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let f=0;f<dW;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let Q=J.metadata??void 0,Z=$.metadata!==void 0?P$($.metadata)??{}:P$(Q)??{},W=Zf(typeof Q?.title==="string"?Q.title:void 0),j=$.title!==void 0?Zf($.title):W??zZ($.prompt);if(j)Z.title=j;else delete Z.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:A,manifest:V}=this.manifestStore.readManifestFile($.sessionId);if(V){if($.prompt!==void 0)V.prompt=$.prompt??void 0;let H=$.metadata!==void 0?P$($.metadata)??{}:P$(V.metadata)??{};if(j)H.title=j;V.metadata=Object.keys(H).length>0?H:void 0,this.manifestStore.writeSessionManifest(A,V)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let Q=m6(f);return this.manifestStore.persistSessionMessages($,Q,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,Q,Z,W){return this.teamChildren.onTeamTaskEnd($,f,J,Q,Z,W)}onTeamTaskProgress($,f,J,Q){return this.teamChildren.onTeamTaskProgress($,f,J,Q)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if(J0($.status)===!1||this.isPidAlive($.pid))return $;let f=s(),J=n1.STALE_REASON;for(let Q=0;Q<dW;Q++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(J0(Z.status)===!1)return Z;let W={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:n1.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:W,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let X=ZA(Z,{status:"failed",endedAt:f,exitCode:1,metadata:W}),{path:Y}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(Y,X),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,n1.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:W,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let W=P$(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),X=Zf(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),Y=X?{...W??{},title:X}:W;return{...Z,metadata:Y}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),Q=0;for(let Z of J){let W=await this.reconcileDeadRunningSession(Z);if(W&&W.status!==Z.status)Q++}return Q}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(Q.map(async(Z)=>{await dZ(Z.cwd,Z.sessionId),N4(Z.messagesPath),N4(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await dZ(J.cwd,f),N4(J.messagesPath),N4(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)Q.add(Rq(Z));for(let Z of Q)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function pW(){return new Date().toISOString()}function tH($,f){let J=`${$}.tmp`;_q(J,`${JSON.stringify(f,null,2)}
511
- `,"utf8"),Lq(J,$)}class sH{sessionsDirPath;constructor($=zq()){this.sessionsDirPath=$}ensureSessionsDir(){if(!lW(this.sessionsDirPath))Uq(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return aH(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return aH(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!lW($))return{version:1,sessions:{}};try{let f=JSON.parse(nH($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){tH(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!lW($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(nH($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){tH(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:pW()};if($.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return f.sessions[$.sessionId]=Z,this.writeIndex(f),{updated:!0,statusLock:Z.statusLock}}async deleteSession($,f){let J=this.readIndex();if(!J.sessions[$])return!1;if(delete J.sessions[$],f){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===$)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest($){let f=this.readQueue();f.requests.push({id:f.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:pW()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),Q=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!Q)return;return Q.consumedAt=pW(),this.writeQueue(J),Q.task}}class rW extends n1{constructor($,f={}){super(new sH($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}var $B={};q($B,{CoreSessionService:()=>D1});import{existsSync as Oq,mkdirSync as Mq}from"node:fs";import{resolveSessionDataDir as Tq}from"@cline/shared/storage";var iW=`
518
+ ${W}`,$.config.mode)}function AJ($,J){return Uw($,J==="plan"?"plan":J==="yolo"?"yolo":"act")}var W3=4;class a1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,J={}){this.adapter=$;this.manifestStore=new iW($,J.messagesArtifactUploader,J.logger),this.teamChildren=new j9($,this.manifestStore,(Q,Z,W)=>this.toPersistedMessages(Q,Z,W),a1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,J,Q){if(!$)return;return J?a5(J.messages,J,Q):n5($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,J){this.manifestStore.writeSessionManifest($,J)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let J=$.startedAt??e(),Q=$.sessionId.trim(),Z=Q.length>0?Q:`${Date.now()}_${zw(5)}`,W=this.manifestStore.artifacts.sessionMessagesPath(Z),j=this.manifestStore.artifacts.sessionManifestPath(Z),f=D6({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Z,source:$.source,pid:$.pid,started_at:J,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:f,messages_path:W};return await this.adapter.upsertSession({sessionId:Z,source:$.source,pid:$.pid,startedAt:J,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:X.prompt??null,metadata:U$(X.metadata),hookPath:"",messagesPath:W,updatedAt:e()}),this.manifestStore.initializeMessagesFile(Z,W,J),this.manifestStore.writeSessionManifest(j,X),{manifestPath:j,messagesPath:W,manifest:X}}async updateSessionStatus($,J,Q){let Z;if((await hV(()=>this.adapter.getSession($),async(j)=>{return Z=j0(J)?void 0:e(),this.adapter.updateSession({sessionId:$,status:J,endedAt:Z??null,exitCode:j0(J)?null:typeof Q==="number"?Q:null,expectedStatusLock:j.statusLock})},W3)).updated){if(J==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Z}}return{updated:!1}}async updateSession($){for(let J=0;J<W3;J++){let Q=await this.adapter.getSession($.sessionId);if(!Q)return{updated:!1};let Z=Q.metadata??void 0,W=$.metadata!==void 0?U$($.metadata)??{}:U$(Z)??{},j=W2(typeof Z?.title==="string"?Z.title:void 0),f=$.title!==void 0?W2($.title):j??I7($.prompt);if(f)W.title=f;else delete W.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(W).length>0?W:null:void 0,title:f,expectedStatusLock:Q.statusLock})).updated)continue;let{path:V,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let B=$.metadata!==void 0?U$($.metadata)??{}:U$(H.metadata)??{};if(f)B.title=f;H.metadata=Object.keys(B).length>0?B:void 0,this.manifestStore.writeSessionManifest(V,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,J){return this.teamChildren.appendSubagentHookAudit(J),Promise.resolve()}persistSessionMessages($,J,Q){let Z=n5(J);return this.manifestStore.persistSessionMessages($,Z,Q)}applySubagentStatus($,J){return this.teamChildren.applySubagentStatus($,J)}applySubagentStatusBySessionId($,J){return this.teamChildren.applySubagentStatusBySessionId($,J)}applyStatusToRunningChildSessions($,J){return this.teamChildren.applyStatusToRunningChildSessions($,J)}onTeamTaskStart($,J,Q){return this.teamChildren.onTeamTaskStart($,J,Q)}onTeamTaskEnd($,J,Q,Z,W,j){return this.teamChildren.onTeamTaskEnd($,J,Q,Z,W,j)}onTeamTaskProgress($,J,Q,Z){return this.teamChildren.onTeamTaskProgress($,J,Q,Z)}handleSubAgentStart($,J){return this.teamChildren.handleSubAgentStart($,J)}handleSubAgentEnd($,J){return this.teamChildren.handleSubAgentEnd($,J)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(J){return typeof J==="object"&&J!==null&&"code"in J&&J.code==="EPERM"}}async reconcileDeadRunningSession($){if(j0($.status)===!1||this.isPidAlive($.pid))return $;let J=e(),Q=a1.STALE_REASON;for(let Z=0;Z<W3;Z++){let W=await this.adapter.getSession($.sessionId);if(!W)return;if(j0(W.status)===!1)return W;let j={...W.metadata??{},terminal_marker:Q,terminal_marker_at:J,terminal_marker_pid:W.pid,terminal_marker_source:a1.STALE_SOURCE},f=await this.adapter.updateSession({sessionId:W.sessionId,status:"failed",endedAt:J,exitCode:1,metadata:j,expectedStatusLock:W.statusLock});if(!f.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(W.sessionId,"failed");let X=bV(W,{status:"failed",endedAt:J,exitCode:1,metadata:j}),{path:Y}=this.manifestStore.readManifestFile(W.sessionId);return this.manifestStore.writeSessionManifest(Y,X),this.manifestStore.appendStaleSessionHookLog(J,W.sessionId,W.pid,Q,a1.STALE_SOURCE),{...W,status:"failed",endedAt:J,exitCode:1,metadata:j,statusLock:f.statusLock,updatedAt:J}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let J=Math.max(1,Math.floor($)),Q=Math.min(J*5,2000);return await this.reconcileDeadSessions(Q),(await this.adapter.listSessions({limit:Q})).slice(0,J).map((W)=>{let j=U$(W.metadata??void 0),f=this.manifestStore.readSessionManifest(W.sessionId),X=W2(typeof f?.metadata?.title==="string"?f.metadata.title:void 0),Y=X?{...j??{},title:X}:j;return{...W,metadata:Y}})}async reconcileDeadSessions($=2000){let J=Math.max(1,Math.floor($)),Q=(await Promise.all(["idle","running","pending"].map((W)=>this.adapter.listSessions({limit:J,status:W})))).flat(),Z=0;for(let W of Q){let j=await this.reconcileDeadRunningSession(W);if(j&&j.status!==W.status)Z++}return Z}async deleteSession($){let J=$.trim();if(!J)throw Error("session id is required");let Q=await this.adapter.getSession(J);if(!Q)return{deleted:!1};if(await this.adapter.deleteSession(J,!1),!Q.isSubagent){let Z=await this.adapter.listSessions({limit:2000,parentSessionId:J});await this.adapter.deleteSession(J,!0),await Promise.allSettled(Z.map(async(W)=>{await ZW(W.cwd,W.sessionId),b6(W.messagesPath),b6(this.manifestStore.artifacts.sessionManifestPath(W.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(W.sessionId)}))}if(await ZW(Q.cwd,J),b6(Q.messagesPath),b6(this.manifestStore.artifacts.sessionManifestPath(J,!1)),Q.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(J);else{let Z=new Set([this.manifestStore.artifacts.sessionArtifactsDir(J)]);for(let W of[Q.messagesPath])if(typeof W==="string"&&W.trim().length>0)Z.add(Rw(W));for(let W of Z)this.manifestStore.artifacts.removeDir(W)}return{deleted:!0}}}function f3(){return new Date().toISOString()}function NA($,J){let Q=`${$}.tmp`;Ow(Q,`${JSON.stringify(J,null,2)}
519
+ `,"utf8"),_w(Q,$)}class wA{sessionsDirPath;constructor($=Tw()){this.sessionsDirPath=$}ensureSessionsDir(){if(!j3(this.sessionsDirPath))Lw(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return PA(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return PA(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!j3($))return{version:1,sessions:{}};try{let J=JSON.parse(qA($,"utf8"));if(J?.version===1&&J.sessions)return J}catch{}return{version:1,sessions:{}}}writeIndex($){NA(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!j3($))return{version:1,nextId:1,requests:[]};try{let J=JSON.parse(qA($,"utf8"));if(J?.version===1&&typeof J.nextId==="number"&&Array.isArray(J.requests))return J}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){NA(this.spawnQueuePath(),$)}async upsertSession($){let J=this.readIndex();J.sessions[$.sessionId]=$,this.writeIndex(J)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((J)=>$.parentSessionId!==void 0?J.parentSessionId===$.parentSessionId:!0).filter((J)=>$.status!==void 0?J.status===$.status:!0).sort((J,Q)=>Q.startedAt.localeCompare(J.startedAt)).slice(0,$.limit)}async updateSession($){let J=this.readIndex(),Q=J.sessions[$.sessionId];if(!Q)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Q.statusLock};let Z=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Q.statusLock,W={...Q,status:$.status??Q.status,endedAt:$.endedAt!==void 0?$.endedAt:Q.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Q.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Q.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Q.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Q.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Q.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Q.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Q.conversationId??null,statusLock:Z,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Q.isSubagent,updatedAt:f3()};if($.setRunning)W.status="running",W.endedAt=null,W.exitCode=null;return J.sessions[$.sessionId]=W,this.writeIndex(J),{updated:!0,statusLock:W.statusLock}}async deleteSession($,J){let Q=this.readIndex();if(!Q.sessions[$])return!1;if(delete Q.sessions[$],J){for(let W of Object.values(Q.sessions))if(W.parentSessionId===$)delete Q.sessions[W.sessionId]}return this.writeIndex(Q),!0}async enqueueSpawnRequest($){let J=this.readQueue();J.requests.push({id:J.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:f3()}),J.nextId+=1,this.writeQueue(J)}async claimSpawnRequest($,J){let Q=this.readQueue(),Z=Q.requests.find((W)=>W.rootSessionId===$&&W.parentAgentId===J&&!W.consumedAt);if(!Z)return;return Z.consumedAt=f3(),this.writeQueue(Q),Z.task}}class X3 extends a1{constructor($,J={}){super(new wA($),J)}ensureSessionsDir(){return super.ensureSessionsDir()}}var yA={};w(yA,{CoreSessionService:()=>z1});import{existsSync as Mw,mkdirSync as qw}from"node:fs";import{resolveSessionDataDir as Pw}from"@cline/shared/storage";var Y3=`
512
520
  session_id AS sessionId,
513
521
  source,
514
522
  pid,
@@ -535,32 +543,33 @@ ${Z}`,$.config.mode)}function WJ($,f){return Pq($,f==="plan"?"plan":f==="yolo"?"
535
543
  metadata_json AS metadata,
536
544
  hook_path AS hookPath,
537
545
  messages_path AS messagesPath,
538
- updated_at AS updatedAt`;function nW($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let f=$.metadata;if(typeof f==="string"&&f.trim())try{let J=JSON.parse(f);$.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{$.metadata=null}else $.metadata=null;return $}function aW($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function oH($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class eH{store;sessionsDirPath;constructor($,f=Tq()){this.store=$;this.sessionsDirPath=f}ensureSessionsDir(){if(!Oq(this.sessionsDirPath))Mq(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
546
+ updated_at AS updatedAt`;function V3($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let J=$.metadata;if(typeof J==="string"&&J.trim())try{let Q=JSON.parse(J);$.metadata=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{$.metadata=null}else $.metadata=null;return $}function H3($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function SA($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class CA{store;sessionsDirPath;constructor($,J=Pw()){this.store=$;this.sessionsDirPath=J}ensureSessionsDir(){if(!Mw(this.sessionsDirPath))qw(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
539
547
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
540
548
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
541
549
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
542
550
  metadata_json, transcript_path, hook_path, messages_path, updated_at
543
- ) 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,aW($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let f=this.store.queryOne(`SELECT ${iW} FROM sessions WHERE session_id = ?`,[$]);return f?nW(f):void 0}async listSessions($){let f=[],J=[];if($.parentSessionId)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.status)f.push("status = ?"),J.push($.status);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${iW}
551
+ ) 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,H3($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let J=this.store.queryOne(`SELECT ${Y3} FROM sessions WHERE session_id = ?`,[$]);return J?V3(J):void 0}async listSessions($){let J=[],Q=[];if($.parentSessionId)J.push("parent_session_id = ?"),Q.push($.parentSessionId);if($.status)J.push("status = ?"),Q.push($.status);let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${Y3}
544
552
  FROM sessions
545
- ${Q}
553
+ ${Z}
546
554
  ORDER BY started_at DESC
547
- LIMIT ?`,[...J,$.limit]).map(nW)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
555
+ LIMIT ?`,[...Q,$.limit]).map(V3)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
548
556
  SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
549
557
  parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
550
558
  prompt = COALESCE(prompt, ?)
551
- WHERE session_id = ? AND status_lock = ?`,[s(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let f=[],J=[];if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt??null);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push(aW($.metadata));if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId??null);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId??null);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId??null);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId??null);if(f.length===0){let j=await this.getSession($.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,f.push("status_lock = ?"),J.push(Q);f.push("updated_at = ?"),J.push(s());let Z=`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`;if(J.push($.sessionId),$.expectedStatusLock!==void 0)Z+=" AND status_lock = ?",J.push($.expectedStatusLock);if((this.store.run(Z,J).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,f){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
552
- VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,s()])}async claimSpawnRequest($,f){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
559
+ WHERE session_id = ? AND status_lock = ?`,[e(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let J=[],Q=[];if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.endedAt!==void 0)J.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)J.push("exit_code = ?"),Q.push($.exitCode);if($.prompt!==void 0)J.push("prompt = ?"),Q.push($.prompt??null);if($.metadata!==void 0)J.push("metadata_json = ?"),Q.push(H3($.metadata));if($.parentSessionId!==void 0)J.push("parent_session_id = ?"),Q.push($.parentSessionId??null);if($.parentAgentId!==void 0)J.push("parent_agent_id = ?"),Q.push($.parentAgentId??null);if($.agentId!==void 0)J.push("agent_id = ?"),Q.push($.agentId??null);if($.conversationId!==void 0)J.push("conversation_id = ?"),Q.push($.conversationId??null);if(J.length===0){let f=await this.getSession($.sessionId);return{updated:!!f,statusLock:f?.statusLock??0}}let Z=0;if($.expectedStatusLock!==void 0)Z=$.expectedStatusLock+1,J.push("status_lock = ?"),Q.push(Z);J.push("updated_at = ?"),Q.push(e());let W=`UPDATE sessions SET ${J.join(", ")} WHERE session_id = ?`;if(Q.push($.sessionId),$.expectedStatusLock!==void 0)W+=" AND status_lock = ?",Q.push($.expectedStatusLock);if((this.store.run(W,Q).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Z=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Z}}async deleteSession($,J){let Q=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
560
+ VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,e()])}async claimSpawnRequest($,J){let Q=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
553
561
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
554
- ORDER BY id ASC LIMIT 1`,[$,f]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),J.id]),J.task??void 0}}class D1 extends n1{store;constructor($,f={}){super(new eH($,f.sessionArtifactsDir),f);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
562
+ ORDER BY id ASC LIMIT 1`,[$,J]);if(!Q||typeof Q.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[e(),Q.id]),Q.task??void 0}}class z1 extends a1{store;constructor($,J={}){super(new CA($,J.sessionArtifactsDir),J);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
555
563
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
556
564
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
557
565
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
558
566
  metadata_json, transcript_path, hook_path, messages_path, updated_at
559
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,s()])}}function Nq($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let f=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(f==="local"||f==="hub"||f==="remote")return f;return"auto"}var jJ,XJ;function qq($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;W6(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function wq($){await $.reconcileDeadSessions?.().catch(()=>{})}function QB($){try{let f=new P1;return f.init(),new D1(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),JB($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new rW(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function fB($,f,J){return new U1({sessionService:J??$.sessionService??QB($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function tW($){if(jJ)return jJ;if(XJ)return await XJ;return XJ=(async()=>{return jJ=QB($),await wq(jJ),jJ})().finally(()=>{XJ=void 0}),await XJ}async function u2($){let f=S1($.distinctId);$.telemetry?.setDistinctId(f);let J=Nq($);if(qq(J,$),J==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new k2({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let Q=$.hub?.endpoint?.trim(),Z=Q||await u$({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:Q||void 0}),new r1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let Q=await O8({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let Z=new r1({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(W){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:W}),JB($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:W,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),fB($,f)}return fB($,f)}var jB={};q(jB,{NoOpFeatureFlagsProvider:()=>Tf,FeatureFlagsService:()=>Mf});import{FEATURE_FLAGS as WB,FeatureFlagDefaultValue as sW}from"@cline/shared";var Cq=3600000;class Mf{provider;telemetry;logger;cacheTtlMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??Cq,this.context={...$.context??{}}}setContext($){this.context={...$}}async poll($=this.context.userId??null){let f=Date.now();if(f-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===$)return}let J=this.cacheInfo;this.cacheInfo={updateTime:f,userId:$||null};try{let Q=await this.provider.getAllFlagsAndPayloads({flagKeys:WB.length>0?WB:void 0,context:{...this.context,userId:$}});if(this.cacheInfo.userId!==$)return;this.cacheInfo.flagsPayload=Q;let Z=new Map;for(let W of this.getReturnedFlagKeys(Q)){let j=this.getFeatureFlag(W);Z.set(W,j??!1)}this.cache=Z}catch(Q){if(this.cacheInfo.userId!==$)return;throw this.cacheInfo=J.updateTime?J:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:Q}),Q}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}getFeatureFlag($){try{let f=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],J=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=f??J??sW[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:g.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:J}});return Q}catch(f){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:f}),sW[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??sW[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,f){if(process.env.IS_TEST==="true")this.cache.set($,f)}async dispose(){await this.provider.dispose()}}class Tf{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}G8();class YJ{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,Q,Z,W,j,X,Y,A){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=Q,this.capabilities=Z,this.logger=W,this.telemetry=j,this.distinctId=X,this.featureFlags=Y,this.settings=eV($),this.pendingPrompts=$H($),this.automation=new WW(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=A?new a4({workspaceRoot:A.workspaceRoot??process.cwd(),specs:{cronSpecsDir:A.cronSpecsDir??A.cronDir,scope:HV(A.cronScope),workspaceRoot:A.workspaceRoot},runtimeHandlers:BV({host:$,getExtensionContext:()=>T5({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:A.dbPath,logger:A.logger,pollIntervalMs:A.pollIntervalMs,claimLeaseSeconds:A.claimLeaseSeconds,globalMaxConcurrency:A.globalMaxConcurrency,watcherDebounceMs:A.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((V)=>{if(V.type!=="ended")return;this.disposeSessionBootstrap(V.payload.sessionId)})}static async create($={}){let f=S1($.distinctId),J=L0($.capabilities),Q={...$,capabilities:J,distinctId:f},Z=await u2(Q),W=VV($.automation),j=new Mf({provider:$.featureFlags??new Tf,telemetry:$.telemetry,logger:$.logger,context:{distinctId:f,clientName:$.clientName}}),X=new YJ(Z,$.clientName,Z.runtimeAddress,$.prepare,J,$.logger,$.telemetry,f,j,W?{...W,logger:$.logger}:void 0);if(W&&W.autoStart!==!1)await X.automation.start();return X}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=fH($),J=await this.prepare?.(f);try{let Q=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(RW(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(W)=>T5({automationService:this.automationService,automation:this.automation,context:W,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return JH({input:Q,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(Q){throw await Promise.resolve(J?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{await this.featureFlags.dispose().catch((J)=>{this.logger?.error?.("Error disposing feature flags provider",{error:J})}),this.unsubscribeBootstrapCleanup();let f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await r5(this.host,$);list=async($=200,f={})=>await this.listHistory({...f,limit:$});delete=async($)=>{let f=await this.host.deleteSession($);if(f)await this.disposeSessionBootstrap($);return f};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let f=$.start?RW($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>T5({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:f})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,f){return this.host.subscribe($,f)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var YB={};q(YB,{resolvePluginSkillDirectoriesFromPaths:()=>Yf,resolvePluginConfigSearchPaths:()=>G4,resolveAndLoadAgentPlugins:()=>D2,resolveAgentPluginPaths:()=>Xf,loadAgentPluginsFromPathsWithDiagnostics:()=>jf,loadAgentPluginsFromPaths:()=>u6,loadAgentPluginFromPath:()=>B4,discoverPluginModulePaths:()=>F4});var HB={};q(HB,{toHookConfigFileName:()=>D4,runSubprocessEvent:()=>d2,runHook:()=>p2,resolveHooksConfigSearchPaths:()=>P4,parseHookEventPayload:()=>l2,mergeAgentHooks:()=>Bf,listHookConfigFiles:()=>U$,createSubprocessHooks:()=>f9,createHookConfigFileHooks:()=>U4,createHookConfigFileExtension:()=>z2,createHookAuditHooks:()=>_2,createAgentHooksExtension:()=>U2,HookEventPayloadSchema:()=>$9,HookEventNameSchema:()=>e5,HookConfigFileName:()=>L2,HOOK_CONFIG_FILE_EVENT_MAP:()=>R4,HOOKS_CONFIG_DIRECTORY_NAME:()=>a6});import{HookEventNameSchema as e5,HookEventPayloadSchema as $9,parseHookEventPayload as l2,resolveHookSessionContext as Iq}from"@cline/shared";import{z as Nf}from"zod";import{spawn as yq}from"node:child_process";import{augmentNodeCommandForDebug as Sq,withResolvedClineBuildEnv as Eq}from"@cline/shared";function hq($){let f=$.trim();if(!f)return{};let Q=f.split(`
560
- `).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function bq($,f){let J=$ instanceof Error?$:Error(String($)),Q=J,Z=f.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function kq($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end(f,(j)=>{if(J.off("error",W),j){let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function d2($,f){let J=Sq(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!f.detached,Z=yq(J[0],J.slice(1),{cwd:f.cwd,env:Eq(f.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),W=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(G)=>{K(bq(G,J))})});if(await kq(Z,JSON.stringify($)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",Y="",A=!1,V;Z.stdout.on("data",(B)=>{X+=B.toString()}),Z.stderr.on("data",(B)=>{Y+=B.toString()});let H=new Promise((B)=>{if((f.timeoutMs??0)>0)V=setTimeout(()=>{A=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(V)clearTimeout(V);let{parsedJson:G,parseError:R}=hq(X);B({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:A})})});return await Promise.race([H,j])}var xq=Nf.object({contextModification:Nf.string().optional(),cancel:Nf.boolean().optional(),review:Nf.boolean().optional(),errorMessage:Nf.string().optional(),context:Nf.string().optional(),overrideInput:Nf.unknown().optional()}).passthrough();var gq=["agent","hook"];async function p2($,f={}){let J=f.command??gq;return await d2($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function VB($){return $ instanceof Error?$:Error(String($))}function mq($){if(!$||typeof $!=="object")return;let f=xq.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function AB($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))if(typeof Q==="string")f[J]=Q;else f[J]=JSON.stringify(Q);return f}function a1($,f,J){let Q=J.env??process.env,Z=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",W=J.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:Iq(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function vq($){return{name:$.name,message:$.message,stack:$.stack}}function cq($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function uq($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function dq($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function lq($){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 pq($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function qf($,f){try{let J=await p2($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(VB(J),$)}}function f9($={}){return{hooks:{beforeRun:async(X)=>{let Y=uq(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let V={...a1("agent_resume",Y,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await qf(V,$)}else{let V={...a1("agent_start",Y,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await qf(V,$)}return},beforeTool:async(X)=>{let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},A={...a1("tool_call",Y,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:AB(X.input)}};try{let V=await p2(A,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:A,result:V,detached:!1}),V?.timedOut)throw Error("tool_call hook command timed out");if(V?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${V.parseError}`);return pq(mq(V?.parsedJson))}catch(V){$.onDispatchError?.(VB(V),A);return}},afterTool:async(X)=>{let Y=lq(X),A={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...a1("tool_result",A,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:Y,postToolUse:{toolName:Y.name,parameters:AB(Y.input),result:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output),success:!Y.error,executionTimeMs:Y.durationMs}};await qf(V,$);return},afterRun:async({snapshot:X,result:Y})=>{let A={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(Y.status==="completed"){let B={...a1("agent_end",A,$),hookName:"agent_end",iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status},taskComplete:{taskMetadata:{}}};await qf(B,$);return}let V=Y.status==="aborted"||cq(Y.error?.message)?"agent_abort":"agent_error",H=V==="agent_error"?{...a1(V,A,$),hookName:V,iteration:Y.iterations,error:vq(Y.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...a1(V,A,$),hookName:V,reason:Y.error?.message,taskCancel:{taskMetadata:{}}};await qf(H,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},A={...a1("prompt_submit",Y,$),hookName:"prompt_submit",userPromptSubmit:{prompt:dq(X.message.content),attachments:[]}};await qf(A,$)}},shutdown:async({agentId:X,conversationId:Y,parentAgentId:A,reason:V})=>{let H={...a1("session_shutdown",{agentId:X,conversationId:Y,parentAgentId:A},$),hookName:"session_shutdown",reason:V};await qf(H,$)}}}oW();var KB={};q(KB,{registerRemoteConfigSessionBlobUpload:()=>Z9,readRemoteConfigSessionBlobUploadMetadata:()=>eW,prepareRemoteConfigCoreIntegration:()=>f7,createRemoteConfigSessionMessagesArtifactUploader:()=>$7,buildRemoteConfigSessionBlobUploadMetadata:()=>J9,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>Q9});import{buildRemoteConfigSessionBlobUploadMetadata as J9,clearRemoteConfigSessionBlobUpload as rq,createClineTelemetryServiceConfig as iq,createSessionId as nq,createRemoteConfigSessionMessagesArtifactUploader as aq,prepareRemoteConfigRuntime as tq,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as Q9,readRemoteConfigSessionBlobUploadMetadata as eW,registerRemoteConfigSessionBlobUpload as Z9}from"@cline/shared";function sq($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return E1(iq(J)).telemetry}function $7(){let $=aq();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function f7($){let f=await tq($),J=sq(f,$),Q=[f.pluginDefinition],Z=f.claims?.subject,W=J9(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:Q,telemetry:J,applyToStartSessionInput(X){let Y=X.config.extensions??[],A=X.config.telemetry,V=W?X.config.sessionId?.trim()||nq():X.config.sessionId;if(V&&W)j=V;let H=V&&W?Z9(V,f.bundle?.remoteConfig,Z):void 0,B=H?{...X.sessionMetadata??{},[Q9]:H}:X.sessionMetadata;return{...X,...B?{sessionMetadata:B}:{},config:{...X.config,...V?{sessionId:V}:{},extensions:[...Y,...Q],telemetry:J??A}}},async dispose(){if(j)rq(j)}}}var LB={};q(LB,{createTeamName:()=>X9,DefaultRuntimeBuilder:()=>n2});import{hasRuntimeConfigExtension as Hw}from"@cline/shared";import{nanoid as Bw}from"nanoid";j1();var UB={};q(UB,{createLocalTeamStore:()=>W7,SqliteTeamStore:()=>wf,FileTeamStore:()=>AJ});import{appendFileSync as oq,existsSync as r2,mkdirSync as GB,readdirSync as eq,readFileSync as FB,renameSync as $w,writeFileSync as fw}from"node:fs";import{join as J7}from"node:path";import{resolveTeamDataDir as Jw}from"@cline/shared/storage";function PB(){return new Date().toISOString()}function Q7($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function RB($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class AJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??Jw()}init(){this.ensureTeamDir()}listTeamNames(){if(!r2(this.teamDirPath))return[];return eq(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>r2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?RB(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!r2(J))return[];return FB(J,"utf8").split(`
561
- `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,f)}loadRuntime($){let f=this.readEnvelope($);return{state:f?.teamState?RB(f.teamState):void 0,teammates:f?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,f){this.ensureTeamSubdir($),oq(this.historyPath($),`${JSON.stringify({ts:PB(),eventType:f.type,payload:f})}
562
- `,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let Q={version:1,updatedAt:PB(),teamState:f,teammates:J},Z=this.statePath($),W=`${Z}.tmp`;fw(W,`${JSON.stringify(Q,null,2)}
563
- `,"utf8"),$w(W,Z)}markInProgressRunsInterrupted($,f){let J=this.readEnvelope($);if(!J?.teamState?.runs?.length)return[];let Q=J.teamState.runs.filter((W)=>W.status==="queued"||W.status==="running").map((W)=>W.id);if(Q.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((W)=>W.status==="queued"||W.status==="running"?{...W,status:"interrupted",error:f,endedAt:Z}:W)},this.persistRuntime($,J.teamState,J.teammates),Q}ensureTeamDir(){if(!r2(this.teamDirPath))GB(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let f=J7(this.ensureTeamDir(),Q7($));if(!r2(f))GB(f,{recursive:!0});return f}statePath($){return J7(this.ensureTeamDir(),Q7($),"state.json")}historyPath($){return J7(this.ensureTeamDir(),Q7($),"task-history.jsonl")}readEnvelope($){let f=this.statePath($);if(!r2(f))return;try{let J=JSON.parse(FB(f,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as Qw,mkdirSync as Zw}from"node:fs";import{join as Ww}from"node:path";import{safeJsonParse as DB}from"@cline/shared";import{loadSqliteDb as jw,nowIso as Z7}from"@cline/shared/db";import{resolveDbDataDir as Xw}from"@cline/shared/storage";function Yw(){return Xw()}function i2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Aw($){let f=DB($);if(!Array.isArray(f))return[];let J=[];for(let Q of f){if(!Q||typeof Q!=="object")continue;let Z=Q,W=Z.agentId,j=Z.rolePrompt;if(typeof W!=="string"||!W.trim())continue;if(typeof j!=="string"||!j.trim())continue;let X={agentId:W.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())X.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))X.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(X)}return J}function Vw($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class wf{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??Yw()}init(){this.getRawDb()}ensureTeamDir(){if(!Qw(this.teamDirPath))Zw(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Ww(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=jw(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
567
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,e()])}}function Nw($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let J=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(J==="local"||J==="hub"||J==="remote")return J;return"auto"}var KJ,GJ;function ww($,J){if($!=="auto"&&$!=="hub")return;if(J.hub?.endpoint?.trim())return;K5(J.hub?.workspaceRoot?.trim()||J.hub?.cwd?.trim()||process.cwd())}async function Sw($){await $.reconcileDeadSessions?.().catch(()=>{})}function hA($){try{let J=new U1;return J.init(),new z1(J,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(J){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),bA($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:J,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new X3(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function EA($,J,Q){return new L1({sessionService:Q??$.sessionService??hA($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:J,fetch:$.fetch})}async function B3($){if(KJ)return KJ;if(GJ)return await GJ;return GJ=(async()=>{return KJ=hA($),await Sw(KJ),KJ})().finally(()=>{GJ=void 0}),await GJ}async function a8($){let J=S0($.distinctId);$.telemetry?.setDistinctId(J);let Q=Nw($);if(ww(Q,$),Q==="remote"){let Z=$.remote?.endpoint?.trim();if(!Z)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Z}),new u8({endpoint:Z,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Q==="hub"){let Z=$.hub?.endpoint?.trim(),W=Z||await u$({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!W)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:W,explicitEndpoint:Z||void 0}),new i1({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Q==="auto"){let Z=await S4({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Z){$.logger?.log("Using discovered local hub runtime host",{url:Z});let W=new i1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await W.connect(),W}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),bA($.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"}),EA($,J)}return EA($,J)}var gA={};w(gA,{NoOpFeatureFlagsProvider:()=>q2,FeatureFlagsService:()=>M2});import{existsSync as Cw,mkdirSync as yw,readFileSync as Ew,writeFileSync as bw}from"node:fs";import{dirname as hw}from"node:path";import{FEATURE_FLAGS as IA,FeatureFlagDefaultValue as A3}from"@cline/shared";var kw=3600000,Iw=604800000,xA=1;class M2{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??kw,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Iw,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let J=$??this.context.userId??null,Q=Date.now();if(Q-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===J)return}let Z=this.cacheInfo;this.cacheInfo={updateTime:Q,userId:J||null};try{let W=await this.provider.getAllFlagsAndPayloads({flagKeys:IA.length>0?IA:void 0,context:{...this.context,userId:J}});if(this.cacheInfo.userId!==J)return;this.cacheInfo.flagsPayload=W,this.rebuildCacheFromSnapshot(W),this.writePersistentCache()}catch(W){if(this.cacheInfo.userId!==J)return;throw this.cacheInfo=Z.updateTime?Z:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:W}),W}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((J)=>this.isFeatureFlagPayload(J));if(typeof $==="object")return Object.values($).every((J)=>this.isFeatureFlagPayload(J));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=Object.entries($).filter(([,Z])=>this.isFeatureFlagPayload(Z));if(J.length===0)return;let Q={};for(let[Z,W]of J)Q[Z]=W;return Q}readPersistentCache(){try{if(!this.cacheFilePath||!Cw(this.cacheFilePath))return;let $=JSON.parse(Ew(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let J=$;if(J.version!==xA||typeof J.updatedAt!=="number"||!Number.isFinite(J.updatedAt)||Date.now()-J.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:J.updatedAt,userId:J.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(J.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(J.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;yw(hw(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),J={version:xA,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};bw(this.cacheFilePath,`${JSON.stringify(J,null,2)}
568
+ `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let J=new Map;for(let Q of this.getReturnedFlagKeys($)){let Z=this.getFeatureFlag(Q);J.set(Q,Z??!1)}this.cache=J}getFeatureFlag($){try{let J=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Q=this.cacheInfo.flagsPayload?.featureFlags?.[$],Z=J??Q??A3[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Z)this.telemetry?.capture({event:g.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Q}});return Z}catch(J){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:J}),A3[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??A3[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,J){if(process.env.IS_TEST==="true")this.cache.set($,J)}async dispose(){await this.provider.dispose()}}class q2{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}l2();class FJ{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,J,Q,Z,W,j,f,X,Y,V){this.clientName=J,this.runtimeAddress=Q,this.host=$,this.prepare=Z,this.capabilities=W,this.logger=j,this.telemetry=f,this.distinctId=X,this.featureFlags=Y,this.settings=CB($),this.pendingPrompts=yB($),this.automation=new zW(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=V?new QJ({workspaceRoot:V.workspaceRoot??process.cwd(),specs:{cronSpecsDir:V.cronSpecsDir??V.cronDir,scope:vH(V.cronScope),workspaceRoot:V.workspaceRoot},runtimeHandlers:cH({host:$,getExtensionContext:()=>bQ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:V.dbPath,logger:V.logger,pollIntervalMs:V.pollIntervalMs,claimLeaseSeconds:V.claimLeaseSeconds,globalMaxConcurrency:V.globalMaxConcurrency,watcherDebounceMs:V.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let J=S0($.distinctId),Q=_0($.capabilities),Z={...$,capabilities:Q,distinctId:J},W=await a8(Z),j=mH($.automation),f=$.featureFlags||new M2({provider:new q2,telemetry:$.telemetry,logger:$.logger,context:{distinctId:J,clientName:$.clientName}}),X=new FJ(W,$.clientName,W.runtimeAddress,$.prepare,Q,$.logger,$.telemetry,J,f,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await X.automation.start();return X}async disposeSessionBootstrap($){let J=this.activeSessionBootstraps.get($);if(!J)return;this.activeSessionBootstraps.delete($),await Promise.resolve(J.dispose?.())}async start($){let J=EB($),Q=await this.prepare?.(J);try{let Z=Q?await Q.applyToStartSessionInput(J):J,W=await this.host.startSession(EW(Z,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>bQ({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Q)if(await this.host.getSession(W.sessionId))this.activeSessionBootstraps.set(W.sessionId,Q);else await Promise.resolve(Q.dispose?.());return bB({input:Z,sessionId:W.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),W}catch(Z){throw await Promise.resolve(Q?.dispose?.()),Z}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let J=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(J.map((Q)=>this.disposeSessionBootstrap(Q)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await J9(this.host,$);list=async($=200,J={})=>await this.listHistory({...J,limit:$});delete=async($)=>{let J=await this.host.deleteSession($);if(J)await this.disposeSessionBootstrap($);return J};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let J=$.start?EW($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>bQ({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:J})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,J){return this.host.subscribe($,J)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var vA={};w(vA,{resolvePluginSkillDirectoriesFromPaths:()=>Y2,resolvePluginConfigSearchPaths:()=>O6,resolveAndLoadAgentPlugins:()=>T8,resolveAgentPluginPaths:()=>X2,loadAgentPluginsFromPathsWithDiagnostics:()=>f2,loadAgentPluginsFromPaths:()=>o5,loadAgentPluginFromPath:()=>L6,discoverPluginModulePaths:()=>T6});var dA={};w(dA,{toHookConfigFileName:()=>P6,runSubprocessEvent:()=>s8,runHook:()=>t8,resolveHooksConfigSearchPaths:()=>M6,parseHookEventPayload:()=>o8,mergeAgentHooks:()=>A2,listHookConfigFiles:()=>L$,createSubprocessHooks:()=>H9,createHookConfigFileHooks:()=>N6,createHookConfigFileExtension:()=>N8,createHookAuditHooks:()=>P8,createAgentHooksExtension:()=>M8,HookEventPayloadSchema:()=>V9,HookEventNameSchema:()=>Y9,HookConfigFileName:()=>q8,HOOK_CONFIG_FILE_EVENT_MAP:()=>q6,HOOKS_CONFIG_DIRECTORY_NAME:()=>ZQ});import{HookEventNameSchema as Y9,HookEventPayloadSchema as V9,parseHookEventPayload as o8,resolveHookSessionContext as dw}from"@cline/shared";import{z as P2}from"zod";import{spawn as xw}from"node:child_process";import{augmentNodeCommandForDebug as gw,withResolvedClineBuildEnv as mw}from"@cline/shared";function vw($){let J=$.trim();if(!J)return{};let Z=J.split(`
569
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function cw($,J){let Q=$ instanceof Error?$:Error(String($)),Z=Q,W=J.join(" ");if(Z.code==="EACCES")return Error(`Failed to execute hook command "${W}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${W}": ${Q.message}`)}async function uw($,J){let Q=$.stdin;if(!Q)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Z,W)=>{let j=(f)=>{Q.off("error",j);let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f)};Q.once("error",j),Q.end(J,(f)=>{if(Q.off("error",j),f){let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f);return}Z()})})}async function s8($,J){let Q=gw(J.command,{env:J.env,debugRole:"hook"});if(!Array.isArray(Q)||Q.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Z=!!J.detached,W=xw(Q[0],Q.slice(1),{cwd:J.cwd,env:mw(J.env),stdio:Z?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Z,windowsHide:!0}),j=new Promise((A)=>{W.once("spawn",()=>{try{J.onSpawn?.({command:Q,pid:W.pid??void 0,detached:Z})}catch{}A()})}),f=new Promise((A,K)=>{W.once("error",(G)=>{K(cw(G,Q))})});if(await uw(W,JSON.stringify($)),Z){await Promise.race([j,f]),W.unref();return}if(!W.stdout||!W.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",Y="",V=!1,H;W.stdout.on("data",(A)=>{X+=A.toString()}),W.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,W.kill("SIGKILL")},J.timeoutMs);W.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=vw(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,f])}var lw=P2.object({contextModification:P2.string().optional(),cancel:P2.boolean().optional(),review:P2.boolean().optional(),errorMessage:P2.string().optional(),context:P2.string().optional(),overrideInput:P2.unknown().optional()}).passthrough();var pw=["agent","hook"];async function t8($,J={}){let Q=J.command??pw;return await s8($,{command:Q,cwd:J.cwd,env:J.env,detached:J.detached,timeoutMs:J.timeoutMs,onSpawn:J.onSpawn})}function uA($){return $ instanceof Error?$:Error(String($))}function rw($){if(!$||typeof $!=="object")return;let J=lw.safeParse($);if(!J.success)return;let Q=J.data;if(!(("cancel"in Q)||("review"in Q)||("context"in Q)||("contextModification"in Q)||("overrideInput"in Q)||("errorMessage"in Q)))return;let W=typeof Q.context==="string"?Q.context:typeof Q.contextModification==="string"?Q.contextModification:typeof Q.errorMessage==="string"&&Q.errorMessage.length>0?Q.errorMessage:void 0;return{cancel:typeof Q.cancel==="boolean"?Q.cancel:void 0,review:typeof Q.review==="boolean"?Q.review:void 0,context:W,overrideInput:Object.hasOwn(Q,"overrideInput")?Q.overrideInput:void 0}}function cA($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))if(typeof Z==="string")J[Q]=Z;else J[Q]=JSON.stringify(Z);return J}function s1($,J,Q){let Z=Q.env??process.env,W=Z.CLINE_USER_ID?.trim()||Z.USER?.trim()||"unknown",j=Q.cwd||process.cwd();return{clineVersion:Z.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:J.conversationId,sessionContext:dw(Q.sessionContext,{hookName:$,conversationId:J.conversationId,agentId:J.agentId,parentAgentId:J.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Q.workspaceInfo,userId:W,agent_id:J.agentId,parent_agent_id:J.parentAgentId}}function iw($){return{name:$.name,message:$.message,stack:$.stack}}function nw($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function aw($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function sw($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function ow($){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 tw($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}async function N2($,J){try{let Q=await t8($,{command:J.command,cwd:J.cwd,env:J.env,detached:!0,onSpawn:J.onSpawn});J.onDispatch?.({payload:$,result:Q,detached:!0})}catch(Q){J.onDispatchError?.(uA(Q),$)}}function H9($={}){return{hooks:{beforeRun:async(X)=>{let Y=aw(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...s1("agent_resume",Y,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await N2(H,$)}else{let H={...s1("agent_start",Y,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await N2(H,$)}return},beforeTool:async(X)=>{let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...s1("tool_call",Y,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:cA(X.input)}};try{let H=await t8(V,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:V,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return tw(rw(H?.parsedJson))}catch(H){$.onDispatchError?.(uA(H),V);return}},afterTool:async(X)=>{let Y=ow(X),V={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},H={...s1("tool_result",V,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:Y,postToolUse:{toolName:Y.name,parameters:cA(Y.input),result:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output),success:!Y.error,executionTimeMs:Y.durationMs}};await N2(H,$);return},afterRun:async({snapshot:X,result:Y})=>{let V={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(Y.status==="completed"){let A={...s1("agent_end",V,$),hookName:"agent_end",iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status},taskComplete:{taskMetadata:{}}};await N2(A,$);return}let H=Y.status==="aborted"||nw(Y.error?.message)?"agent_abort":"agent_error",B=H==="agent_error"?{...s1(H,V,$),hookName:H,iteration:Y.iterations,error:iw(Y.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...s1(H,V,$),hookName:H,reason:Y.error?.message,taskCancel:{taskMetadata:{}}};await N2(B,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...s1("prompt_submit",Y,$),hookName:"prompt_submit",userPromptSubmit:{prompt:sw(X.message.content),attachments:[]}};await N2(V,$)}},shutdown:async({agentId:X,conversationId:Y,parentAgentId:V,reason:H})=>{let B={...s1("session_shutdown",{agentId:X,conversationId:Y,parentAgentId:V},$),hookName:"session_shutdown",reason:H};await N2(B,$)}}}B9();var pA={};w(pA,{registerRemoteConfigSessionBlobUpload:()=>G9,readRemoteConfigSessionBlobUploadMetadata:()=>K3,prepareRemoteConfigCoreIntegration:()=>F3,createRemoteConfigSessionMessagesArtifactUploader:()=>G3,buildRemoteConfigSessionBlobUploadMetadata:()=>A9,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>K9});import{buildRemoteConfigSessionBlobUploadMetadata as A9,clearRemoteConfigSessionBlobUpload as ew,createClineTelemetryServiceConfig as $S,createSessionId as JS,createRemoteConfigSessionMessagesArtifactUploader as QS,prepareRemoteConfigRuntime as ZS,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as K9,readRemoteConfigSessionBlobUploadMetadata as K3,registerRemoteConfigSessionBlobUpload as G9}from"@cline/shared";function WS($,J){let Q=$.telemetry||J.telemetryService?{...J.telemetryService??{},...$.telemetry??{}}:void 0;if(!Q)return;return b1($S(Q)).telemetry}function G3(){let $=QS();return{async uploadMessagesFile(J){await $.uploadMessagesFile(J)}}}async function F3($){let J=await ZS($),Q=WS(J,$),Z=[J.pluginDefinition],W=J.claims?.subject,j=A9(J.bundle?.remoteConfig,W),f;return{prepared:J,extensions:Z,telemetry:Q,applyToStartSessionInput(X){let Y=X.config.extensions??[],V=X.config.telemetry,H=j?X.config.sessionId?.trim()||JS():X.config.sessionId;if(H&&j)f=H;let B=H&&j?G9(H,J.bundle?.remoteConfig,W):void 0,A=B?{...X.sessionMetadata??{},[K9]:B}:X.sessionMetadata;return{...X,...A?{sessionMetadata:A}:{},config:{...X.config,...H?{sessionId:H}:{},extensions:[...Y,...Z],telemetry:Q??V}}},async dispose(){if(f)ew(f)}}}var tA={};w(tA,{createTeamName:()=>U9,DefaultRuntimeBuilder:()=>J4});import{hasRuntimeConfigExtension as RS}from"@cline/shared";import{nanoid as zS}from"nanoid";t0();var oA={};w(oA,{createLocalTeamStore:()=>z3,SqliteTeamStore:()=>w2,FileTeamStore:()=>DJ});import{appendFileSync as jS,existsSync as e8,mkdirSync as rA,readdirSync as fS,readFileSync as iA,renameSync as XS,writeFileSync as YS}from"node:fs";import{join as D3}from"node:path";import{resolveTeamDataDir as VS}from"@cline/shared/storage";function nA(){return new Date().toISOString()}function U3($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function aA($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class DJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??VS()}init(){this.ensureTeamDir()}listTeamNames(){if(!e8(this.teamDirPath))return[];return fS(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>e8(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let J=this.readEnvelope($);return J?.teamState?aA(J.teamState):void 0}readHistory($,J=200){let Q=this.historyPath($);if(!e8(Q))return[];return iA(Q,"utf8").split(`
570
+ `).map((Z)=>Z.trim()).filter(Boolean).map((Z)=>{try{return JSON.parse(Z)}catch{return}}).filter((Z)=>Z!==void 0).reverse().slice(0,J)}loadRuntime($){let J=this.readEnvelope($);return{state:J?.teamState?aA(J.teamState):void 0,teammates:J?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,J){this.ensureTeamSubdir($),jS(this.historyPath($),`${JSON.stringify({ts:nA(),eventType:J.type,payload:J})}
571
+ `,"utf8")}persistRuntime($,J,Q){this.ensureTeamSubdir($);let Z={version:1,updatedAt:nA(),teamState:J,teammates:Q},W=this.statePath($),j=`${W}.tmp`;YS(j,`${JSON.stringify(Z,null,2)}
572
+ `,"utf8"),XS(j,W)}markInProgressRunsInterrupted($,J){let Q=this.readEnvelope($);if(!Q?.teamState?.runs?.length)return[];let Z=Q.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Z.length===0)return[];let W=new Date;return Q.teamState={...Q.teamState,runs:Q.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:J,endedAt:W}:j)},this.persistRuntime($,Q.teamState,Q.teammates),Z}ensureTeamDir(){if(!e8(this.teamDirPath))rA(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let J=D3(this.ensureTeamDir(),U3($));if(!e8(J))rA(J,{recursive:!0});return J}statePath($){return D3(this.ensureTeamDir(),U3($),"state.json")}historyPath($){return D3(this.ensureTeamDir(),U3($),"task-history.jsonl")}readEnvelope($){let J=this.statePath($);if(!e8(J))return;try{let Q=JSON.parse(iA(J,"utf8"));if(Q?.version===1&&Q.teamState)return Q}catch{}return}}import{existsSync as HS,mkdirSync as BS}from"node:fs";import{join as AS}from"node:path";import{safeJsonParse as sA}from"@cline/shared";import{loadSqliteDb as KS,nowIso as R3}from"@cline/shared/db";import{resolveDbDataDir as GS}from"@cline/shared/storage";function FS(){return GS()}function $4($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function DS($){let J=sA($);if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,j=W.agentId,f=W.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof f!=="string"||!f.trim())continue;let X={agentId:j.trim(),rolePrompt:f};if(typeof W.modelId==="string"&&W.modelId.trim())X.modelId=W.modelId.trim();if(typeof W.maxIterations==="number"&&Number.isFinite(W.maxIterations))X.maxIterations=Math.max(1,Math.floor(W.maxIterations));Q.push(X)}return Q}function US($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class w2{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??FS()}init(){this.getRawDb()}ensureTeamDir(){if(!HS(this.teamDirPath))BS(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return AS(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=KS(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
564
573
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
565
574
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
566
575
  version INTEGER NOT NULL
@@ -644,13 +653,13 @@ ${Z}`,$.config.mode)}function WJ($,f){return Pq($,f==="plan"?"plan":f==="yolo"?"
644
653
  version INTEGER NOT NULL DEFAULT 1,
645
654
  PRIMARY KEY(team_name, fragment_id)
646
655
  );
647
- `)}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}withTransaction($){let f=this.getRawDb();f.exec("BEGIN IMMEDIATE;");try{$(),f.exec("COMMIT;")}catch(J){try{f.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let f=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[i2($)]);if(!f)return;let J=DB(f.state_json);if(!J)return;try{return Vw(J)}catch{return}}readHistory($,f=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[i2($),f]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime($){let f=i2($),J=this.readState(f),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f]),Z=Q?Aw(Q.teammates_json):[];return{state:J,teammates:Z,interruptedRunIds:[]}}appendTeamEvent($,f,J,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
648
- VALUES (?, ?, ?, ?, NULL, ?)`,[i2($),Z7(),f,JSON.stringify(J),Q??null])}persistRuntime($,f,J){let Q=i2($),Z=Z7();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
656
+ `)}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}withTransaction($){let J=this.getRawDb();J.exec("BEGIN IMMEDIATE;");try{$(),J.exec("COMMIT;")}catch(Q){try{J.exec("ROLLBACK;")}catch{}throw Q}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let J=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[$4($)]);if(!J)return;let Q=sA(J.state_json);if(!Q)return;try{return US(Q)}catch{return}}readHistory($,J=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[$4($),J]).flatMap((Q)=>{try{return[{eventType:Q.event_type,payload:JSON.parse(Q.payload_json),ts:Q.ts}]}catch{return[]}})}loadRuntime($){let J=$4($),Q=this.readState(J),Z=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[J]),W=Z?DS(Z.teammates_json):[];return{state:Q,teammates:W,interruptedRunIds:[]}}appendTeamEvent($,J,Q,Z){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
657
+ VALUES (?, ?, ?, ?, NULL, ?)`,[$4($),R3(),J,JSON.stringify(Q),Z??null])}persistRuntime($,J,Q){let Z=$4($),W=R3();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
649
658
  VALUES (?, ?, ?, ?)
650
659
  ON CONFLICT(team_name) DO UPDATE SET
651
660
  state_json = excluded.state_json,
652
661
  teammates_json = excluded.teammates_json,
653
- updated_at = excluded.updated_at`,[Q,JSON.stringify(f),JSON.stringify(J),Z]);for(let W of f.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
662
+ updated_at = excluded.updated_at`,[Z,JSON.stringify(J),JSON.stringify(Q),W]);for(let j of J.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
654
663
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
655
664
  ON CONFLICT(team_name, task_id) DO UPDATE SET
656
665
  title = excluded.title,
@@ -660,7 +669,7 @@ ${Z}`,$.config.mode)}function WJ($,f){return Pq($,f==="plan"?"plan":f==="yolo"?"
660
669
  depends_on_json = excluded.depends_on_json,
661
670
  summary = excluded.summary,
662
671
  version = team_tasks.version + 1,
663
- updated_at = excluded.updated_at`,[Q,W.id,W.title,W.description,W.status,W.assignee??null,JSON.stringify(W.dependsOn??[]),W.summary??null,W.updatedAt.toISOString()]);for(let W of f.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
672
+ updated_at = excluded.updated_at`,[Z,j.id,j.title,j.description,j.status,j.assignee??null,JSON.stringify(j.dependsOn??[]),j.summary??null,j.updatedAt.toISOString()]);for(let j of J.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
664
673
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
665
674
  ON CONFLICT(team_name, run_id) DO UPDATE SET
666
675
  agent_id = excluded.agent_id,
@@ -672,14 +681,14 @@ ${Z}`,$.config.mode)}function WJ($,f){return Pq($,f==="plan"?"plan":f==="yolo"?"
672
681
  error = excluded.error,
673
682
  lease_owner = excluded.lease_owner,
674
683
  heartbeat_at = excluded.heartbeat_at,
675
- version = team_runs.version + 1`,[Q,W.id,W.agentId,W.taskId??null,W.status,W.message,W.startedAt?W.startedAt.toISOString():null,W.endedAt?W.endedAt.toISOString():null,W.error??null,W.leaseOwner??null,W.heartbeatAt?W.heartbeatAt.toISOString():null]);for(let W of f.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
684
+ version = team_runs.version + 1`,[Z,j.id,j.agentId,j.taskId??null,j.status,j.message,j.startedAt?j.startedAt.toISOString():null,j.endedAt?j.endedAt.toISOString():null,j.error??null,j.leaseOwner??null,j.heartbeatAt?j.heartbeatAt.toISOString():null]);for(let j of J.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
676
685
  VALUES (?, ?, ?, ?, ?, ?, 1)
677
686
  ON CONFLICT(team_name, outcome_id) DO UPDATE SET
678
687
  title = excluded.title,
679
688
  status = excluded.status,
680
689
  schema_json = excluded.schema_json,
681
690
  finalized_at = excluded.finalized_at,
682
- version = team_outcomes.version + 1`,[Q,W.id,W.title,W.status,JSON.stringify({requiredSections:W.requiredSections}),W.finalizedAt?W.finalizedAt.toISOString():null]);for(let W of f.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
691
+ version = team_outcomes.version + 1`,[Z,j.id,j.title,j.status,JSON.stringify({requiredSections:j.requiredSections}),j.finalizedAt?j.finalizedAt.toISOString():null]);for(let j of J.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
683
692
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
684
693
  ON CONFLICT(team_name, fragment_id) DO UPDATE SET
685
694
  outcome_id = excluded.outcome_id,
@@ -690,30 +699,31 @@ ${Z}`,$.config.mode)}function WJ($,f){return Pq($,f==="plan"?"plan":f==="yolo"?"
690
699
  status = excluded.status,
691
700
  reviewed_by = excluded.reviewed_by,
692
701
  reviewed_at = excluded.reviewed_at,
693
- version = team_outcome_fragments.version + 1`,[Q,W.outcomeId,W.id,W.section,W.sourceAgentId,W.sourceRunId??null,W.content,W.status,W.reviewedBy??null,W.reviewedAt?W.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=i2($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(Q.length===0)return[];let Z=Z7();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
694
- WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),Q.map((W)=>W.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function W7($={}){try{let f=new wf($);return f.init(),f}catch{let f=new AJ({teamDir:$.teamDir});return f.init(),f}}function W9($,f){return Hw($,f)}function Kw($,f){let J=f?.["*"]??{},Q=f?.[$]??{};return{...J,...Q}.enabled!==!1}function Gw($,f){return $.filter((J)=>Kw(J.name,f))}function j7($,f){return x$(Gw($,f))}var Fw={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 Pw($){let f=$.trim().toLowerCase();return Fw[f]??f}function Rw($,f){if(f.tools===void 0)return $;let J=new Set(f.tools.map(Pw));if(f.skills!==void 0)J.add("skills");return $.filter((Q)=>J.has(Q.name))}function X9(){return`team-${Bw(5)}`}function j9($,f,J,Q,Z,W,j,X){let Y=v0[c1({mode:J})],A=j2(f,Q,J,Z??W2);return j7(Jf({cwd:$,...Y,enableSkills:!!j,...A,executors:{...j?{skills:j}:{},...X??{}}}),W)}function Dw($){return j9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,Uw,$.toolExecutors).some((f)=>f.name==="skills")}var Uw=async()=>"";async function Lw($){let f=T0();if(!p1({filePath:f}))return{tools:[]};let J=new Lf({clientFactory:S2({settingsPath:f})}),Q;try{Q=await Uf(J,{filePath:f})}catch(X){await J.dispose().catch(()=>{});let Y=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${Y}`),{tools:[]}}let Z=Q.filter((X)=>X.disabled!==!0),W=await Promise.allSettled(Z.map((X)=>E2({serverName:X.name,provider:J}))),j=[];for(let[X,Y]of W.entries())if(Y.status==="fulfilled")j.push(...Y.value);else{let A=Y.reason instanceof Error?Y.reason.message:String(Y.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[X].name}", skipping: ${A}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function _w($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function zw($){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 Ow($){let f=v0[c1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??f.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??f.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class n2{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:Q,logger:Z,telemetry:W,createSpawnTool:j,onTeamRestored:X,userInstructionService:Y,configExtensions:A,toolExecutors:V}=$,H=$.onTeamEvent??(()=>{}),B=Ow(f),K=f.workspaceRoot??f.cwd,G=$.toolPolicies??f.toolPolicies,R=W1(),P=[],F=f.teamName?.trim()||X9(),D=f.sessionId?.trim()||F,z=B.enableSpawnAgent?I2({workspaceRoot:K}):{configs:[],errors:[]},T=z.configs.some((m)=>m.skills!==void 0),L=W9(A,"rules"),U=W9(A,"skills"),w=U||T,h=W9(A,"workflows"),I=W9(A,"plugins"),o=L||U||h,V0=!1,$0=Boolean(Y),t=Y,t0;for(let m of z.errors)(Z??f.logger)?.log?.(`[agents] Failed to load agent config at ${m.path}: ${m.error.message}`);if(!t&&(o||T))t=M$({skills:w?{workspacePath:K,includePluginSkills:I,pluginSkillDirectories:I?$.pluginSkillDirectories:void 0,pluginPaths:f.pluginPaths,cwd:f.cwd}:{workspacePath:K},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(t)await t.start().catch(()=>{});let E$=B.enableTools&&U&&Boolean(t)&&t?.hasConfiguredSkills(f.skills)===!0&&Dw({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:G,toolExecutors:V}),i=t&&o?t.createExtension({includeRules:L,includeSkills:U,includeWorkflows:h,registerSkillsTool:E$,allowedSkillNames:f.skills}):void 0,_1=i?[...Q??f.extensions??[],i]:Q??f.extensions;if(B.enableTools){if(P.push(...j9(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,G,void 0,V)),!B.disableMcpSettingsTools){let m=await Lw(f.logger);P.push(...m.tools),t0=m.shutdown}}let C,G0=B.enableAgentTeams?W7():void 0,Q0=G0?.loadRuntime(D),w0=Q0?.state,hf=Q0?.teammates??[],z1=new Map(hf.map((m)=>[m.agentId,m])),Z1=f.sessionId||F,$8,bf=[],_J=!1,O1=K$({providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey??"",baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:J,extensions:_1,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(B.enableSpawnAgent){if(z.configs.length>0)P.push(...j7(x2({configProvider:O1,agents:z.configs,createSubAgentTools:(m)=>B.enableTools?Rw(j9(f.cwd,m.providerId??f.providerId,B.mode,m.modelId??f.modelId,f.toolRoutingRules,G,m.skills!==void 0&&t?.createSkillsExecutor?t.createSkillsExecutor(m.skills):void 0,V),m):[],hookErrorMode:f.hookErrorMode,toolPolicies:G,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),G))}if(!this.teamRuntimeEntries.has(Z1))this.teamRuntimeEntries.set(Z1,{delegatedAgentConfigProvider:O1});let zJ=()=>{if(!B.enableAgentTeams)return;let m=this.teamRuntimeEntries.get(Z1)??{delegatedAgentConfigProvider:O1};if(this.teamRuntimeEntries.set(Z1,m),C=m.runtime,!C){if(C=new Of({teamName:F,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(f0)=>{if(H(f0),C&&G0){if(f0.type==="teammate_spawned"&&f0.teammate?.rolePrompt){let M1={agentId:f0.agentId,rolePrompt:f0.teammate.rolePrompt,modelId:f0.teammate.modelId,maxIterations:f0.teammate.maxIterations};z1.set(M1.agentId,M1)}if(f0.type==="teammate_shutdown"&&!zw(f0.reason))z1.delete(f0.agentId);G0.handleTeamEvent(D,f0),G0.persistRuntime(D,C.exportState(),Array.from(z1.values()))}}}),w0)C.hydrateState(w0),_J=!0;m.runtime=C}if(!V0){if(!C)return;V0=!0;let f0=A2({runtime:C,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(w0),restoredTeammates:hf,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(M1)=>{bf=M1,$8?.addTools(M1)},createBaseTools:B.enableTools?()=>j9(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,G,void 0,V):void 0,teammateConfigProvider:O1});if(_J)C.recoverActiveRuns("runtime_recovered");if(f0.restoredFromPersistence)X?.();P.push(...f0.tools)}return C};if(B.enableSpawnAgent&&j){let m=j();P.push({...m,execute:async(f0,M1)=>{return zJ(),m.execute(f0,M1)}})}if(B.enableAgentTeams)zJ();let kf=j7(P,G),I9=kf.some((m)=>m.name==="submit_and_exit"&&m.lifecycle?.completesRun===!0),OJ=B.enableAgentTeams?()=>{let m=this.teamRuntimeEntries.get(Z1)?.runtime;if(!m)return;let f0=m.listTasks(),M1=f0.some((s1)=>s1.status==="in_progress"||s1.status==="pending"),D3=m.listRuns({}),OG=D3.some((s1)=>s1.status==="running"||s1.status==="queued");if(M1||OG){let s1=f0.filter((k0)=>k0.status==="in_progress"||k0.status==="pending").map((k0)=>`${k0.id} (${k0.status}): ${k0.title}`).join(", "),U3=D3.filter((k0)=>k0.status==="running"||k0.status==="queued").map((k0)=>`${k0.id} (${k0.status})`).join(", "),x9=[];if(s1)x9.push(`Unfinished tasks: ${s1}`);if(U3)x9.push(`Active runs: ${U3}`);return`[SYSTEM] You still have team obligations. ${x9.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,zG=I9?{requireCompletionTool:!0,...OJ?{completionGuard:OJ}:{}}:OJ?{completionGuard:OJ}:void 0;return{tools:kf,logger:Z??f.logger,telemetry:W??f.telemetry,teamRuntime:C,teamRestoredFromPersistence:Boolean(w0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(Z1)?.delegatedAgentConfigProvider??O1,extensions:_1,completionPolicy:zG,registerLeadAgent:(m)=>{if($8=m,bf.length>0)m.addTools(x$(bf,[...R]))},shutdown:async(m)=>{if(_w(C,m),this.teamRuntimeEntries.delete(Z1),await t0?.(),!$0)t?.stop()}}}}var zB={};q(zB,{requestDesktopToolApproval:()=>Y7});import{mkdir as Mw,readFile as Tw,unlink as Nw,writeFile as qw}from"node:fs/promises";import{join as _B}from"node:path";function ww($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function Cw($){return new Promise((f)=>setTimeout(f,$))}async function X7($){try{await Nw($)}catch{}}async function Y7($,f={}){let J=f.approvalDir?.trim(),Q=f.sessionId?.trim();if(!J||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await Mw(J,{recursive:!0});let Z=ww(`${$.toolCallId}`),W=_B(J,`${Q}.request.${Z}.json`),j=_B(J,`${Q}.decision.${Z}.json`),X=f.nowIso??(()=>new Date().toISOString());await qw(W,`${JSON.stringify({requestId:Z,sessionId:Q,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
695
- `,"utf8");let Y=f.timeoutMs??300000,A=f.pollIntervalMs??200,V=Date.now();while(Date.now()-V<Y){try{let H=await Tw(j,"utf8"),B=JSON.parse(H),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([X7(j),X7(W)]),K}catch{}await Cw(A)}return await X7(W),{approved:!1,reason:"Tool approval request timed out"}}j1();j1();var NB={};q(NB,{uninstallPlugin:()=>P7});import{existsSync as t2,readdirSync as yw,readFileSync as Sw,rmdirSync as Ew,rmSync as hw,statSync as bw}from"node:fs";import{basename as r0,dirname as C$,extname as kw,isAbsolute as Iw,join as t1,relative as xw,resolve as a2,sep as A7}from"node:path";import{discoverPluginModulePaths as gw,resolvePluginConfigSearchPaths as mw}from"@cline/shared/storage";var G7="_installed",vw="package",cw=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function V7($){return $.trim().toLowerCase()}function Q1($,f){let J=f?.trim();if(!J)return;$.add(J)}function uw($){return $.replace(/-[0-9a-f]{12}$/i,"")}function H7($){let f=kw($);return f?$.slice(0,-f.length):$}function B7($){if(!t2($))return;try{let f=JSON.parse(Sw($,"utf8"));return typeof f.name==="string"?f.name.trim():void 0}catch{return}}function F7($,f){let J=xw(f,$);return J===""||!J.startsWith("..")&&!Iw(J)}function OB($){let J=a2($).split(A7),Q=J.lastIndexOf(G7);if(Q<0)return;let Z=J[Q+1];if(!Z)return;let W=cw.get(Z)??1,j=Q+2+W;if(J.length<j)return;let X=J.slice(0,j).join(A7)||A7;return t2(X)?X:void 0}function Y9($){try{return yw($,{withFileTypes:!0})}catch{return[]}}function dw($){let f=t1($,G7);if(!t2(f))return[];let J=[];for(let Q of Y9(f)){if(!Q.isDirectory())continue;let Z=t1(f,Q.name);if(Q.name==="git"){for(let W of Y9(Z)){if(!W.isDirectory())continue;let j=t1(Z,W.name);for(let X of Y9(j))if(X.isDirectory())J.push(t1(j,X.name))}continue}for(let W of Y9(Z))if(W.isDirectory())J.push(t1(Z,W.name))}return J.sort((Q,Z)=>Q.localeCompare(Z))}function MB($){try{return gw($)}catch{return[]}}function K7($){let f=MB($),J=new Set;Q1(J,r0($)),Q1(J,uw(r0($))),Q1(J,B7(t1($,"package.json"))),Q1(J,B7(t1($,vw,"package.json")));for(let Q of f)Q1(J,r0(Q)),Q1(J,H7(r0(Q)));return{installPath:$,entryPaths:f,names:[...J].sort((Q,Z)=>Q.localeCompare(Z)),installed:!0}}function lw($,f){let J=a2($),Q=f.find((j)=>F7(J,j));if(!Q)return;let Z=C$(J);while(Z!==Q&&Z!==C$(Z)){if(t2(t1(Z,"package.json")))return Z;Z=C$(Z)}let W=r0(J);if((W==="index.ts"||W==="index.js")&&C$(J)!==Q)return C$(J);return J}function TB($,f){let J=lw($,f);if(!J)return;let Q=new Set;return Q1(Q,r0($)),Q1(Q,H7(r0($))),Q1(Q,r0(J)),Q1(Q,H7(r0(J))),Q1(Q,B7(t1(J,"package.json"))),{installPath:J,entryPaths:[$],names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!1}}function pw($){let f=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return mw(f).filter((J)=>t2(J))}function rw($){let f=new Map;for(let J of $){for(let Q of dw(J))f.set(Q,K7(Q));for(let Q of MB(J)){let Z=OB(Q);if(Z){if(!f.has(Z))f.set(Z,K7(Z));continue}let W=TB(Q,$);if(W)f.set(W.installPath,W)}}return[...f.values()].sort((J,Q)=>J.installPath.localeCompare(Q.installPath))}function iw($,f){let J=V7(f);if(!J)return!1;if(V7($.installPath)===J)return!0;return $.names.some((Q)=>V7(Q)===J)}function nw($,f,J){let Q=a2($);for(let W of f){if(F7(Q,W.installPath))return W;if(W.entryPaths.some((j)=>a2(j)===Q))return W}let Z=OB(Q);if(Z)return K7(Z);if(t2(Q))return TB(Q,J);return}function aw($){let f=z0(),J=f.disabledPlugins;if(!J?.length)return;let Q=J.filter((Z)=>{let W=a2(Z);if(F7(W,$.installPath))return!1;return!$.entryPaths.some((j)=>a2(j)===W)});if(Q.length===J.length)return;y1({...f,disabledPlugins:Q})}function tw($){let f=C$($);while(f!==C$(f)&&r0(f)!==G7){try{Ew(f)}catch{return}f=C$(f)}}function sw($){return`${$.names[0]??r0($.installPath)} at ${$.installPath}`}async function P7($){let f=pw($),J=rw(f),Q=$.path?.trim(),Z=$.name?.trim(),W;if(Q){if(W=nw(Q,J,f),!W)throw Error(`No plugin found at ${Q}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let X=J.filter((Y)=>iw(Y,Z));if(X.length===0)throw Error(`No plugin found matching "${Z}"`);if(X.length>1)throw Error(`Multiple plugins match "${Z}": ${X.map(sw).join(", ")}`);W=X[0]}let j=bw(W.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${W.installPath}`);if(hw(W.installPath,{recursive:j.isDirectory(),force:!0}),aw(W),W.installed)tw(W.installPath);return{name:Z||W.names[0]||r0(W.installPath),installPath:W.installPath,removedPaths:[W.installPath],entryPaths:W.entryPaths}}var rB={};q(rB,{updateLocalProvider:()=>P9,saveLocalProviderSettings:()=>M7,saveLocalProviderOAuthCredentials:()=>w7,resolveLocalClineAuthToken:()=>y7,refreshProviderModelsFromSource:()=>T7,normalizeOAuthProvider:()=>N7,loginLocalProvider:()=>q7,loginAndSaveLocalProviderOAuthCredentials:()=>C7,listLocalProviders:()=>z7,getLocalProviderModels:()=>O7,ensureCustomProvidersLoaded:()=>K9,deleteLocalProvider:()=>R9,addLocalProvider:()=>_7});import*as q0 from"@cline/llms";import{existsSync as ow,mkdirSync as ew,readFileSync as $C,writeFileSync as fC}from"node:fs";import{mkdir as JC,readFile as QC,writeFile as ZC}from"node:fs/promises";import{dirname as R7,join as WC}from"node:path";import*as E0 from"@cline/llms";import{ModelCapabilitySchema as jC,ProviderCapabilitySchema as XC,ProviderClientSchema as YC,ProviderProtocolSchema as AC}from"@cline/shared";import{z as r}from"zod";var VC=r.object({id:r.string().optional(),name:r.string().optional(),maxTokens:r.number().optional(),contextWindow:r.number().optional(),maxInputTokens:r.number().optional(),capabilities:r.array(jC).optional(),supportsVision:r.boolean().optional(),supportsAttachments:r.boolean().optional(),supportsReasoning:r.boolean().optional()}).passthrough(),HC=r.object({name:r.string(),baseUrl:r.string(),defaultModelId:r.string().optional(),protocol:AC.optional(),client:YC.optional(),capabilities:r.array(XC).optional(),modelsSourceUrl:r.string().optional()}).passthrough(),qB=r.object({provider:HC.optional(),models:r.record(r.string(),VC).optional()}).passthrough(),wB=r.object({version:r.literal(1),providers:r.record(r.string(),qB)}),BC=r.object({version:r.literal(1),providers:r.record(r.string(),r.unknown())}),A9=new Set;function CB($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function Cf($){return WC(R7($.getFilePath()),"models.json")}function V9(){return{version:1,providers:{}}}function yB($){let f=BC.safeParse($);if(!f.success)return V9();let J={};for(let[Q,Z]of Object.entries(f.data.providers)){let W=qB.safeParse(Z);if(W.success)J[Q]=W.data}return{version:1,providers:J}}function D7($){if(!ow($))return V9();try{let f=$C($,"utf8");return yB(JSON.parse(f))}catch{}return V9()}async function s2($){try{let f=await QC($,"utf8");return yB(JSON.parse(f))}catch{}return V9()}function SB($,f){ew(R7($),{recursive:!0});let J=wB.parse(f);fC($,`${JSON.stringify(J,null,2)}
696
- `,"utf8")}async function H9($,f){await JC(R7($),{recursive:!0});let J=wB.parse(f);await ZC($,`${JSON.stringify(J,null,2)}
697
- `,"utf8")}function EB($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function hB($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function bB($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function KC($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function kB($,f){return $??f??"openai-chat"}function IB($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function xB($,f,J){let Q=new Set(f?.capabilities??J??[]);if(f?.supportsVision)Q.add("images");if(f?.supportsAttachments)Q.add("files");if(f?.supportsReasoning)Q.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function GC($,f){for(let[J,Q]of Object.entries(f??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;E0.registerModel($,Z,xB(Z,Q))}}function FC($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function PC($){return Object.assign({},...E0.resolveProviderModelCatalogKeys($).map((J)=>E0.getGeneratedModelsForProvider(J)))}function RC($){let f=$.provider.trim();if(!f||E0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let Q=E0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=PC(f),W=bB($.capabilities),j=W.length>0?W:void 0,X=$.model?.trim(),Y={...Z,...Q?.models??{}};if(X)Y[X]=FC(X,Y[X],j);let A=Object.keys(Y).filter(Boolean),V=X||A[0];if(!V)return;let H=kB($.protocol,Q?.provider.protocol),B=IB($.client,H,Q?.provider.client);E0.registerProvider({provider:{id:f,name:Q?.provider.name??CB(f),description:Q?.provider.description,protocol:H,client:B,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:V,capabilities:hB($.capabilities)??Q?.provider.capabilities,source:"file"},models:Y})}function B9($){for(let f of Object.values($.providers))RC(f.settings)}function VJ($,f){let J=f.models??{};if(!KC(f.provider)){GC($,J);return}let Q=bB(f.provider.capabilities),Z=Object.entries(J).map(([A,V])=>({id:V.id?.trim()||A.trim(),model:V})).filter(({id:A})=>A.length>0),W=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=kB(f.provider.protocol,void 0),X=IB(f.provider.client,j,void 0),Y=Object.fromEntries(Z.map(({id:A,model:V})=>[A,{...xB(A,V,Q.length>0?Q:void 0),status:"active"}]));E0.registerProvider({provider:{id:$,name:f.provider.name.trim()||CB($),protocol:j,client:X,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:W,capabilities:hB(f.provider.capabilities),source:"file"},models:Y})}function gB($){let f=Cf($);if(A9.has(f))return;let J=D7(f);for(let[Q,Z]of Object.entries(J.providers))VJ(Q,Z);A9.add(f)}async function K9($){let f=Cf($);if(A9.has(f))return;let J=await s2(f);for(let[Q,Z]of Object.entries(J.providers))VJ(Q,Z);A9.add(f)}function DC($){return $.apiKey??$.auth?.apiKey}function UC($){return($.auth?.accessToken?.trim()??"").length>0}function vB($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function LC($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function _C($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of $)J=J*31+Q.charCodeAt(0)>>>0;return f[J%f.length]}function cB($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>EB(f,J))}async function zC($,f){let J=await q0.getModelsForProvider($);if(!f)return J;let Q=await z4($,{loadPrivateOnAuth:!0,failOnError:!1},f);return Q?.knownModels?{...J,...Q.knownModels}:J}function U7($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function OC($){if(!$?.length)return;return[...new Set($)]}function MC($,f){return OC([...$??[],...f??[]])}function TC($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function NC($){if(!$||typeof $!=="object")return!1;let f=$;return typeof f.path==="string"&&f.path.trim().length>0&&typeof f.label==="string"&&f.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(f.type))}function qC($){let f=$?.configFields;if(!Array.isArray(f))return;return f.filter(NC)}var G9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},mB={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function wC($){if(!$)return[G9];if($.source!=="system")return $.baseUrl?[G9,mB]:[G9];let f=[];if($.env?.length)f.push(G9);if($.baseUrl)f.push(mB);return f}function CC($,f){return f.split(".").reduce((J,Q)=>{if(!J||typeof J!=="object")return;return J[Q]},$)}function yC($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function SC($,f,J){if(!$?.length)return;let Q={};for(let Z of $){let j=yC(Z.path==="baseUrl"&&f?.baseUrl===void 0?J?.baseUrl:CC(f,Z.path))??Z.defaultValue;if(j!==void 0)Q[Z.path]=j}return Q}function uB($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function L7($,f){let J=f?.includes("vision")??!1,Q=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function dB($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await o6($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function lB($,f){let J=$.read(),Q=!1;if(J.providers[f])delete J.providers[f],Q=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,Q=!0;if(Q)$.write(J);q0.unregisterProvider(f)}async function _7($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!Q&&!Z){let G=Cf($);if((await s2(G)).providers[J]){let P=await R9($,{providerId:J});return{providerId:J,settingsPath:P.settingsPath,modelsPath:P.modelsPath,modelsCount:0}}return lB($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(q0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=f.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=U7(f.models),X=f.modelsSourceUrl?.trim(),Y=await dB({providerId:J,explicitModels:j,modelsSourceUrl:X,shouldRecompute:!0});if(Y.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=f.defaultModelId?.trim()&&Y.includes(f.defaultModelId.trim())?f.defaultModelId.trim():Y[0],V=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,H=uB(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:H,timeout:f.timeoutMs,model:A,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=Cf($),K=await s2(B);return K.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:A,protocol:f.protocol,client:f.client,capabilities:V,modelsSourceUrl:X},models:L7(Y,V)},await H9(B,K),VJ(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:Y.length}}async function P9($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=Cf($),Z=await s2(Q),W=Z.providers[J];if(!W){let T=$.getProviderSettings(J);if(!T)throw Error(`provider "${J}" does not exist`);let L=f.modelsSourceUrl?.trim(),U=U7(f.models)[0]??T.model?.trim();if(!U&&!L)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:f.name?.trim()||vB(J),baseUrl:f.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:U,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:U?L7([U],T.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let X=f.baseUrl?.trim()??W.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let Y=f.capabilities===void 0?W.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],A=f.protocol===void 0?W.provider.protocol:f.protocol??void 0,V=f.client===void 0?W.provider.client:f.client??void 0,H=U7(f.models),B=f.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,G=Object.keys(W.models??{}).map((T)=>T.trim()).filter(Boolean),R=await dB({providerId:J,explicitModels:H,modelsSourceUrl:B,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let P=f.defaultModelId===void 0?W.provider.defaultModelId?.trim():f.defaultModelId?.trim(),F=P&&R.includes(P)?P:R[0],z={...$.getProviderSettings(J)??{},provider:J,baseUrl:X,model:F};if(A)z.protocol=A;else delete z.protocol;if(V)z.client=V;else delete z.client;if(f.apiKey!==void 0){let T=f.apiKey?.trim()??"";if(T)z.apiKey=T;else delete z.apiKey}if(f.headers!==void 0){let T=uB(f.headers);if(T)z.headers=T;else delete z.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")z.timeout=f.timeoutMs;else delete z.timeout;return $.saveProviderSettings(z,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:X,defaultModelId:F,protocol:A,client:V,capabilities:Y,modelsSourceUrl:B},models:L7(R,Y)},await H9(Q,Z),VJ(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:R.length}}async function R9($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=Cf($),Z=await s2(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await H9(Q,Z),q0.unregisterProvider(J),lB($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q}}async function z7($){let f=$.read(),J=q0.getProviderIds(),Q=await Promise.all(J.map(async(W)=>{let[j,X]=await Promise.all([q0.getProvider(W),q0.getModelsForProvider(W)]),Y=cB(X),A=f.providers[W]?.settings,V=j?.name??vB(W),H=MC(j?.capabilities,A?.capabilities),B=qC(j?.metadata)??wC(j);return{provider:{id:W,name:V,models:Y.length,color:_C(W),letter:LC(V),enabled:Boolean(A),apiKey:A?DC(A):void 0,oauthAccessTokenPresent:A?UC(A):void 0,baseUrl:A?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:A?.protocol??j?.protocol,client:A?.client??j?.client,capabilities:H,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:SC(B,A,j),modelList:Y},rank:TC(j?.metadata)}}));return Q.sort((W,j)=>{if(W.rank!==j.rank)return W.rank-j.rank;return W.provider.name.localeCompare(j.provider.name)||W.provider.id.localeCompare(j.provider.id)}),{providers:Q.map((W)=>W.provider),settingsPath:$.getFilePath()}}async function O7($,f){let J=$.trim(),Q=await zC(J,f),Z=cB(Q);return{providerId:J,models:Z}}function F9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function pB($,f){if(!F9(f))return F9($)?{...$}:void 0;let J=F9($)?{...$}:{};for(let[Q,Z]of Object.entries(f)){if(Z==null||Z===""){delete J[Q];continue}if(F9(Z)){let W=pB(J[Q],Z);if(W&&Object.keys(W).length>0)J[Q]=W;else delete J[Q];continue}J[Q]=Z}return Object.keys(J).length>0?J:void 0}function M7($,f){let J=f.providerId.trim();if(f.enabled===!1){let W=$.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return $.write(W),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,W)&&typeof f[W]==="string")if(f[W].trim().length===0)delete Z[W];else Z[W]=f[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,W))Z[W]=f[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,W)&&f[W]!=null){let j=pB(Z[W],f[W]);if(j)Z[W]=j;else delete Z[W]}return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function T7($,f){let J=f.trim(),Q=$.getProviderSettings(J),W=q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),X=e6(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!X)return{providerId:J,refreshed:!1};let Y=await P9($,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:X,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:Y.modelsCount}}function N7($){let f=$.trim().toLowerCase(),J=B0(f);if(J)return J.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function q7($,f,J,Q){let Z=B0($);if(!Z)throw Error(`provider "${$}" does not support OAuth login`);let W=q2({onPrompt:async(j)=>j.defaultValue??"",openUrl:J,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return Z.login({settings:f,callbacks:W,telemetry:Q})}function w7($,f,J,Q,Z){return p$({manager:$,providerId:f,settings:J,credentials:Q,setLastUsed:Z?.setLastUsed})}async function C7($,f,J,Q){let Z=q2({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});return S8($,f,{callbacks:Z,telemetry:Q})}function y7($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var iB={};q(iB,{getProviderConfigFields:()=>S7});import*as D9 from"@cline/llms";var EC=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],hC={"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 bC($,f){let J={};for(let Q of EC){let Z=$[Q],W=f[Q];if(Z||W)J[Q]={...Z,...W}}return J}function kC($){let f=hC[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:bC($.fields,f.fields)}}var IC=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function xC($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return IC.has($)}function S7($){let f=D9.normalizeProviderId($);if(l$(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=D9.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if(xC(f,J))Z.baseUrl={defaultValue:Q};return kC({providerId:f,authMethod:"api-key",fields:Z})}var sB={};q(sB,{resolveLegacyClineAuth:()=>b7,migrateLegacyProviderSettings:()=>HJ});import{existsSync as gC,readFileSync as mC}from"node:fs";import{dirname as vC,join as E7}from"node:path";import*as L9 from"@cline/llms";import{resolveClineDataDir as cC}from"@cline/shared/storage";var U9="openai",tB=L9.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,nB=128000;function b7($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;let Q=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:Q,accountId:J.userInfo?.id}}catch{return}}function S($){let f=$?.trim();return f?f:void 0}function aB($){if(!gC($))return;try{let f=mC($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function uC($){let f=$.dataDir??cC(),J=$.globalStatePath??E7(f,"globalState.json"),Q=$.secretsPath??E7(f,"secrets.json"),Z=aB(J),W=aB(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function h7($){if($===U9)return tB;return $}function dC($,f,J,Q){let Z=J==="plan"?"planMode":"actMode",W=f===Q?S(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(X?S(typeof $[X]==="string"?$[X]:void 0):void 0)??W}function lC($,f,J){let Q=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,W=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??Q,X=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,Y=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function pC($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),Q=S(J.access_token),Z=S(J.refresh_token),W=S(J.accountId);if(!Q&&!Z&&!W)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...Z?{refreshToken:Z}:{},...W?{accountId:W}:{}}}}catch{return}}function rC($){let f=L9.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function iC($,f,J,Q){let Z=h7($),W=S(Q==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=dC(f,$,Q,W)??rC(Z),X=lC(f,Z,Q),Y=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,A={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey},V={};if($==="openai-codex")Object.assign(V,pC(J));if($==="cline")try{let F=S(J["cline:clineAccountId"]);if(F)V.auth={...V.auth??{},...b7(F)}}catch{}if($===U9&&f.openAiHeaders)V.headers=f.openAiHeaders;if($==="bedrock"){let F=f.awsAuthentication==="profile"||f.awsUseProfile===!0;V.aws={accessKey:S(J.awsAccessKey),secretKey:S(J.awsSecretKey),sessionToken:S(J.awsSessionToken),region:S(f.awsRegion),authentication:f.awsAuthentication,profile:F?S(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:S(f.awsBedrockEndpoint),customModelBaseId:S(Q==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")V.gcp={projectId:S(f.vertexProjectId),region:S(f.vertexRegion)};if($===U9&&(f.azureApiVersion||f.azureIdentity!==void 0))V.azure={apiVersion:S(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")V.sap={clientId:S(J.sapAiCoreClientId),clientSecret:S(J.sapAiCoreClientSecret),tokenUrl:S(f.sapAiCoreTokenUrl),resourceGroup:S(f.sapAiResourceGroup),deploymentId:S(Q==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){V.oca={mode:f.ocaMode};let F=S(J.ocaRefreshToken);if(F)V.auth={...V.auth??{},refreshToken:F}}if($==="qwen")V.apiLine=f.qwenApiLine;if($==="moonshot")V.apiLine=f.moonshotApiLine;if($==="zai")V.apiLine=f.zaiApiLine;if($==="minimax")V.apiLine=f.minimaxApiLine;let H={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=S(A[$]),K=S(H[$]),G={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...Y?{timeout:Y}:{},...V},R=T4.safeParse(G);if(!R.success)return;return Object.keys(G).filter((F)=>F!=="provider").length>0?R.data:void 0}function nC($,f){if($!==tB)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model,contextWindow:nB,maxInputTokens:nB,capabilities:["streaming","tools","images"]}}}}function aC($,f){let J=new Set;for(let Z of[$.actModeApiProvider,$.planModeApiProvider]){let W=S(Z);if(W)J.add(W)}if(S(f.apiKey))J.add("anthropic");if(S(f.openRouterApiKey))J.add("openrouter");if(S(f.openAiApiKey))J.add(U9);if(S(f.openAiNativeApiKey))J.add("openai-native");if(S(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(S(f.geminiApiKey))J.add("gemini");if(S(f.ollamaApiKey))J.add("ollama");if(S(f.awsAccessKey)||S(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||S($.awsProfile))J.add("bedrock");if(S($.vertexProjectId)||S($.vertexRegion))J.add("vertex");if(S(f.clineApiKey))J.add("cline");let Q=b7(S(f["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)J.add("cline");if(S(f.ocaApiKey))J.add("oca");if(S(f.sapAiCoreClientId)||S(f.sapAiCoreClientSecret)||S($.sapAiCoreTokenUrl)||S($.sapAiCoreBaseUrl)||S($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function HJ($){let f=$.providerSettingsManager.read(),J=uC($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=aC(Q,Z),X=O$();X.providers={...f.providers},X.lastUsedProvider=f.lastUsedProvider;let Y=new Date().toISOString(),A=0,V=E7(vC($.providerSettingsManager.getFilePath()),"models.json"),H=D7(V),B=0;for(let R of j){let P=h7(R);if(X.providers[P])continue;let F=iC(R,Q,Z,W);if(!F)continue;X.providers[P]={settings:F,updatedAt:Y,tokenSource:"migration"},A+=1;let D=nC(P,F);if(D&&!H.providers[P])H.providers[P]=D,B+=1}if(A===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=S(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),G=K?h7(K):void 0;if(X.lastUsedProvider=f.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),B>0)SB(V,H);return{migrated:A>0||B>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}_0();oJ();var $K={};q($K,{trimMessagesToCheckpoint:()=>eB,trimMessagesBeforeCheckpoint:()=>I7,readSessionCheckpointHistory:()=>BJ,createRestoredCheckpointMetadata:()=>k7,createCheckpointRestorePlan:()=>x7,applyCheckpointToWorktree:()=>g7});import{execFile as tC}from"node:child_process";import{promisify as sC}from"node:util";var o2=sC(tC);function BJ($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let Z=String(Q.ref??"").trim(),W=Number(Q.createdAt??0),j=Number(Q.runCount??0);if(Z.length===0||!Number.isFinite(W)||!Number.isInteger(j)||j<1)return[];let X=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...X?{kind:X}:{}}]})}function k7($,f){let J=BJ($).filter((Z)=>Z.runCount<=f),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function oC($,f){return $.reduce((J,Q)=>{if(Q.runCount>f)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function oB($,f){let J=0;for(let Q=0;Q<$.length;Q+=1){let Z=$[Q];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return Q}throw Error(`Could not find user message for checkpoint run ${f}`)}function eB($,f){let J=oB($,f);return $.slice(0,J+1)}function I7($,f){let J=oB($,f);return $.slice(0,J)}function x7($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=oC(BJ($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...$.restoreMessages!==!1?{messages:eB($.messages??[],f)}:{}}}async function g7($,f){if((await o2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await o2("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await o2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await o2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await o2("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await o2("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}var fK={};q(fK,{SessionVersioningService:()=>y$,SessionVersioningError:()=>h0});class h0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function eC($){let f=$.sessionId.trim();if(!f)throw new h0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new h0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new h0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new h0("invalid_restore","checkpointRunCount must be a positive integer");return f}class y${async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,Q=eC({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(Q);if(!Z)throw new h0("session_not_found",`Session ${Q} not found`);let W=f?await $.readMessages(Q):void 0;if(f&&W?.length===0)throw new h0("session_messages_not_found",`No messages found for session ${Q}`);let j=x7({session:Z,messages:W,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??g7)(j.cwd,j.checkpoint);let X=G1({session:Z,messages:W});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:X};let Y=k7(Z,$.checkpointRunCount),A=$.restore?.omitCheckpointMessageFromSession?I7(W??[],$.checkpointRunCount):j.messages??[],V={sourceSession:Z,sourceMessages:W,sourceSnapshot:X,plan:j,restoredCheckpointMetadata:Y,initialMessages:A,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new h0("invalid_restore","start is required when restore.messages is true");let H=$.buildStartInput?await $.buildStartInput(V,$.start):$.start,B=await $.startSession(H),K=$.getStartedSessionId?.(B);if(K)await($.retainCheckpointRefs??EA)(j.cwd,K,Y?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:G1({session:G,messages:A})}:{}}}}var JK={};q(JK,{FileTeamPersistenceStore:()=>_9});import{appendFileSync as $y,existsSync as m7,mkdirSync as fy,readFileSync as Jy,renameSync as Qy,unlinkSync as Zy,writeFileSync as Wy}from"node:fs";import{join as v7}from"node:path";import{resolveTeamDataDir as jy}from"@cline/shared/storage";function Xy($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class _9{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=Xy($.teamName),J=$.baseDir?.trim()||jy();this.dirPath=v7(J,f),this.statePath=v7(this.dirPath,"state.json"),this.taskHistoryPath=v7(this.dirPath,"task-history.jsonl")}loadState(){if(!m7(this.statePath))return;try{let $=Jy(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return oH(f.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;Wy(J,`${JSON.stringify(f,null,2)}
698
- `,"utf8"),Qy(J,this.statePath)}appendTaskHistory($){let f={};switch($.type){case"team_task_updated":f=$.task;break;case"team_message":f={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":f={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":f={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":f={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":f={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),$y(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
699
- `,"utf8")}ensureDir(){if(!m7(this.dirPath))fy(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(m7(this.statePath))Zy(this.statePath)}}var QK={};q(QK,{ChatViewStateSchema:()=>c7,ChatSummarySchema:()=>N9,ChatSessionStatusSchema:()=>O9,ChatSessionConfigSchema:()=>z9,ChatMessageSchema:()=>T9,ChatMessageRoleSchema:()=>M9});import{z as E}from"zod";var z9=E.object({workspaceRoot:E.string().min(1),cwd:E.string().optional(),provider:E.string().min(1),model:E.string().min(1),mode:E.enum(["act","plan"]).default("act"),apiKey:E.string(),systemPrompt:E.string().optional(),rules:E.string().optional(),maxIterations:E.number().int().positive().optional(),enableTools:E.boolean(),enableSpawn:E.boolean().optional(),enableTeams:E.boolean().optional(),autoApproveTools:E.boolean().optional(),missionStepInterval:E.number().int().positive().optional(),missionTimeIntervalMs:E.number().int().positive().optional()}),O9=E.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),M9=E.enum(["user","assistant","tool","system","status","error"]),T9=E.object({id:E.string().min(1),sessionId:E.string().nullable(),role:M9,content:E.string(),createdAt:E.number().int().nonnegative(),meta:E.object({stream:E.enum(["stdout","stderr"]).optional(),toolName:E.string().optional(),iteration:E.number().int().nonnegative().optional(),agentId:E.string().optional(),conversationId:E.string().optional(),hookEventName:E.string().optional(),inputTokens:E.number().int().nonnegative().optional(),outputTokens:E.number().int().nonnegative().optional(),checkpoint:E.object({ref:E.string(),createdAt:E.number().int().nonnegative(),runCount:E.number().int().positive(),kind:E.enum(["stash","commit"]).optional()}).optional()}).optional()}),N9=E.object({toolCalls:E.number().int().nonnegative(),tokensIn:E.number().int().nonnegative(),tokensOut:E.number().int().nonnegative()}),c7=E.object({sessionId:E.string().nullable(),status:O9,config:z9,messages:E.array(T9),rawTranscript:E.string(),error:E.string().nullable(),summary:N9});var ZK={};q(ZK,{CORE_BUILD_VERSION:()=>u7});var u7=jj;import{Agent as py,createAgentRuntime as ry}from"@cline/agents";var jK={};q(jK,{fetchClineRecommendedModels:()=>d7,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>q9});import{getClineEnvironmentConfig as Yy}from"@cline/shared";var Ay=5000,q9={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}]};function Vy($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function WK($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function Hy($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],Q=Array.isArray(f.free)?f.free:[],Z=J.map(WK).filter((j)=>j!==null),W=Q.map(WK).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function By($){let f=$.baseUrl?.trim();if(f)return f;let J=Yy().apiBaseUrl;try{return($.providerSettingsManager??new L1).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function Ky($,f,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await $(f,{signal:Q.signal})}finally{clearTimeout(Z)}}async function d7($={}){try{let f=By($),J=$.fetchImpl??fetch,Q=await Ky(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??Ay);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=Hy(Z);if(W)return W}catch{}return Vy(q9)}var XK={};q(XK,{loadLlmsConfigFromFile:()=>p7,defineLlmsConfig:()=>l7});import{readFile as Gy}from"node:fs/promises";import Fy from"node:path";function l7($){return $}async function p7($){let f=Fy.resolve($),J=await Gy(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${W}`)}return Py(Q,f)}function Py($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}var KK={};q(KK,{createLlmsSdk:()=>i7,DefaultLlmsSdk:()=>KJ});import{BUILT_IN_PROVIDER_IDS as VK,createHandler as Uy,createHandlerAsync as Ly,getProviderCollection as _y,hasProvider as HK,registerAsyncHandler as zy,registerHandler as Oy,registerModel as My,registerProvider as BK}from"@cline/llms";function YK($){return $?{...$}:{}}function Ry($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function Dy($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function AK($){let f=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class r7{providers=new Map;register($){Dy($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...YK($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:Ry($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...YK($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class KJ{configuredProviders=new r7;constructor($){this.applyConfig($)}createHandler($){return Uy(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return Ly(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(BK($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)Oy($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)zy($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);BK({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){My($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...VK]}async getBuiltInProviders(){return(await Promise.all(VK.map((f)=>_y(f)))).filter((f)=>f!==void 0).map((f)=>AK({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=HK(f.id),Q=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof Q==="string"&&HK(Q);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function i7($){return new KJ($)}o9();async function Ty(){return Promise.resolve().then(() => (oW(),BB))}function sy(){return new Date().toISOString()}function oy($){if(_K($)!=="providers.json")return;let f=a7($);if(_K(f)!=="settings")return;return a7(f)}class L1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??ty(),this.dataDir=$.dataDir??oy(this.filePath),this.dataDir||!$.filePath)HJ({providerSettingsManager:this,dataDir:this.dataDir});if(gB(this),B9(this.read()),n7(this.filePath))try{LK(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!n7(this.filePath))return O$();try{let $=ny(this.filePath,"utf8"),f=JSON.parse($),J=T2.safeParse(f);if(J.success)return B9(J.data),J.data}catch{}return O$()}write($){let f=T2.parse($),J=a7(this.filePath);if(!n7(J))iy(J,{recursive:!0,mode:448});ay(this.filePath,`${JSON.stringify(f,null,2)}
700
- `,"utf8");try{LK(this.filePath,384)}catch{}B9(f)}saveProviderSettings($,f={}){let J=T4.parse($),Q=this.read(),Z=J.provider,W=f.setLastUsed!==!1,j=Q.providers[Z],X=f.tokenSource??j?.tokenSource??"manual",Y={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:sy(),tokenSource:X}},lastUsedProvider:W?Z:Q.lastUsedProvider};return this.write(Y),Y}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return u0(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return u0(f,$)}async refreshCatalog(){try{await O2({})}catch{}}}_0();G8();function ey($,f){let J=$?.expiresAt,Q=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===Q}class y9 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 t7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new L1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let f=B0($.providerId);if(!f)return null;return this.resolveWithSingleFlight(f.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let Q=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,Q),Q}async resolveProviderApiKeyInternal($,f){let J=B0($);if(!J)return null;let Q=this.providerSettingsManager.getProviderSettings(J.storageProviderId);if(!Q)return null;let Z=E8($,Q);if(!Z)return null;let W=await J.refresh({settings:Q,credentials:Z,forceRefresh:f,telemetry:this.telemetry});if(!W)throw new y9($);let j=p$({manager:this.providerSettingsManager,providerId:$,settings:Q,credentials:W,setLastUsed:!1,save:!1}),X=!ey(Q.auth,j.auth);if(X)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:J.getApiKey(j)??W.access,accountId:W.accountId,refreshed:X}}}import{normalizeUserInput as $S}from"@cline/shared";import{nanoid as fS}from"nanoid";class zK{list($){return $?i0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((Y)=>Y.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:i0($),updated:!1};let Z=$.pendingPrompts[Q];if(!Z)return{sessionId:f.sessionId,prompts:i0($),updated:!1};let W=f.prompt===void 0?Z.prompt:$S(f.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,X={...Z,prompt:W,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(Q,1),JS($,X,Q,Z.delivery),{sessionId:f.sessionId,prompts:i0($),prompt:S9(X),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:i0($),removed:!1};let[Z]=$.pendingPrompts.splice(Q,1);return{sessionId:f.sessionId,prompts:i0($),prompt:Z?S9(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=f,X=$.pendingPrompts.findIndex((Y)=>Y.prompt===J);if(X>=0){let[Y]=$.pendingPrompts.splice(X,1),A={...Y,prompt:J,mode:Q??Y.mode,userImages:W??Y.userImages,userFiles:j??Y.userFiles};if(Z==="steer"||Y.delivery==="steer")$.pendingPrompts.unshift({...A,delivery:"steer"});else $.pendingPrompts.push(A)}else{let Y={id:`pending_${Date.now()}_${fS(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(Y);else $.pendingPrompts.push(Y)}return i0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(f<0)return{prompts:i0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:i0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:i0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),i0($)}clear($){return $.pendingPrompts.length=0,[]}}class s7{deps;service=new zK;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:i0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,Q&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=S9(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function S9($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function i0($){return $.pendingPrompts.map(S9)}function JS($,f,J,Q){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(Q==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}_0();class e7{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let Q=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=NZ(J),j=!!Q&&(!W.agentId||W.agentId===o7(Q.agent));qZ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:o7(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(xW(J,f),f.type==="agent_event"){let Q={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};qZ(Q,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let Q=d1({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:o7(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(Q)J$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await gW($,f,this.deps.invokeBackendOptional),J)mW(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let Y=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!Y)return;let A=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!A)return;await Y.ingestEvent(A);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let Q=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:W,delivery:j})}handlePluginLog($,f,J){let Q=this.deps.getSession($),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!f||typeof f!=="object")return;let W=f,j=typeof W.message==="string"?W.message:"";if(!j)return;let X=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(X.sessionId??=$,typeof W.pluginName==="string"&&W.pluginName)X.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,X);return}if(W.level==="error"){if(Z.error)Z.error(j,X);else Z.log(j,{...X,severity:"error"});return}Z.log(j,X)}}function o7($){return $.getAgentId()}function $3($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:R$($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function f3($,f){let J=$[f];return typeof J==="function"?J:null}async function OK($,f,...J){let Q=f3($,f);if(!Q)throw Error(`session service method not available: ${f}`);return Promise.resolve(Q.apply($,J))}async function MK($,f,...J){let Q=f3($,f);if(!Q)return;await Promise.resolve(Q.apply($,J))}async function TK($,f,...J){let Q=f3($,f);if(!Q)return;return await Promise.resolve(Q.apply($,J))}j1();_0();function J3($,f,J){return{onSubAgentEvent:(Q)=>$.onAgentEvent(J,f,Q),onSubAgentStart:(Q)=>{let Z=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let W=d1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(W)J$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...W});H8(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...W}),$.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=$.getSession(J)?.runtime.teamRuntime,W=$.subAgentStarts.get(Q.subAgentId),j=W?Date.now()-W.startedAt:0,X=Q.result?.text?Q.result.text.split(`
701
- `).length:0;H8(f.telemetry,{event:"ended",ulid:J,durationMs:j,outputLines:X,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...d1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,Q)}}}function Q3($,f,J,Q){let Z=J3($,f,J);return F$({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let j=f.enableTools?Jf({cwd:f.cwd,...v0[c1({mode:f.mode})],executors:Q}):[];if(f.enableSpawnAgent)j.push(Q3($,f,J,Q));return x$(j)},...Z})}import{readFile as QS,stat as ZS}from"node:fs/promises";var WS=20480000;async function NK($){let f=await ZS($);if(!f.isFile())throw Error("Path is not a file");if(f.size>WS)throw Error("File is too large to read into context.");let J=await QS($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var qK=5000;function DJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function KS($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=DJ(f.inputTokens),Q=DJ(f.outputTokens),Z=DJ(f.cacheReadTokens),W=DJ(f.cacheWriteTokens),j=DJ(f.totalCost);if(J===void 0||Q===void 0||Z===void 0||W===void 0||j===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:Z,cacheWriteTokens:W,totalCost:j}}function GS($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class U1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new t4;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new y$;constructor($){let f=XS();if(f)BS(f);let J=S1($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new n2,this.createAgentInstance=$.createAgent??((Q)=>new B$(Q)),this.defaultCapabilities=L0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new L1,this.oauthTokenManager=$.oauthTokenManager??new t7({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new s7({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 e7({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,Z,W)=>{this.invoke("persistSessionMessages",Q,Z,W)},enqueuePendingPrompt:(Q,Z)=>this.pendingPromptsController.enqueue(Q,Z),invokeBackendOptional:(Q,...Z)=>this.invokeOptional(Q,...Z)})}async startSession($){let f=$.source??R0.CLI,J=s(),Q=$.config.sessionId?.trim()??"",Z=Q||AS(),W=$,j=W.initialMessages??[],X=j.length>0?K2(j):K0(),Y=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Y)throw Error("session service method not available: ensureSessionsDir");let A=Z3(Y,Z),V=Z3(A,`${Z}.messages.json`),H=Z3(A,`${Z}.json`),B=R$($.config),K=y0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:W.config.cwd,workspace_root:B,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,messages_path:V}),G;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",Z);if(C)K=C,G={manifestPath:H,messagesPath:C.messages_path||V,manifest:C}}let P=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:A,rootMessagesPath:G?.messagesPath??V,manifest:K});this.usageBySession.set(Z,X),this.aggregateUsageBySession.set(Z,P);let F=L0(this.defaultCapabilities,$.capabilities),D=F?.toolExecutors??this.toolExecutors,z=$.localRuntime,T=z?.extensionContext?.logger??z?.logger,L=z?.extensionContext?.automation,U,w={getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,G0,Q0)=>this.eventBridge.dispatchAgentEvent(C,G0,Q0),invokeBackendOptional:(C,...G0)=>this.invokeOptional(C,...G0)};U=await QV({input:W,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,C.payload,T);return}this.eventBridge.handlePluginEvent(Z,C,L)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(Z,C),U.config.onTeamEvent?.(C)},createSpawnTool:()=>Q3(w,U.config,Z,D),createSubAgentLifecycleCallbacks:(C)=>J3(w,C,Z),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(Z,()=>C)}});let h=await this.runtimeBuilder.build(U.runtimeBuilderInput),I=U.config,o=U.providerConfig;if(h.teamRuntime&&!I.teamName?.trim())I.teamName=h.teamRuntime.getTeamName();let V0=[...h.tools,...I.extraTools??[]],$0=h.extensions??U.extensions,t={sessionId:Z,providerId:o.providerId,modelId:o.modelId,apiKey:o.apiKey,baseUrl:o.baseUrl,headers:o.headers,knownModels:o.knownModels,providerConfig:o,thinking:I.thinking,reasoningEffort:I.reasoningEffort??o.reasoningEffort,systemPrompt:I.systemPrompt,maxIterations:I.maxIterations,execution:I.execution,prepareTurn:g8(I),tools:V0,hooks:U.hooks,extensions:$0,hookErrorMode:I.hookErrorMode,initialMessages:U.effectiveInput.initialMessages,userFileContentLoader:NK,toolPolicies:U.toolPolicies,requestToolApproval:U.requestToolApproval?async(C)=>{let G0=U.requestToolApproval,Q0=this.sessions.get(Z);if(Q0)await this.markTurnPending(Q0);try{if(!G0)return{approved:!1,reason:"Tool approval callback is not configured."};return await G0(C)}finally{let w0=this.sessions.get(Z);if(w0?.status==="pending")await this.markTurnRunning(w0)}}:void 0,telemetry:I.telemetry,onConsecutiveMistakeLimitReached:I.onConsecutiveMistakeLimitReached,completionPolicy:h.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(Z);return C?WJ(C.prompt,C.mode??I.mode):void 0},logger:h.logger??I.logger,extensionContext:I.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(Z,I,C)};t.hooks={...t.hooks,onEvent:async(C)=>{if(await U.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let G0=this.sessions.get(Z);if(!G0)return;let Q0=G0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,Q0,I.systemPrompt)}catch(w0){I.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:w0}),yf(I.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:w0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:I.providerId,modelId:I.modelId}})}}};let t0=this.createAgentInstance(t);if(t.onEvent)t0.subscribeEvents(t.onEvent);h.registerLeadAgent?.(t0);let E$=d1({agentId:t0.getAgentId(),conversationId:t0.getConversationId(),teamId:h.teamRuntime?.getTeamId(),teamName:h.teamRuntime?.getTeamName(),teamRole:h.teamRuntime?"lead":void 0});if(WV(I,Z,Q.length>0,B,E$),E$)J$(I.telemetry,{ulid:Z,modelId:I.modelId,provider:I.providerId,...E$});if(h.teamRuntime)uJ(I.telemetry,{ulid:Z,teamId:h.teamRuntime.getTeamId(),teamName:h.teamRuntime.getTeamName(),leadAgentId:t0.getAgentId(),restoredFromPersistence:h.teamRestoredFromPersistence===!0});let i={sessionId:Z,config:I,sessionMetadata:W.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:h,agent:t0,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:U.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,i),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(i),await this.invoke("persistSessionMessages",i.sessionId,j,i.config.systemPrompt),!W.prompt?.trim())await this.updateStatus(i,"completed",0)}let _1;try{if(W.prompt?.trim())if(_1=await this.executeTurn(i,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!i.interactive)await this.finalizeSingleRun(i,_1.finishReason);else await this.completeInteractiveTurn(i,_1.finishReason)}catch(C){if(i.interactive&&i.aborting)_1=await this.completeAbortedInteractiveTurn(i);else throw yf(i.config.telemetry,{component:"core",operation:"session.start",error:C,severity:"error",handled:!1,context:{sessionId:i.sessionId,providerId:i.config.providerId,modelId:i.config.modelId}}),await this.failSession(i),C}return{sessionId:Z,manifest:K,manifestPath:H,messagesPath:V,result:_1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let Q=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),Q=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw yf(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=qW(this.usageBySession.get($)),J=qW(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&!J0(f.status)){await this.releaseSessionRuntime(f,"session_stop");return}if(f.interactive&&f.agent.canStartRun()){await this.shutdownSession(f,{status:this.resolveInteractiveStopStatus(f),exitCode:this.resolveInteractiveStopExitCode(f),shutdownReason:"session_stop",endReason:"stopped"});return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&!J0(J.status)?this.releaseSessionRuntime(J,$):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return $3(f);let J=$.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return X4(Q);let Z=await this.readManifest(J);return Z?p5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(X4),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift($3(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return N$(J.messagesPath);let Q=await this.readManifest(f);return N$(Q?.messages_path)}async dispatchHookEvent($){await HH($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),Q=J.prompt.trim();if(!Q)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,Q,J.userImages,J.userFiles);while(vW($,Z.finishReason)){let W=await cW($);if(W.length===0)break;let j=uW($,W);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(ZJ($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),Q=K0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,Q){let Z=$.started||$.agent.getMessages().length>0,W=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??K0(),X=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=K0(),$.turnUsageByAgent=new Map,kJ($.config.telemetry,$.sessionId,$.config.mode),cf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let Y=Z?()=>$.agent.continue(f,J,Q):()=>$.agent.run(f,J,Q),A=await this.runWithAuthRetry($,Y,W);$.started=!0;let V=v6(A.messages,A,W);$.persistedMessages=V;let H=A4($.turnUsageByAgent?.values()??[]),B=Y0(j,A.usage),K=Y0(Y0(K0(),A.usage),H),G=Y0(X,K);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:G.totalCost,usage:B,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,V,$.config.systemPrompt),this.observeTaskCompletionTool($,A),A}catch(Y){throw yf($.config.telemetry,{component:"core",operation:"session.turn",error:Y,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),Y}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((Q)=>Q.name===H0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,A8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,f){let J=R$($.config),Q=HS(f.prompt).trim();if(!Q)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await Q2(Q,J);jV($.config.telemetry,Z);let W=WJ(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),X=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),Y=Array.from(new Set([...j,...X]));return{prompt:W,userImages:f.userImages,userFiles:Y.length>0?Y:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=R$($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(ZJ($))return;let J=f==="aborted"||$.aborting,Q=f==="error";await this.shutdownSession($,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)A8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});o5($);let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),yf($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){Q("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),yf($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,J0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=Q.endedAt??s(),$.endedAt=J0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(Q){if(!l$($.config.providerId)||!VS(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(Q){if(Q instanceof y9)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=new h1($);throw yf(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>YS(Q)?Q:W3($,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return d1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=Y0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let Q=W3(f),Z=`${J}.messages.json`,W;try{W=jS($)}catch{return K0()}let j=K0();for(let X of W){if(!X.endsWith(".messages.json"))continue;if(X===Z)continue;let Y=W3($,X);if(Y===Q)continue;let A=await N$(Y);if(A.length===0)continue;j=Y0(j,K2(A))}return j}withPersistedAggregateUsageFloor($,f){let J=KS(f.metadata?.aggregateUsage);if(J)return GS($,J);let Q=f.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:G1({session:f,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),qK))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(qK)).find((Q)=>Q.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return OK(this.sessionService,$,...f)}invokeOptional($,...f){return MK(this.sessionService,$,...f)}invokeOptionalValue($,...f){return TK(this.sessionService,$,...f)}}function PS($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function RS($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function PK($={}){let f=new U1({sessionService:new D1(new P1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||R0.CLI,interactive:!1,config:{providerId:FS(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:RS(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:PS(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}import{resolveClineBuildEnv as LG}from"@cline/shared";function DS($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
702
- `).trim()||void 0}var wK=120,j3="...";function GJ($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=wK)return f;let J=wK-Buffer.byteLength(j3,"utf8");if(J<=0)return j3;let Q="";for(let Z of f){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${j3}`}async function CK($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await N$(J)].reverse().find((Y)=>Y.role==="assistant"),W=Z?DS(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:GJ(W&&W.length>0?W:X.length>0?X:j),severity:"info"}}import{captureSdkError as k9,createSessionId as iS}from"@cline/shared";import{createSessionId as zS}from"@cline/shared";import{createSessionId as _S}from"@cline/shared";function US($){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 LS($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())f.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())f.parentAgentId=$.parentAgentId;if($.agentId?.trim())f.agentId=$.agentId;if($.conversationId?.trim())f.conversationId=$.conversationId;if($.messagesPath?.trim())f.messagesPath=$.messagesPath;if($.prompt?.trim())f.prompt=$.prompt;if($.provider?.trim())f.provider=$.provider;if($.model?.trim())f.model=$.model;if($.source?.trim())f.source=$.source;if(typeof $.pid==="number")f.pid=$.pid;return Object.keys(f).length>0?f:void 0}function E9($,f,J,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:US($.status),participants:f?[...f.participants.values()]:[],metadata:LS($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function d($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function v($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function h9($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function b0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function Sf($,f,J){return{version:"v1",event:$,eventId:_S("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function n0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let Q=await $.sessionHost.getAccumulatedUsage?.(f);return E9(J,$.sessionState.get(f),Q?.usage,Q?.aggregateUsage)}async function a0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[Q,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return G1({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function b9($,f,J,Q,Z={}){let W=$.sessionState.get(f);if(W){if(Z.interactive!==void 0)W.interactive=Z.interactive;if(!W.participants.has(J))W.participants.set(J,{clientId:J,attachedAt:Date.now(),role:Q});return W}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(f,j),j}async function X3($,f){let J=zS("approval_"),Q=f.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((W)=>{$.pendingApprovals.set(J,{sessionId:Q,resolve:W}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},Q))})}function Y3($,f,J){let Q=$.pendingApprovals.get(f);if(!Q)return;return $.pendingApprovals.delete(f),Q.resolve(J),{sessionId:Q.sessionId}}function A3($,f,J){let Q=0;for(let[Z,W]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:W.sessionId}))continue;$.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function yK($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return v(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,W=f.payload?.approved===!0,j=Y3($,J,{approved:W,reason:Z});if(!j)return v(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),d(f,{approvalId:J,approved:W})}import{createSessionId as TS}from"@cline/shared";function OS($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var SK={debug:10,info:20,warn:30,error:40,silent:50};function MS(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function c($,f,J={}){if(SK[$]<SK[MS()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,OS(W)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function V3($,f){let J=f instanceof Error?f.stack||f.message:String(f);c("error",$,{error:J})}async function EK($,f,J,Q,Z,W){let j=TS("capreq_"),X=performance.now();return c("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((Y,A)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(V)=>{if(c(V.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-X)}),!V.ok){A(Error(V.error||`Capability ${J} was rejected by ${Z}.`));return}Y(V.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},f)),c("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function hK($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return v(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==Q.targetClientId)return v(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return v(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return Q.onProgress?.(W),d(f,{requestId:J})}function S$($,f,J){let Q=0;for(let[Z,W]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...W}))continue;$.pendingCapabilityRequests.delete(Z),c("warn","capability.request.cancelled",{requestId:Z,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,reason:J}),W.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:W.capabilityName,targetClientId:W.targetClientId,ok:!1,cancelled:!0,error:J},W.sessionId)),Q+=1}return Q}async function bK($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",Q=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!Q||!Z)return v(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,Q,W,Z);return d(f,j)}catch(W){return v(f,"capability_request_failed",W instanceof Error?W.message:String(W))}}function kK($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return v(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==Q.targetClientId)return v(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return v(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(J);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,X=f.payload?.ok===!0;return c(X?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,error:j}),Q.resolve({ok:X,payload:W,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,payload:W,error:j},Q.sessionId)),d(f,{requestId:J,ok:X})}import{createSessionId as NS}from"@cline/shared";function IK($,f){let J=f.payload,Q=J?.clientId?.trim()||f.clientId?.trim()||NS("client_");return $.clients.set(Q,{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),d(f,{clientId:Q})}function xK($,f){let J=f.clientId?.trim(),Q=J?$.clients.get(J):void 0;if(!J||!Q)return v(f,"client_not_found","Client is not registered with this hub.");let Z=h9(f.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return d(f)}function gK($,f,J){let Q=f.clientId?.trim();if(Q)$.clients.delete(Q),J(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return d(f)}function mK($,f){return d(f,{clients:[...$.clients.values()]})}var qS=30000;function wS($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function CS($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function yS($,f,J){let Q=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${f}`;return v($,g$,Q)}function SS($){return $?$:void 0}function ES($){let f=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(f&&Number.isFinite(f)&&f>0)return Math.floor(f);let J=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function hS($,f,J,Q){let Z=performance.now(),W=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:Q},X=setInterval(()=>{if(W)return;let V=Math.round(performance.now()-Z);c("warn","run.heartbeat",{...j,elapsedMs:V}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:V,...Q?{timeoutMs:Q}:{}},J.sessionId))},qS),Y=$.sessionHost.runTurn(J);Y.then((V)=>{if(!W)return;c("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:V?.finishReason})},(V)=>{if(!W)return;c("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:V})});let A;try{if(!Q)return await Y;return await Promise.race([Y,new Promise((V,H)=>{A=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${Q}ms.`;W=!0,clearInterval(X),H(Error(B)),c("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),A3($,(K)=>K.sessionId===J.sessionId,B),S$($,(K)=>K.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((K)=>{c("error","run.timeout_abort_failed",{...j,error:K})})},Q)})])}finally{if(W=!0,clearInterval(X),A)clearTimeout(A)}}async function vK($,f){let J=b0(f),Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return v(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let W=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,j=Array.isArray(W?.userFiles)?W.userFiles.filter((V)=>typeof V==="string"):void 0,X=ES(Q);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let Y;try{Y=await hS($,f,{sessionId:J,prompt:Z,mode:SS(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(W?.userImages)?W.userImages:void 0,userFiles:j,timeoutMs:X},X)}catch(V){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);if(b1(V))return yS(f,J,V);throw $.publish($.buildEvent("run.failed",{reason:"error",error:V instanceof Error?V.message:String(V)},J)),V}if(Y){let V=await a0($,J),H=CS(Y);if($.publish($.buildEvent(wS(Y.finishReason),{reason:Y.finishReason,...H?{error:H}:{},result:Y,...V?{snapshot:V}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let A=await a0($,J);return d(f,Y||A?{...Y?{result:Y}:{},...A?{snapshot:A}:{}}:void 0)}async function cK($,f){let J=b0(f),Q=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";A3($,(Z)=>Z.sessionId===J,Q);try{await $.sessionHost.abort(J,f.payload?.reason)}catch(Z){c("warn","run.abort_failed",{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J,error:Z})}finally{S$($,(Z)=>Z.sessionId===J,Q)}return d(f,{applied:!0})}async function uK($,f){let J=l2(f.payload?.payload);if(!J)return v(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),d(f,{applied:!0})}async function dK($,f){switch(f.type){case"chunk":return;case"agent_event":await bS($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,Q]=await Promise.all([n0($,f.payload.sessionId),a0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},f.payload.sessionId));return}case"ended":await kS($,f);return;default:return}}async function bS($,f){let{sessionId:J,event:Q}=f.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},J));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},J));break}return}if(Q.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function kS($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),Q=J===f.payload.reason||J==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,W]=await Promise.all([n0($,f.payload.sessionId),a0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await CK(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(Q)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...W?{snapshot:W}:{}},f.payload.sessionId))}import{createSessionId as rK,parseRuntimeConfigExtensions as iK}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as hi,HUB_COMPACTION_CAPABILITY as bi,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ki,HUB_HOOK_CAPABILITY_PREFIX as Ii,HUB_MISTAKE_LIMIT_CAPABILITY as xi,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as gi,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as mi,isHubToolExecutorName as IS}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as li,HUB_COMPACTION_CAPABILITY as pi,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ri,HUB_HOOK_CAPABILITY_PREFIX as ii,HUB_MISTAKE_LIMIT_CAPABILITY as ni,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ai,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ti}from"@cline/shared";var xS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Ef($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function gS($,f){let J=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",W=Ef($.inputSchema);if(!J||!Q||!W||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...Ef($.lifecycle)?{lifecycle:Ef($.lifecycle)}:{}}}function B3($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Z=Q,W=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(W==="tool"){let X=gS(Z,J);if(X)f.push(X);continue}if(W==="toolExecutor"){let X=Z.executor;if(!IS(X))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:X});continue}if(W==="hook"){let X=typeof Z.name==="string"?Z.name.trim():"";if(!X)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:X});continue}if(W==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...Ef(Z.config)?{config:Ef(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...Ef(Z.config)?{config:Ef(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function pK($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function mS($){return Object.hasOwn($,"update")?$.update:$}function UJ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function vS($){let f=($??[]).map(UJ).filter(Boolean);return f.length>0?new Set(f):void 0}function cS($,f,J){if(!J)return!0;let Q=UJ($),Z=UJ(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function H3($,f){let J=vS(f);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>cS(Q.id,Q.name,J))}function lK($,f){let J=async(Q,Z)=>{let W=UJ(Q),X=H3($,f).filter((B)=>B.id===W||UJ(B.name)===W||B.id.endsWith(`:${W}`)).filter((B)=>!B.disabled);if(X.length!==1)return X.length>1?`Skill "${Q}" is ambiguous. Use one of: ${X.map((B)=>B.id).join(", ")}`:`Skill "${Q}" not found.`;let Y=X[0].skill,A=Z?.trim(),V=A?`
703
- <command-args>${A}</command-args>`:"",H=Y.description?.trim()?`Description: ${Y.description.trim()}
704
-
705
- `:"";return`<command-name>${Y.name}</command-name>${V}
702
+ version = team_outcome_fragments.version + 1`,[Z,j.outcomeId,j.id,j.section,j.sourceAgentId,j.sourceRunId??null,j.content,j.status,j.reviewedBy??null,j.reviewedAt?j.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,J){let Q=$4($),Z=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Q]);if(Z.length===0)return[];let W=R3();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
703
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[J,W,Q]),Z.map((j)=>j.run_id)}handleTeamEvent($,J){this.appendTeamEvent($,J.type,J)}}function z3($={}){try{let J=new w2($);return J.init(),J}catch{let J=new DJ({teamDir:$.teamDir});return J.init(),J}}function F9($,J){return RS($,J)}function LS($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function _S($,J){return $.filter((Q)=>LS(Q.name,J))}function L3($,J){return E1(_S($,J))}var OS={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 TS($){let J=$.trim().toLowerCase();return OS[J]??J}function MS($,J){if(J.tools===void 0)return $;let Q=new Set(J.tools.map(TS));if(J.skills!==void 0)Q.add("skills");return $.filter((Z)=>Q.has(Z.name))}function U9(){return`team-${zS(5)}`}function D9($,J,Q,Z,W,j,f,X){let Y=c0[u1({mode:Q})],V=H8(J,Z,Q,W??V8);return L3(Q2({cwd:$,...Y,enableSkills:!!f,...V,executors:{...f?{skills:f}:{},...X??{}}}),j)}function qS($){return D9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,PS,$.toolExecutors).some((J)=>J.name==="skills")}var PS=async()=>"";async function NS($){let J=A0();if(!r1({filePath:J}))return{tools:[]};let Q=new L2({clientFactory:x8({settingsPath:J})}),Z;try{Z=await z2(Q,{filePath:J})}catch(X){await Q.dispose().catch(()=>{});let Y=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${Y}`),{tools:[]}}let W=Z.filter((X)=>X.disabled!==!0),j=await Promise.allSettled(W.map((X)=>m8({serverName:X.name,provider:Q}))),f=[];for(let[X,Y]of j.entries())if(Y.status==="fulfilled")f.push(...Y.value);else{let V=Y.reason instanceof Error?Y.reason.message:String(Y.reason);$?.log(`[mcp] Failed to load tools from MCP server "${W[X].name}", skipping: ${V}`)}return{tools:f,shutdown:async()=>{await Q.dispose()}}}function wS($,J){if(!$)return;for(let Q of $.getTeammateIds())try{$.shutdownTeammate(Q,J)}catch{}}function SS($){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 CS($){let J=c0[u1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??J.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??J.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class J4{teamRuntimeEntries=new Map;async build($){let{config:J,hooks:Q,extensions:Z,logger:W,telemetry:j,createSpawnTool:f,onTeamRestored:X,userInstructionService:Y,configExtensions:V,toolExecutors:H}=$,B=$.onTeamEvent??(()=>{}),A=CS(J),K=J.workspaceRoot??J.cwd,G=$.toolPolicies??J.toolPolicies,R=X1(),D=[],U=J.teamName?.trim()||U9(),F=J.sessionId?.trim()||U,O=A.enableSpawnAgent?d8({workspaceRoot:K}):{configs:[],errors:[]},T=O.configs.some((m)=>m.skills!==void 0),L=F9(V,"rules"),z=F9(V,"skills"),P=z||T,S=F9(V,"workflows"),b=F9(V,"plugins"),u=L||z||S,o=!1,J0=Boolean(Y),t=Y,o0;for(let m of O.errors)(W??J.logger)?.log?.(`[agents] Failed to load agent config at ${m.path}: ${m.error.message}`);if(!t&&(u||T))t=q$({skills:P?{workspacePath:K,includePluginSkills:b,pluginSkillDirectories:b?$.pluginSkillDirectories:void 0,pluginPaths:J.pluginPaths,cwd:J.cwd}:{workspacePath:K},rules:{workspacePath:J.cwd},workflows:{workspacePath:J.cwd}});if(t)await t.start().catch(()=>{});let b$=A.enableTools&&z&&Boolean(t)&&t?.hasConfiguredSkills(J.skills)===!0&&qS({cwd:J.cwd,providerId:J.providerId,mode:A.mode,modelId:J.modelId,toolRoutingRules:J.toolRoutingRules,toolPolicies:G,toolExecutors:H}),n=t&&u?t.createExtension({includeRules:L,includeSkills:z,includeWorkflows:S,registerSkillsTool:b$,allowedSkillNames:J.skills}):void 0,O1=n?[...Z??J.extensions??[],n]:Z??J.extensions;if(A.enableTools){if(D.push(...D9(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H)),!A.disableMcpSettingsTools){let m=await NS(J.logger);D.push(...m.tools),o0=m.shutdown}}let C,F0=A.enableAgentTeams?z3():void 0,f0=F0?.loadRuntime(F),w0=f0?.state,h2=f0?.teammates??[],T1=new Map(h2.map((m)=>[m.agentId,m])),f1=J.sessionId||U,X4,k2=[],SJ=!1,M1=G$({providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey??"",baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:Q,extensions:O1,logger:W??J.logger,telemetry:$.telemetry??J.telemetry,workspaceMetadata:J.workspaceMetadata});if(A.enableSpawnAgent){if(O.configs.length>0)D.push(...L3(l8({configProvider:M1,agents:O.configs,createSubAgentTools:(m)=>A.enableTools?MS(D9(J.cwd,m.providerId??J.providerId,A.mode,m.modelId??J.modelId,J.toolRoutingRules,G,m.skills!==void 0&&t?.createSkillsExecutor?t.createSkillsExecutor(m.skills):void 0,H),m):[],hookErrorMode:J.hookErrorMode,toolPolicies:G,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),G))}if(!this.teamRuntimeEntries.has(f1))this.teamRuntimeEntries.set(f1,{delegatedAgentConfigProvider:M1});let CJ=()=>{if(!A.enableAgentTeams)return;let m=this.teamRuntimeEntries.get(f1)??{delegatedAgentConfigProvider:M1};if(this.teamRuntimeEntries.set(f1,m),C=m.runtime,!C){if(C=new T2({teamName:U,leadAgentId:J.sessionId||"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(Q0)=>{if(B(Q0),C&&F0){if(Q0.type==="teammate_spawned"&&Q0.teammate?.rolePrompt){let q1={agentId:Q0.agentId,rolePrompt:Q0.teammate.rolePrompt,modelId:Q0.teammate.modelId,maxIterations:Q0.teammate.maxIterations};T1.set(q1.agentId,q1)}if(Q0.type==="teammate_shutdown"&&!SS(Q0.reason))T1.delete(Q0.agentId);F0.handleTeamEvent(F,Q0),F0.persistRuntime(F,C.exportState(),Array.from(T1.values()))}}}),w0)C.hydrateState(w0),SJ=!0;m.runtime=C}if(!o){if(!C)return;o=!0;let Q0=K8({runtime:C,leadAgentId:J.sessionId||"lead",restoredFromPersistence:Boolean(w0),restoredTeammates:h2,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(q1)=>{k2=q1,X4?.addTools(q1)},createBaseTools:A.enableTools?()=>D9(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H):void 0,teammateConfigProvider:M1});if(SJ)C.recoverActiveRuns("runtime_recovered");if(Q0.restoredFromPersistence)X?.();D.push(...Q0.tools)}return C};if(A.enableSpawnAgent&&f){let m=f();D.push({...m,execute:async(Q0,q1)=>{return CJ(),m.execute(Q0,q1)}})}if(A.enableAgentTeams)CJ();let I2=L3(D,G),a9=I2.some((m)=>m.name==="submit_and_exit"&&m.lifecycle?.completesRun===!0),yJ=A.enableAgentTeams?()=>{let m=this.teamRuntimeEntries.get(f1)?.runtime;if(!m)return;let Q0=m.listTasks(),q1=Q0.some((t1)=>t1.status==="in_progress"||t1.status==="pending"),gj=m.listRuns({}),WF=gj.some((t1)=>t1.status==="running"||t1.status==="queued");if(q1||WF){let t1=Q0.filter((I0)=>I0.status==="in_progress"||I0.status==="pending").map((I0)=>`${I0.id} (${I0.status}): ${I0.title}`).join(", "),mj=gj.filter((I0)=>I0.status==="running"||I0.status==="queued").map((I0)=>`${I0.id} (${I0.status})`).join(", "),s9=[];if(t1)s9.push(`Unfinished tasks: ${t1}`);if(mj)s9.push(`Active runs: ${mj}`);return`[SYSTEM] You still have team obligations. ${s9.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,ZF=a9?{requireCompletionTool:!0,...yJ?{completionGuard:yJ}:{}}:yJ?{completionGuard:yJ}:void 0;return{tools:I2,logger:W??J.logger,telemetry:j??J.telemetry,teamRuntime:C,teamRestoredFromPersistence:Boolean(w0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(f1)?.delegatedAgentConfigProvider??M1,extensions:O1,completionPolicy:ZF,registerLeadAgent:(m)=>{if(X4=m,k2.length>0)m.addTools(E1(k2,[...R]))},shutdown:async(m)=>{if(wS(C,m),this.teamRuntimeEntries.delete(f1),await o0?.(),!J0)t?.stop()}}}}var $K={};w($K,{requestDesktopToolApproval:()=>O3});import{mkdir as yS,readFile as ES,unlink as bS,writeFile as hS}from"node:fs/promises";import{join as eA}from"node:path";function kS($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function IS($){return new Promise((J)=>setTimeout(J,$))}async function _3($){try{await bS($)}catch{}}async function O3($,J={}){let Q=J.approvalDir?.trim(),Z=J.sessionId?.trim();if(!Q||!Z)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await yS(Q,{recursive:!0});let W=kS(`${$.toolCallId}`),j=eA(Q,`${Z}.request.${W}.json`),f=eA(Q,`${Z}.decision.${W}.json`),X=J.nowIso??(()=>new Date().toISOString());await hS(j,`${JSON.stringify({requestId:W,sessionId:Z,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
704
+ `,"utf8");let Y=J.timeoutMs??300000,V=J.pollIntervalMs??200,H=Date.now();while(Date.now()-H<Y){try{let B=await ES(f,"utf8"),A=JSON.parse(B),K={approved:A.approved===!0,reason:typeof A.reason==="string"?A.reason:void 0};return await Promise.all([_3(f),_3(j)]),K}catch{}await IS(V)}return await _3(j),{approved:!1,reason:"Tool approval request timed out"}}t0();var WK={};w(WK,{syncPluginMcpServersToSettings:()=>P3,removePluginMcpServersFromSettings:()=>UJ,disablePluginMcpServersInSettings:()=>N3});import{existsSync as xS,mkdirSync as gS,readFileSync as mS,writeFileSync as vS}from"node:fs";import{dirname as QK,isAbsolute as cS,relative as uS,resolve as JK}from"node:path";function S2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R9($,J){let Q=uS(JK($),JK(J));return Q===""||!Q.startsWith("..")&&!cS(Q)}function T3($){if(!xS($))return{mcpServers:{}};try{let J=JSON.parse(mS($,"utf8"));if(S2(J))return J}catch(J){throw Error(`Invalid MCP settings at "${$}": ${J instanceof Error?J.message:String(J)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function M3($){if(S2($.mcpServers))return{...$.mcpServers};return{}}function q3($,J,Q){gS(QK($),{recursive:!0}),vS($,`${JSON.stringify({...J,mcpServers:Q},null,2)}
705
+ `,"utf8")}function ZK($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((J)=>J.trim()).filter((J)=>J.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((J)=>J.trim()).filter((J)=>J.length>0))]}}function L9($){if(!S2($))return;let J=$.metadata;return S2(J)?J:void 0}function z9($,J){let Q=L9($);if(!Q||Q.source!=="plugin")return!1;let Z=typeof Q.pluginName==="string"?Q.pluginName:typeof Q.plugin==="string"?Q.plugin:void 0,W=typeof Q.pluginPath==="string"?Q.pluginPath:void 0;if(J.pluginName&&Z===J.pluginName){if(!J.pluginPath||W===J.pluginPath)return!0}if(W&&J.pluginPath&&(W===J.pluginPath||R9(J.pluginPath,W)||R9(W,J.pluginPath)))return!0;if(Z&&J.pluginNames?.some((j)=>j===Z))return!0;if(W&&J.pluginPaths?.some((j)=>W===j||R9(j,W)||R9(W,j)))return!0;return!1}function dS($){let J=S2($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:QK($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...J,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function lS($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let J=await O8({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Q=[],Z=[],W=(J.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of J.extensions??[]){let f=j.__clinePluginPath;if(!f)continue;if(!j.setup){Q.push({pluginName:j.name,pluginPath:f});continue}let X=[],Y={registerTool:(V)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(V)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');X.push(V)}};try{await j.setup(Y,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(V){W.push({pluginPath:f,pluginName:j.name,message:V instanceof Error?V.message:String(V)});continue}Q.push({pluginName:j.name,pluginPath:f});for(let V of X)Z.push({pluginName:j.name,pluginPath:f,server:{...V,metadata:{...V.metadata??{},source:"plugin",pluginName:j.name,pluginPath:f}}})}return{plugins:Q,servers:Z,failures:W}}finally{await J.shutdown().catch(()=>{})}}async function P3($){let J=$.settingsPath??A0(),Q={mutations:[],failures:[]},Z;try{Z=await lS($)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}Q.failures.push(...Z.failures);let W;try{W=T3(J)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}let j=M3(W),f=new Map,X=new Map;for(let V of Z.plugins)f.set(V.pluginPath,new Set),X.set(V.pluginPath,V.pluginName);let Y=rQ(Z.servers.map((V)=>({server:V.server,owner:V,ownerLabel:V.pluginName})));for(let V of Y){let H=V.owner;if(!f.has(H.pluginPath))f.set(H.pluginPath,new Set);if(V.name)f.get(H.pluginPath)?.add(V.name);if(!V.registration){Q.mutations.push({name:V.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:V.loadError??"invalid MCP server registration"});continue}let B=j[V.registration.name];if(B!==void 0){if(!z9(B,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[V.registration.name]=dS({registration:V.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:S2(B)?B:void 0}),Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:B===void 0?"created":"updated"})}for(let[V,H]of Object.entries(j)){let B=L9(H),A=typeof B?.pluginPath==="string"?B.pluginPath:"",K=f.get(A);if(K&&z9(H,{pluginPath:A})&&!K.has(V))delete j[V],Q.mutations.push({name:V,pluginName:typeof B?.pluginName==="string"?B.pluginName:X.get(A)??"plugin",pluginPath:A,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Q.mutations.some((V)=>V.action!=="skipped"))try{q3(J,W,j)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)})}return Q}function N3($){let J=$.settingsPath??A0(),Q;try{Q=T3(J)}catch{return[]}let Z=M3(Q),W=ZK($),j=[];for(let[f,X]of Object.entries(Z)){if(!S2(X)||!z9(X,W))continue;let Y=L9(X);Z[f]={...X,disabled:!0},j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"disabled"})}if(j.length>0)q3(J,Q,Z);return j}function UJ($){let J=$.settingsPath??A0(),Q;try{Q=T3(J)}catch{return[]}let Z=M3(Q),W=ZK($),j=[];for(let[f,X]of Object.entries(Z)){if(!z9(X,W))continue;let Y=L9(X);delete Z[f],j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"removed"})}if(j.length>0)q3(J,Q,Z);return j}t0();var YK={};w(YK,{uninstallPlugin:()=>k3});import{existsSync as Z4,readdirSync as pS,readFileSync as rS,rmdirSync as iS,rmSync as nS,statSync as aS}from"node:fs";import{basename as i0,dirname as C$,extname as sS,isAbsolute as oS,join as o1,relative as tS,resolve as Q4,sep as w3}from"node:path";import{discoverPluginModulePaths as eS,resolvePluginConfigSearchPaths as $C}from"@cline/shared/storage";var b3="_installed",JC="package",QC=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function S3($){return $.trim().toLowerCase()}function j1($,J){let Q=J?.trim();if(!Q)return;$.add(Q)}function ZC($){return $.replace(/-[0-9a-f]{12}$/i,"")}function C3($){let J=sS($);return J?$.slice(0,-J.length):$}function y3($){if(!Z4($))return;try{let J=JSON.parse(rS($,"utf8"));return typeof J.name==="string"?J.name.trim():void 0}catch{return}}function h3($,J){let Q=tS(J,$);return Q===""||!Q.startsWith("..")&&!oS(Q)}function jK($){let Q=Q4($).split(w3),Z=Q.lastIndexOf(b3);if(Z<0)return;let W=Q[Z+1];if(!W)return;let j=QC.get(W)??1,f=Z+2+j;if(Q.length<f)return;let X=Q.slice(0,f).join(w3)||w3;return Z4(X)?X:void 0}function _9($){try{return pS($,{withFileTypes:!0})}catch{return[]}}function WC($){let J=o1($,b3);if(!Z4(J))return[];let Q=[];for(let Z of _9(J)){if(!Z.isDirectory())continue;let W=o1(J,Z.name);if(Z.name==="git"){for(let j of _9(W)){if(!j.isDirectory())continue;let f=o1(W,j.name);for(let X of _9(f))if(X.isDirectory())Q.push(o1(f,X.name))}continue}for(let j of _9(W))if(j.isDirectory())Q.push(o1(W,j.name))}return Q.sort((Z,W)=>Z.localeCompare(W))}function fK($){try{return eS($)}catch{return[]}}function E3($){let J=fK($),Q=new Set;j1(Q,i0($)),j1(Q,ZC(i0($))),j1(Q,y3(o1($,"package.json"))),j1(Q,y3(o1($,JC,"package.json")));for(let Z of J)j1(Q,i0(Z)),j1(Q,C3(i0(Z)));return{installPath:$,entryPaths:J,names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!0}}function jC($,J){let Q=Q4($),Z=J.find((f)=>h3(Q,f));if(!Z)return;let W=C$(Q);while(W!==Z&&W!==C$(W)){if(Z4(o1(W,"package.json")))return W;W=C$(W)}let j=i0(Q);if((j==="index.ts"||j==="index.js")&&C$(Q)!==Z)return C$(Q);return Q}function XK($,J){let Q=jC($,J);if(!Q)return;let Z=new Set;return j1(Z,i0($)),j1(Z,C3(i0($))),j1(Z,i0(Q)),j1(Z,C3(i0(Q))),j1(Z,y3(o1(Q,"package.json"))),{installPath:Q,entryPaths:[$],names:[...Z].sort((W,j)=>W.localeCompare(j)),installed:!1}}function fC($){let J=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return $C(J).filter((Q)=>Z4(Q))}function XC($){let J=new Map;for(let Q of $){for(let Z of WC(Q))J.set(Z,E3(Z));for(let Z of fK(Q)){let W=jK(Z);if(W){if(!J.has(W))J.set(W,E3(W));continue}let j=XK(Z,$);if(j)J.set(j.installPath,j)}}return[...J.values()].sort((Q,Z)=>Q.installPath.localeCompare(Z.installPath))}function YC($,J){let Q=S3(J);if(!Q)return!1;if(S3($.installPath)===Q)return!0;return $.names.some((Z)=>S3(Z)===Q)}function VC($,J,Q){let Z=Q4($);for(let j of J){if(h3(Z,j.installPath))return j;if(j.entryPaths.some((f)=>Q4(f)===Z))return j}let W=jK(Z);if(W)return E3(W);if(Z4(Z))return XK(Z,Q);return}function HC($){let J=T0(),Q=J.disabledPlugins;if(!Q?.length)return;let Z=Q.filter((W)=>{let j=Q4(W);if(h3(j,$.installPath))return!1;return!$.entryPaths.some((f)=>Q4(f)===j)});if(Z.length===Q.length)return;y1({...J,disabledPlugins:Z})}function BC($){let J=C$($);while(J!==C$(J)&&i0(J)!==b3){try{iS(J)}catch{return}J=C$(J)}}function AC($){return`${$.names[0]??i0($.installPath)} at ${$.installPath}`}async function k3($){let J=fC($),Q=XC(J),Z=$.path?.trim(),W=$.name?.trim(),j;if(Z){if(j=VC(Z,Q,J),!j)throw Error(`No plugin found at ${Z}`)}else{if(!W)throw Error("plugin uninstall requires a plugin name");let X=Q.filter((Y)=>YC(Y,W));if(X.length===0)throw Error(`No plugin found matching "${W}"`);if(X.length>1)throw Error(`Multiple plugins match "${W}": ${X.map(AC).join(", ")}`);j=X[0]}let f=aS(j.installPath,{throwIfNoEntry:!1});if(!f)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(UJ({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),nS(j.installPath,{recursive:f.isDirectory(),force:!0}),HC(j),j.installed)BC(j.installPath);return{name:W||j.names[0]||i0(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var wK={};w(wK,{updateLocalProvider:()=>S9,saveLocalProviderSettings:()=>d3,saveLocalProviderOAuthCredentials:()=>i3,resolveLocalClineAuthToken:()=>a3,refreshProviderModelsFromSource:()=>l3,normalizeOAuthProvider:()=>p3,loginLocalProvider:()=>r3,loginAndSaveLocalProviderOAuthCredentials:()=>n3,listLocalProviders:()=>c3,getLocalProviderModels:()=>u3,ensureCustomProvidersLoaded:()=>P9,deleteLocalProvider:()=>C9,addLocalProvider:()=>v3});import*as N0 from"@cline/llms";import{existsSync as KC,mkdirSync as GC,readFileSync as FC,writeFileSync as DC}from"node:fs";import{mkdir as UC,readFile as RC,writeFile as zC}from"node:fs/promises";import{dirname as I3,join as LC}from"node:path";import*as b0 from"@cline/llms";import{ModelCapabilitySchema as _C,ProviderCapabilitySchema as OC,ProviderClientSchema as TC,ProviderProtocolSchema as MC}from"@cline/shared";import{z as i}from"zod";var qC=i.object({id:i.string().optional(),name:i.string().optional(),maxTokens:i.number().optional(),contextWindow:i.number().optional(),maxInputTokens:i.number().optional(),capabilities:i.array(_C).optional(),supportsVision:i.boolean().optional(),supportsAttachments:i.boolean().optional(),supportsReasoning:i.boolean().optional()}).passthrough(),PC=i.object({name:i.string(),baseUrl:i.string(),defaultModelId:i.string().optional(),protocol:MC.optional(),client:TC.optional(),capabilities:i.array(OC).optional(),modelsSourceUrl:i.string().optional()}).passthrough(),VK=i.object({provider:PC.optional(),models:i.record(i.string(),qC).optional()}).passthrough(),HK=i.object({version:i.literal(1),providers:i.record(i.string(),VK)}),NC=i.object({version:i.literal(1),providers:i.record(i.string(),i.unknown())}),O9=new Set;function BK($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function C2($){return LC(I3($.getFilePath()),"models.json")}function T9(){return{version:1,providers:{}}}function AK($){let J=NC.safeParse($);if(!J.success)return T9();let Q={};for(let[Z,W]of Object.entries(J.data.providers)){let j=VK.safeParse(W);if(j.success)Q[Z]=j.data}return{version:1,providers:Q}}function x3($){if(!KC($))return T9();try{let J=FC($,"utf8");return AK(JSON.parse(J))}catch{}return T9()}async function W4($){try{let J=await RC($,"utf8");return AK(JSON.parse(J))}catch{}return T9()}function KK($,J){GC(I3($),{recursive:!0});let Q=HK.parse(J);DC($,`${JSON.stringify(Q,null,2)}
706
+ `,"utf8")}async function M9($,J){await UC(I3($),{recursive:!0});let Q=HK.parse(J);await zC($,`${JSON.stringify(Q,null,2)}
707
+ `,"utf8")}function GK($,J){return{id:$,name:J.name??$,supportsAttachments:J.capabilities?.includes("files"),supportsVision:J.capabilities?.includes("images"),supportsReasoning:J.capabilities?.includes("reasoning")||J.thinkingConfig!=null}}function FK($){if(!$||$.length===0)return;let J=new Set;if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("tools"))J.add("tools");return J.size>0?[...J]:void 0}function DK($){let J=new Set;if(!$||$.length===0)return[...J];if($.includes("streaming"))J.add("streaming");if($.includes("tools"))J.add("tools");if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("vision"))J.add("images"),J.add("files");return[...J]}function wC($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function UK($,J){return $??J??"openai-chat"}function RK($,J,Q){return $??Q??(J==="openai-responses"?"openai":"openai-compatible")}function zK($,J,Q){let Z=new Set(J?.capabilities??Q??[]);if(J?.supportsVision)Z.add("images");if(J?.supportsAttachments)Z.add("files");if(J?.supportsReasoning)Z.add("reasoning");return{id:$,name:J?.name??$,maxTokens:J?.maxTokens,contextWindow:J?.contextWindow,maxInputTokens:J?.maxInputTokens,capabilities:Z.size>0?[...Z]:void 0}}function SC($,J){for(let[Q,Z]of Object.entries(J??{})){let W=Z.id?.trim()||Q.trim();if(!W)continue;b0.registerModel($,W,zK(W,Z))}}function CC($,J,Q){return{...J??{},id:$,name:J?.name??$,capabilities:J?.capabilities??Q}}function yC($){return Object.assign({},...b0.resolveProviderModelCatalogKeys($).map((Q)=>b0.getGeneratedModelsForProvider(Q)))}function EC($){let J=$.provider.trim();if(!J||b0.isBuiltInProviderId(J))return;let Q=$.baseUrl?.trim();if(!Q)return;let Z=b0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J],W=yC(J),j=DK($.capabilities),f=j.length>0?j:void 0,X=$.model?.trim(),Y={...W,...Z?.models??{}};if(X)Y[X]=CC(X,Y[X],f);let V=Object.keys(Y).filter(Boolean),H=X||V[0];if(!H)return;let B=UK($.protocol,Z?.provider.protocol),A=RK($.client,B,Z?.provider.client);b0.registerProvider({provider:{id:J,name:Z?.provider.name??BK(J),description:Z?.provider.description,protocol:B,client:A,baseUrl:Q,modelsSourceUrl:Z?.provider.modelsSourceUrl,defaultModelId:H,capabilities:FK($.capabilities)??Z?.provider.capabilities,source:"file"},models:Y})}function q9($){for(let J of Object.values($.providers))EC(J.settings)}function RJ($,J){let Q=J.models??{};if(!wC(J.provider)){SC($,Q);return}let Z=DK(J.provider.capabilities),W=Object.entries(Q).map(([V,H])=>({id:H.id?.trim()||V.trim(),model:H})).filter(({id:V})=>V.length>0),j=J.provider.defaultModelId?.trim()||W[0]?.id||"default",f=UK(J.provider.protocol,void 0),X=RK(J.provider.client,f,void 0),Y=Object.fromEntries(W.map(({id:V,model:H})=>[V,{...zK(V,H,Z.length>0?Z:void 0),status:"active"}]));b0.registerProvider({provider:{id:$,name:J.provider.name.trim()||BK($),protocol:f,client:X,baseUrl:J.provider.baseUrl,modelsSourceUrl:J.provider.modelsSourceUrl,defaultModelId:j,capabilities:FK(J.provider.capabilities),source:"file"},models:Y})}function LK($){let J=C2($);if(O9.has(J))return;let Q=x3(J);for(let[Z,W]of Object.entries(Q.providers))RJ(Z,W);O9.add(J)}async function P9($){let J=C2($);if(O9.has(J))return;let Q=await W4(J);for(let[Z,W]of Object.entries(Q.providers))RJ(Z,W);O9.add(J)}var bC="cline-pass";function hC($){return $.apiKey??$.auth?.apiKey}function kC($){return($.auth?.accessToken?.trim()??"").length>0}function OK($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function IC($){let J=$.split(/\s+/).filter(Boolean);if(J.length===0)return"?";if(J.length===1)return J[0].slice(0,2).toUpperCase();return`${J[0][0]}${J[1][0]}`.toUpperCase()}function xC($){let J=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Q=0;for(let Z of $)Q=Q*31+Z.charCodeAt(0)>>>0;return J[Q%J.length]}function TK($){return Object.entries($).sort(([J],[Q])=>J.localeCompare(Q)).map(([J,Q])=>GK(J,Q))}async function gC($,J){let Q=await N0.getModelsForProvider($);if(!J)return Q;let Z=await C6($,{loadPrivateOnAuth:!0,failOnError:!1},J);return Z?.knownModels?{...Q,...Z.knownModels}:Q}function g3($){return[...new Set(($??[]).map((J)=>J.trim()).filter(Boolean))]}function mC($){if(!$?.length)return;return[...new Set($)]}function vC($,J){return mC([...$??[],...J??[]])}function cC($){let J=$?.popularRank;return typeof J==="number"&&Number.isFinite(J)?J:Number.MAX_SAFE_INTEGER}function uC($){if(!$||typeof $!=="object")return!1;let J=$;return typeof J.path==="string"&&J.path.trim().length>0&&typeof J.label==="string"&&J.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(J.type))}function dC($){let J=$?.configFields;if(!Array.isArray(J))return;return J.filter(uC)}var N9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},_K={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function lC($){if(!$)return[N9];if($.source!=="system")return $.baseUrl?[N9,_K]:[N9];let J=[];if($.env?.length)J.push(N9);if($.baseUrl)J.push(_K);return J}function pC($,J){return J.split(".").reduce((Q,Z)=>{if(!Q||typeof Q!=="object")return;return Q[Z]},$)}function rC($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function iC($,J,Q){if(!$?.length)return;let Z={};for(let W of $){let f=rC(W.path==="baseUrl"&&J?.baseUrl===void 0?Q?.baseUrl:pC(J,W.path))??W.defaultValue;if(f!==void 0)Z[W.path]=f}return Z}function MK($){let J=Object.entries($??{}).filter(([Q])=>Q.trim().length>0);return J.length>0?Object.fromEntries(J):void 0}function m3($,J){let Q=J?.includes("vision")??!1,Z=J?.includes("reasoning")??!1;return Object.fromEntries($.map((W)=>[W,{id:W,name:W,supportsVision:Q,supportsAttachments:Q,supportsReasoning:Z}]))}async function qK($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let J=$.modelsSourceUrl?await fQ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...J])]}function PK($,J){let Q=$.read(),Z=!1;if(Q.providers[J])delete Q.providers[J],Z=!0;if(Q.lastUsedProvider===J)delete Q.lastUsedProvider,Z=!0;if(Z)$.write(Q);N0.unregisterProvider(J)}async function v3($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=J.baseUrl.trim(),W=J.apiKey?.trim()??"";if(!Z&&!W){let G=C2($);if((await W4(G)).providers[Q]){let D=await C9($,{providerId:Q});return{providerId:Q,settingsPath:D.settingsPath,modelsPath:D.modelsPath,modelsCount:0}}return PK($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(N0.hasProvider(Q))throw Error(`provider "${Q}" already exists`);let j=J.name.trim();if(!j)throw Error("name is required");if(!Z)throw Error("baseUrl is required");let f=g3(J.models),X=J.modelsSourceUrl?.trim(),Y=await qK({providerId:Q,explicitModels:f,modelsSourceUrl:X,shouldRecompute:!0});if(Y.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let V=J.defaultModelId?.trim()&&Y.includes(J.defaultModelId.trim())?J.defaultModelId.trim():Y[0],H=J.capabilities?.length?[...new Set(J.capabilities)]:void 0,B=MK(J.headers);$.saveProviderSettings({provider:Q,apiKey:W||void 0,baseUrl:Z,headers:B,timeout:J.timeoutMs,model:V,protocol:J.protocol,client:J.client},{setLastUsed:!1});let A=C2($),K=await W4(A);return K.providers[Q]={provider:{name:j,baseUrl:Z,defaultModelId:V,protocol:J.protocol,client:J.client,capabilities:H,modelsSourceUrl:X},models:m3(Y,H)},await M9(A,K),RJ(Q,K.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:Y.length}}async function S9($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=C2($),W=await W4(Z),j=W.providers[Q];if(!j){let T=$.getProviderSettings(Q);if(!T)throw Error(`provider "${Q}" does not exist`);let L=J.modelsSourceUrl?.trim(),z=g3(J.models)[0]??T.model?.trim();if(!z&&!L)throw Error(`provider "${Q}" cannot be updated because no model is configured`);j={provider:{name:J.name?.trim()||OK(Q),baseUrl:J.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:z,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:z?m3([z],T.capabilities):{}}}if(!j.provider)throw Error(`provider "${Q}" cannot be updated because it is a model overlay (no provider metadata)`);let f=J.name?.trim()??j.provider.name.trim();if(!f)throw Error("name is required");let X=J.baseUrl?.trim()??j.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let Y=J.capabilities===void 0?j.provider.capabilities:J.capabilities===null?void 0:[...new Set(J.capabilities)],V=J.protocol===void 0?j.provider.protocol:J.protocol??void 0,H=J.client===void 0?j.provider.client:J.client??void 0,B=g3(J.models),A=J.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:J.modelsSourceUrl?.trim()||void 0,K=J.models!==void 0||J.modelsSourceUrl!==void 0&&!!A,G=Object.keys(j.models??{}).map((T)=>T.trim()).filter(Boolean),R=await qK({providerId:Q,explicitModels:B,modelsSourceUrl:A,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let D=J.defaultModelId===void 0?j.provider.defaultModelId?.trim():J.defaultModelId?.trim(),U=D&&R.includes(D)?D:R[0],O={...$.getProviderSettings(Q)??{},provider:Q,baseUrl:X,model:U};if(V)O.protocol=V;else delete O.protocol;if(H)O.client=H;else delete O.client;if(J.apiKey!==void 0){let T=J.apiKey?.trim()??"";if(T)O.apiKey=T;else delete O.apiKey}if(J.headers!==void 0){let T=MK(J.headers);if(T)O.headers=T;else delete O.headers}if(J.timeoutMs!==void 0)if(typeof J.timeoutMs==="number")O.timeout=J.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),W.providers[Q]={provider:{name:f,baseUrl:X,defaultModelId:U,protocol:V,client:H,capabilities:Y,modelsSourceUrl:A},models:m3(R,Y)},await M9(Z,W),RJ(Q,W.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z,modelsCount:R.length}}async function C9($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=C2($),W=await W4(Z);if(!W.providers[Q])throw Error(`provider "${Q}" does not exist`);return delete W.providers[Q],await M9(Z,W),N0.unregisterProvider(Q),PK($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z}}async function c3($,J={}){let Q=$.read(),Z=N0.getProviderIds(),W=await Promise.all(Z.map(async(f)=>{let[X,Y]=await Promise.all([N0.getProvider(f),N0.getModelsForProvider(f)]),V=TK(Y),H=Q.providers[f]?.settings,B=X?.name??OK(f),A=vC(X?.capabilities,H?.capabilities),K=dC(X?.metadata)??lC(X);return{provider:{id:f,name:B,models:V.length,color:xC(f),letter:IC(B),enabled:Boolean(H),apiKey:H?hC(H):void 0,oauthAccessTokenPresent:H?kC(H):void 0,baseUrl:H?.baseUrl??X?.baseUrl,defaultModelId:X?.defaultModelId,protocol:H?.protocol??X?.protocol,client:H?.client??X?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:K,configValues:iC(K,H,X),modelList:V},rank:cC(X?.metadata)}}));W.sort((f,X)=>{if(f.rank!==X.rank)return f.rank-X.rank;return f.provider.name.localeCompare(X.provider.name)||f.provider.id.localeCompare(X.provider.id)});let j=W.map((f)=>f.provider);if(J.isClinePassEnabled!==!0)j=j.filter((f)=>f.id!==bC);return{providers:j,settingsPath:$.getFilePath()}}async function u3($,J){let Q=$.trim(),Z=await gC(Q,J),W=TK(Z);return{providerId:Q,models:W}}function w9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function NK($,J){if(!w9(J))return w9($)?{...$}:void 0;let Q=w9($)?{...$}:{};for(let[Z,W]of Object.entries(J)){if(W==null||W===""){delete Q[Z];continue}if(w9(W)){let j=NK(Q[Z],W);if(j&&Object.keys(j).length>0)Q[Z]=j;else delete Q[Z];continue}Q[Z]=W}return Object.keys(Q).length>0?Q:void 0}function d3($,J){let Q=J.providerId.trim();if(J.enabled===!1){let j=$.read();if(delete j.providers[Q],j.lastUsedProvider===Q)delete j.lastUsedProvider;return $.write(j),{providerId:Q,enabled:!1,settingsPath:$.getFilePath()}}let W={...$.getProviderSettings(Q)??{},provider:Q};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(J,j)&&typeof J[j]==="string")if(J[j].trim().length===0)delete W[j];else W[j]=J[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(J,j))W[j]=J[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(J,j)&&J[j]!=null){let f=NK(W[j],J[j]);if(f)W[j]=f;else delete W[j]}return $.saveProviderSettings(W,{setLastUsed:!1}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function l3($,J){let Q=J.trim(),Z=$.getProviderSettings(Q),j=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Q]?.provider,f=Z?.baseUrl?.trim()||j?.baseUrl?.trim(),X=XQ(f,j?.baseUrl,j?.modelsSourceUrl);if(!Z||!j||!f||!X)return{providerId:Q,refreshed:!1};let Y=await S9($,{providerId:Q,name:j.name,baseUrl:f,apiKey:Z.apiKey,headers:Z.headers??null,timeoutMs:Z.timeout??null,modelsSourceUrl:X,protocol:Z.protocol??j.protocol??null,client:Z.client??j.client??null,capabilities:Z.capabilities??null});return{providerId:Q,refreshed:!0,modelsCount:Y.modelsCount}}function p3($){let J=$.trim().toLowerCase(),Q=Z0(J);if(Q)return Q.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function r3($,J,Q,Z){let W=Z0($);if(!W)throw Error(`provider "${$}" does not support OAuth login`);let j=b8({onPrompt:async(f)=>f.defaultValue??"",openUrl:Q,onOpenUrlError:({error:f})=>{throw f instanceof Error?f:Error(String(f))}});return W.login({settings:J,callbacks:j,telemetry:Z})}function i3($,J,Q,Z,W){return p$({manager:$,providerId:J,settings:Q,credentials:Z,setLastUsed:W?.setLastUsed})}async function n3($,J,Q,Z){let W=b8({onPrompt:async(j)=>j.defaultValue??"",openUrl:Q,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return x4($,J,{callbacks:W,telemetry:Z})}function a3($){let J=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return J&&J.length>0?J:void 0}var SK={};w(SK,{getProviderConfigFields:()=>s3});import*as y9 from"@cline/llms";var nC=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],aC={"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 sC($,J){let Q={};for(let Z of nC){let W=$[Z],j=J[Z];if(W||j)Q[Z]={...W,...j}}return Q}function oC($){let J=aC[$.providerId];if(!J)return $;return{...$,description:J.description??$.description,fields:J.mode==="replace"?J.fields:sC($.fields,J.fields)}}var tC=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function eC($,J){if(!J?.provider.baseUrl)return!1;if(J.provider.source!=="system")return!0;return tC.has($)}function s3($){let J=y9.normalizeProviderId($);if(l$(J))return{providerId:J,authMethod:"oauth",fields:{}};let Q=y9.MODEL_COLLECTIONS_BY_PROVIDER_ID[J];if(Q?.provider.capabilities?.includes("local-auth"))return{providerId:J,authMethod:"local",fields:{}};let Z=Q?.provider.baseUrl,W={apiKey:{}};if(eC(J,Q))W.baseUrl={defaultValue:Z};return oC({providerId:J,authMethod:"api-key",fields:W})}var bK={};w(bK,{resolveLegacyClineAuth:()=>e3,migrateLegacyProviderSettings:()=>zJ});import{existsSync as $y,readFileSync as Jy}from"node:fs";import{dirname as Qy,join as o3}from"node:path";import*as b9 from"@cline/llms";import{resolveClineDataDir as Zy}from"@cline/shared/storage";var E9="openai",EK=b9.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,CK=128000;function e3($){let J=$?.trim();if(!J)return;try{let Q=JSON.parse(J);if(!Q)return;let Z=typeof Q.expiresAt==="number"&&Number.isFinite(Q.expiresAt)?Q.expiresAt<10000000000?Q.expiresAt*1000:Q.expiresAt:void 0;return{accessToken:Q.idToken,refreshToken:Q.refreshToken,expiresAt:Z,accountId:Q.userInfo?.id}}catch{return}}function E($){let J=$?.trim();return J?J:void 0}function yK($){if(!$y($))return;try{let J=Jy($,"utf8"),Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return}function Wy($){let J=$.dataDir??Zy(),Q=$.globalStatePath??o3(J,"globalState.json"),Z=$.secretsPath??o3(J,"secrets.json"),W=yK(Q),j=yK(Z);if(!W&&!j)return;return{globalState:W??{},secrets:j??{}}}function t3($){if($===E9)return EK;return $}function jy($,J,Q,Z){let W=Q==="plan"?"planMode":"actMode",j=J===Z?E(Q==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${W}OpenRouterModelId`,cline:`${W}ClineModelId`,openai:`${W}OpenAiModelId`,ollama:`${W}OllamaModelId`,lmstudio:`${W}LmStudioModelId`,litellm:`${W}LiteLlmModelId`,requesty:`${W}RequestyModelId`,together:`${W}TogetherModelId`,fireworks:`${W}FireworksModelId`,sapaicore:`${W}SapAiCoreModelId`,groq:`${W}GroqModelId`,baseten:`${W}BasetenModelId`,huggingface:`${W}HuggingFaceModelId`,"huawei-cloud-maas":`${W}HuaweiCloudMaasModelId`,oca:`${W}OcaModelId`,aihubmix:`${W}AihubmixModelId`,hicap:`${W}HicapModelId`,nousResearch:`${W}NousResearchModelId`,"vercel-ai-gateway":`${W}VercelAiGatewayModelId`}[J];return(X?E(typeof $[X]==="string"?$[X]:void 0):void 0)??j}function fy($,J,Q){let Z=Q==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,W=Q==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,j=Q==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,f=(J==="gemini"?W:void 0)??Z,X=f==="none"||f==="low"||f==="medium"||f==="high"?f:void 0,Y=typeof j==="number"&&Number.isInteger(j)&&j>0?j:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function Xy($){let J=$["openai-codex-oauth-credentials"];if(!J)return;try{let Q=JSON.parse(J),Z=E(Q.access_token),W=E(Q.refresh_token),j=E(Q.accountId);if(!Z&&!W&&!j)return;return{...Z?{apiKey:Z}:{},auth:{...Z?{accessToken:Z}:{},...W?{refreshToken:W}:{},...j?{accountId:j}:{}}}}catch{return}}function Yy($){let J=b9.getGeneratedModelsForProvider($);return Object.keys(J)[0]??void 0}function Vy($,J,Q,Z){let W=t3($),j=E(Z==="plan"?J.planModeApiProvider:J.actModeApiProvider),f=jy(J,$,Z,j)??Yy(W),X=fy(J,W,Z),Y=typeof J.requestTimeoutMs==="number"&&Number.isInteger(J.requestTimeoutMs)&&J.requestTimeoutMs>0?J.requestTimeoutMs:void 0,V={anthropic:Q.apiKey,cline:Q.clineApiKey,openai:Q.openAiApiKey,"openai-native":Q.openAiNativeApiKey,openrouter:Q.openRouterApiKey,bedrock:Q.awsBedrockApiKey,gemini:Q.geminiApiKey,ollama:Q.ollamaApiKey,deepseek:Q.deepSeekApiKey,requesty:Q.requestyApiKey,together:Q.togetherApiKey,fireworks:Q.fireworksApiKey,qwen:Q.qwenApiKey,doubao:Q.doubaoApiKey,mistral:Q.mistralApiKey,litellm:Q.liteLlmApiKey,asksage:Q.asksageApiKey,xai:Q.xaiApiKey,moonshot:Q.moonshotApiKey,zai:Q.zaiApiKey,huggingface:Q.huggingFaceApiKey,nebius:Q.nebiusApiKey,sambanova:Q.sambanovaApiKey,cerebras:Q.cerebrasApiKey,groq:Q.groqApiKey,"huawei-cloud-maas":Q.huaweiCloudMaasApiKey,baseten:Q.basetenApiKey,"vercel-ai-gateway":Q.vercelAiGatewayApiKey,dify:Q.difyApiKey,minimax:Q.minimaxApiKey,hicap:Q.hicapApiKey,aihubmix:Q.aihubmixApiKey,nousResearch:Q.nousResearchApiKey,oca:Q.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,Xy(Q));if($==="cline")try{let U=E(Q["cline:clineAccountId"]);if(U)H.auth={...H.auth??{},...e3(U)}}catch{}if($===E9&&J.openAiHeaders)H.headers=J.openAiHeaders;if($==="bedrock"){let U=J.awsAuthentication==="profile"||J.awsUseProfile===!0;H.aws={accessKey:E(Q.awsAccessKey),secretKey:E(Q.awsSecretKey),sessionToken:E(Q.awsSessionToken),region:E(J.awsRegion),authentication:J.awsAuthentication,profile:U?E(J.awsProfile):void 0,usePromptCache:J.awsBedrockUsePromptCache,useCrossRegionInference:J.awsUseCrossRegionInference,useGlobalInference:J.awsUseGlobalInference,endpoint:E(J.awsBedrockEndpoint),customModelBaseId:E(Z==="plan"?J.planModeAwsBedrockCustomModelBaseId:J.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:E(J.vertexProjectId),region:E(J.vertexRegion)};if($===E9&&(J.azureApiVersion||J.azureIdentity!==void 0))H.azure={apiVersion:E(J.azureApiVersion),useIdentity:J.azureIdentity};if($==="sapaicore")H.sap={clientId:E(Q.sapAiCoreClientId),clientSecret:E(Q.sapAiCoreClientSecret),tokenUrl:E(J.sapAiCoreTokenUrl),resourceGroup:E(J.sapAiResourceGroup),deploymentId:E(Z==="plan"?J.planModeSapAiCoreDeploymentId:J.actModeSapAiCoreDeploymentId),useOrchestrationMode:J.sapAiCoreUseOrchestrationMode};if($==="oca"){H.oca={mode:J.ocaMode};let U=E(Q.ocaRefreshToken);if(U)H.auth={...H.auth??{},refreshToken:U}}if($==="qwen")H.apiLine=J.qwenApiLine;if($==="moonshot")H.apiLine=J.moonshotApiLine;if($==="zai")H.apiLine=J.zaiApiLine;if($==="minimax")H.apiLine=J.minimaxApiLine;let B={anthropic:J.anthropicBaseUrl,openai:J.openAiBaseUrl,ollama:J.ollamaBaseUrl,lmstudio:J.lmStudioBaseUrl,litellm:J.liteLlmBaseUrl,gemini:J.geminiBaseUrl,requesty:J.requestyBaseUrl,asksage:J.asksageApiUrl,dify:J.difyBaseUrl,oca:J.ocaBaseUrl,aihubmix:J.aihubmixBaseUrl,sapaicore:J.sapAiCoreBaseUrl},A=E(V[$]),K=E(B[$]),G={provider:W,...A?{apiKey:A}:{},...f?{model:f}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...Y?{timeout:Y}:{},...H},R=C8.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function Hy($,J){if($!==EK)return;if(!J.baseUrl||!J.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:J.baseUrl,defaultModelId:J.model},models:{[J.model]:{id:J.model,name:J.model,contextWindow:CK,maxInputTokens:CK,capabilities:["streaming","tools","images"]}}}}function By($,J){let Q=new Set;for(let W of[$.actModeApiProvider,$.planModeApiProvider]){let j=E(W);if(j)Q.add(j)}if(E(J.apiKey))Q.add("anthropic");if(E(J.openRouterApiKey))Q.add("openrouter");if(E(J.openAiApiKey))Q.add(E9);if(E(J.openAiNativeApiKey))Q.add("openai-native");if(E(J["openai-codex-oauth-credentials"]))Q.add("openai-codex");if(E(J.geminiApiKey))Q.add("gemini");if(E(J.ollamaApiKey))Q.add("ollama");if(E(J.awsAccessKey)||E(J.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||E($.awsProfile))Q.add("bedrock");if(E($.vertexProjectId)||E($.vertexRegion))Q.add("vertex");if(E(J.clineApiKey))Q.add("cline");let Z=e3(E(J["cline:clineAccountId"]));if(Z?.accessToken||Z?.refreshToken||Z?.accountId)Q.add("cline");if(E(J.ocaApiKey))Q.add("oca");if(E(J.sapAiCoreClientId)||E(J.sapAiCoreClientSecret)||E($.sapAiCoreTokenUrl)||E($.sapAiCoreBaseUrl)||E($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Q.add("sapaicore");return Q}function zJ($){let J=$.providerSettingsManager.read(),Q=Wy($);if(!Q)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let{globalState:Z,secrets:W}=Q,j=Z.mode==="plan"?"plan":"act",f=By(Z,W),X=M$();X.providers={...J.providers},X.lastUsedProvider=J.lastUsedProvider;let Y=new Date().toISOString(),V=0,H=o3(Qy($.providerSettingsManager.getFilePath()),"models.json"),B=x3(H),A=0;for(let R of f){let D=t3(R);if(X.providers[D])continue;let U=Vy(R,Z,W,j);if(!U)continue;X.providers[D]={settings:U,updatedAt:Y,tokenSource:"migration"},V+=1;let F=Hy(D,U);if(F&&!B.providers[D])B.providers[D]=F,A+=1}if(V===0&&A===0)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let K=E(j==="plan"?Z.planModeApiProvider:Z.actModeApiProvider),G=K?t3(K):void 0;if(X.lastUsedProvider=J.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),A>0)KK(H,B);return{migrated:V>0||A>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}B9();O0();f5();var IK={};w(IK,{trimMessagesToCheckpoint:()=>kK,trimMessagesBeforeCheckpoint:()=>Jj,readSessionCheckpointHistory:()=>LJ,createRestoredCheckpointMetadata:()=>$j,createCheckpointRestorePlan:()=>Qj,applyCheckpointToWorktree:()=>Zj});import{execFile as Ay}from"node:child_process";import{promisify as Ky}from"node:util";var j4=Ky(Ay);function LJ($){let J=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(J?.history)?J.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let W=String(Z.ref??"").trim(),j=Number(Z.createdAt??0),f=Number(Z.runCount??0);if(W.length===0||!Number.isFinite(j)||!Number.isInteger(f)||f<1)return[];let X=Z.kind==="stash"||Z.kind==="commit"?Z.kind:void 0;return[{ref:W,createdAt:j,runCount:f,...X?{kind:X}:{}}]})}function $j($,J){let Q=LJ($).filter((W)=>W.runCount<=J),Z=Q.at(-1);return Z?{latest:Z,history:Q}:void 0}function Gy($,J){return $.reduce((Q,Z)=>{if(Z.runCount>J)return Q;if(!Q||Z.runCount>Q.runCount)return Z;return Q},void 0)}function hK($,J){let Q=0;for(let Z=0;Z<$.length;Z+=1){let W=$[Z];if(W?.role!=="user")continue;if(("metadata"in W&&W.metadata&&typeof W.metadata==="object"?W.metadata:void 0)?.kind==="recovery_notice")continue;if(Q+=1,Q===J)return Z}throw Error(`Could not find user message for checkpoint run ${J}`)}function kK($,J){let Q=hK($,J);return $.slice(0,Q+1)}function Jj($,J){let Q=hK($,J);return $.slice(0,Q)}function Qj($){let J=$.checkpointRunCount;if(!Number.isInteger(J)||J<1)throw Error("checkpointRunCount must be a positive integer");let Q=Gy(LJ($.session),J);if(!Q)throw Error(`No checkpoint found at or before run ${J} in session ${$.session.sessionId}`);let Z=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Z)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Q,cwd:Z,...$.restoreMessages!==!1?{messages:kK($.messages??[],J)}:{}}}async function Zj($,J){if((await j4("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await j4("git",["-C",$,"cat-file","-e",`${J.ref}^{commit}`],{windowsHide:!0}),await j4("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await j4("git",["-C",$,"clean","-fd"],{windowsHide:!0}),J.kind==="commit"){await j4("git",["-C",$,"reset","--hard",J.ref],{windowsHide:!0});return}await j4("git",["-C",$,"stash","apply",J.ref],{windowsHide:!0})}var xK={};w(xK,{SessionVersioningService:()=>y$,SessionVersioningError:()=>h0});class h0 extends Error{code;constructor($,J){super(J);this.code=$;this.name="SessionVersioningError"}}function Fy($){let J=$.sessionId.trim();if(!J)throw new h0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new h0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new h0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new h0("invalid_restore","checkpointRunCount must be a positive integer");return J}class y${async restoreCheckpoint($){let J=$.restore?.messages!==!1,Q=$.restore?.workspace!==!1,Z=Fy({sessionId:$.sessionId,restoreMessages:J,restoreWorkspace:Q,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),W=await $.getSession(Z);if(!W)throw new h0("session_not_found",`Session ${Z} not found`);let j=J?await $.readMessages(Z):void 0;if(J&&j?.length===0)throw new h0("session_messages_not_found",`No messages found for session ${Z}`);let f=Qj({session:W,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:J});if(Q)await($.applyWorkspaceCheckpoint??Zj)(f.cwd,f.checkpoint);let X=F1({session:W,messages:j});if(!J)return{checkpoint:f.checkpoint,sourceSnapshot:X};let Y=$j(W,$.checkpointRunCount),V=$.restore?.omitCheckpointMessageFromSession?Jj(j??[],$.checkpointRunCount):f.messages??[],H={sourceSession:W,sourceMessages:j,sourceSnapshot:X,plan:f,restoredCheckpointMetadata:Y,initialMessages:V,restoreMessages:J,restoreWorkspace:Q,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new h0("invalid_restore","start is required when restore.messages is true");let B=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,A=await $.startSession(B),K=$.getStartedSessionId?.(A);if(K)await($.retainCheckpointRefs??XH)(f.cwd,K,Y?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:A,messages:f.messages,checkpoint:f.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:F1({session:G,messages:V})}:{}}}}var gK={};w(gK,{FileTeamPersistenceStore:()=>h9});import{appendFileSync as Dy,existsSync as Wj,mkdirSync as Uy,readFileSync as Ry,renameSync as zy,unlinkSync as Ly,writeFileSync as _y}from"node:fs";import{join as jj}from"node:path";import{resolveTeamDataDir as Oy}from"@cline/shared/storage";function Ty($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class h9{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let J=Ty($.teamName),Q=$.baseDir?.trim()||Oy();this.dirPath=jj(Q,J),this.statePath=jj(this.dirPath,"state.json"),this.taskHistoryPath=jj(this.dirPath,"task-history.jsonl")}loadState(){if(!Wj(this.statePath))return;try{let $=Ry(this.statePath,"utf8"),J=JSON.parse($);if(J.version!==1||!J.teamState)return;for(let Q of J.teammates??[])this.teammateSpecs.set(Q.agentId,Q);return SA(J.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let J={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Q=`${this.statePath}.tmp`;_y(Q,`${JSON.stringify(J,null,2)}
708
+ `,"utf8"),zy(Q,this.statePath)}appendTaskHistory($){let J={};switch($.type){case"team_task_updated":J=$.task;break;case"team_message":J={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":J={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":J={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":J={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":J={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Dy(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:J})}
709
+ `,"utf8")}ensureDir(){if(!Wj(this.dirPath))Uy(this.dirPath,{recursive:!0})}hasPersistableState($){let J=$.exportState();if(this.teammateSpecs.size>0)return!0;if(J.members.some((Q)=>Q.role==="teammate"))return!0;return J.tasks.length>0||J.mailbox.length>0||J.missionLog.length>0}clearPersistedState(){if(Wj(this.statePath))Ly(this.statePath)}}var mK={};w(mK,{ChatViewStateSchema:()=>fj,ChatSummarySchema:()=>m9,ChatSessionStatusSchema:()=>I9,ChatSessionConfigSchema:()=>k9,ChatMessageSchema:()=>g9,ChatMessageRoleSchema:()=>x9});import{z as h}from"zod";var k9=h.object({workspaceRoot:h.string().min(1),cwd:h.string().optional(),provider:h.string().min(1),model:h.string().min(1),mode:h.enum(["act","plan"]).default("act"),apiKey:h.string(),systemPrompt:h.string().optional(),rules:h.string().optional(),maxIterations:h.number().int().positive().optional(),enableTools:h.boolean(),enableSpawn:h.boolean().optional(),enableTeams:h.boolean().optional(),autoApproveTools:h.boolean().optional(),missionStepInterval:h.number().int().positive().optional(),missionTimeIntervalMs:h.number().int().positive().optional()}),I9=h.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),x9=h.enum(["user","assistant","tool","system","status","error"]),g9=h.object({id:h.string().min(1),sessionId:h.string().nullable(),role:x9,content:h.string(),createdAt:h.number().int().nonnegative(),meta:h.object({stream:h.enum(["stdout","stderr"]).optional(),toolName:h.string().optional(),iteration:h.number().int().nonnegative().optional(),agentId:h.string().optional(),conversationId:h.string().optional(),hookEventName:h.string().optional(),inputTokens:h.number().int().nonnegative().optional(),outputTokens:h.number().int().nonnegative().optional(),checkpoint:h.object({ref:h.string(),createdAt:h.number().int().nonnegative(),runCount:h.number().int().positive(),kind:h.enum(["stash","commit"]).optional()}).optional()}).optional()}),m9=h.object({toolCalls:h.number().int().nonnegative(),tokensIn:h.number().int().nonnegative(),tokensOut:h.number().int().nonnegative()}),fj=h.object({sessionId:h.string().nullable(),status:I9,config:k9,messages:h.array(g9),rawTranscript:h.string(),error:h.string().nullable(),summary:m9});var vK={};w(vK,{CORE_BUILD_VERSION:()=>Xj});var Xj=Pf;import{Agent as XE,createAgentRuntime as YE}from"@cline/agents";var cK={};w(cK,{fetchClineRecommendedModels:()=>Vj,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>v9});import{getClineEnvironmentConfig as My}from"@cline/shared";var qy=5000,v9={clinePass:[],recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}]};function Py($){return{clinePass:$.clinePass.map((J)=>({...J,tags:[...J.tags]})),recommended:$.recommended.map((J)=>({...J,tags:[...J.tags]})),free:$.free.map((J)=>({...J,tags:[...J.tags]}))}}function Yj($){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.id!=="string"||J.id.length===0)return null;return{id:J.id,name:typeof J.name==="string"&&J.name.length>0?J.name:J.id,description:typeof J.description==="string"?J.description:"",tags:Array.isArray(J.tags)?J.tags.filter((Q)=>typeof Q==="string"):[]}}function Ny($){if(!$||typeof $!=="object")return null;let J=$,Q=Array.isArray(J.recommended)?J.recommended:[],Z=Array.isArray(J.free)?J.free:[],W=Array.isArray(J.clinePass)?J.clinePass:[],j=Q.map(Yj).filter((Y)=>Y!==null),f=Z.map(Yj).filter((Y)=>Y!==null),X=W.map(Yj).filter((Y)=>Y!==null);if(j.length===0&&f.length===0&&X.length===0)return null;return{recommended:j,free:f,clinePass:X}}function wy($){let J=$.baseUrl?.trim();if(J)return J;let Q=My().apiBaseUrl;try{return($.providerSettingsManager??new _1).getProviderSettings("cline")?.baseUrl?.trim()||Q}catch{return Q}}async function Sy($,J,Q){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await $(J,{signal:Z.signal})}finally{clearTimeout(W)}}async function Vj($={}){try{let J=wy($),Q=$.fetchImpl??fetch,Z=await Sy(Q,`${J}/api/v1/ai/cline/recommended-models`,$.timeoutMs??qy);if(!Z.ok)throw Error(`HTTP ${Z.status}`);let W=await Z.json(),j=Ny(W);if(j)return j}catch{}return Py(v9)}var uK={};w(uK,{loadLlmsConfigFromFile:()=>Bj,defineLlmsConfig:()=>Hj});import{readFile as Cy}from"node:fs/promises";import yy from"node:path";function Hj($){return $}async function Bj($){let J=yy.resolve($),Q=await Cy(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse JSON config at "${J}": ${j}`)}return Ey(Z,J)}function Ey($,J){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${J}": expected an object.`);let Z=$.providers;if(!Array.isArray(Z))throw Error(`Invalid llms config in "${J}": "providers" must be an array.`);if(!Z.length)throw Error(`Invalid llms config in "${J}": "providers" cannot be empty.`);return $}var nK={};w(nK,{createLlmsSdk:()=>Kj,DefaultLlmsSdk:()=>_J});import{BUILT_IN_PROVIDER_IDS as pK,createHandler as ky,createHandlerAsync as Iy,getProviderCollection as xy,hasProvider as rK,registerAsyncHandler as gy,registerHandler as my,registerModel as vy,registerProvider as iK}from"@cline/llms";function dK($){return $?{...$}:{}}function by($,J){if($)return $;if(!J)return;let Q=globalThis.process;if(!Q?.env)return;return Q.env[J]}function hy($,J){if(!J.length)throw Error(`Provider "${$}" must include at least one model.`)}function lK($){let J=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:J,defaultModel:$.collection.provider.defaultModelId,modelCount:J.length}}class Aj{providers=new Map;register($){hy($.id,$.models);let J=$.defaultModel??$.models[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(J))throw Error(`Default model "${J}" is not included in configured models for "${$.id}".`);let Q=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Q?.models??[],...$.models]),defaultModel:J,defaults:{...Q?.defaults??{},...dK($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:by($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...dK($.settings)}})}registerModel($,J){let Q=this.providers.get($);if(!Q){this.providers.set($,{id:$,models:new Set([J]),defaultModel:J,defaults:{}});return}Q.models.add(J)}createHandlerConfig($){let J=this.require($.providerId),Q=$.modelId??J.defaultModel;if(!J.models.has(Q))throw Error(`Model "${Q}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Q,...J.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,J){return this.providers.get($)?.models.has(J)??!1}require($){let J=this.providers.get($);if(!J)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return J}}class _J{configuredProviders=new Aj;constructor($){this.applyConfig($)}createHandler($){return ky(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return Iy(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(iK($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)my($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)gy($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let J=$.exposeModels??Object.keys($.models),Q=$.defaultModel??J[0];if(!Q)throw Error(`Provider "${$.id}" must define a default model.`);iK({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Q,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:J,defaultModel:Q,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){vy($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...pK]}async getBuiltInProviders(){return(await Promise.all(pK.map((J)=>xy(J)))).filter((J)=>J!==void 0).map((J)=>lK({collection:J}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,J){return this.configuredProviders.hasModel($,J)}applyConfig($){for(let J of $.providers)this.configuredProviders.registerSelectionConfig(J);for(let J of $.models??[])this.registerModel(J);for(let J of $.customProviders??[])this.registerProvider(J);for(let J of this.configuredProviders.list()){let Q=rK(J.id),Z=this.configuredProviders.createHandlerConfig({providerId:J.id,modelId:J.defaultModel}).routingProviderId,W=typeof Z==="string"&&rK(Z);if(!Q&&!W)throw Error(`Provider "${J.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function Kj($){return new _J($)}BZ();async function cy(){return Promise.resolve().then(() => (B9(),lA))}function KE(){return new Date().toISOString()}var GE="cline",FE="cline-pass";function DE($){if(QG($)!=="providers.json")return;let J=Fj($);if(QG(J)!=="settings")return;return Fj(J)}class _1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??AE(),this.dataDir=$.dataDir??DE(this.filePath),this.dataDir||!$.filePath)zJ({providerSettingsManager:this,dataDir:this.dataDir});if(LK(this),q9(this.read()),Gj(this.filePath))try{JG(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!Gj(this.filePath))return M$();try{let $=HE(this.filePath,"utf8"),J=JSON.parse($),Q=y8.safeParse(J);if(Q.success)return q9(Q.data),Q.data}catch{}return M$()}write($){let J=y8.parse($),Q=Fj(this.filePath);if(!Gj(Q))VE(Q,{recursive:!0,mode:448});BE(this.filePath,`${JSON.stringify(J,null,2)}
710
+ `,"utf8");try{JG(this.filePath,384)}catch{}q9(J)}saveProviderSettings($,J={}){let Q=C8.parse($),Z=this.read(),W=Q.provider,j=J.setLastUsed!==!1,f=Z.providers[W],X=J.tokenSource??f?.tokenSource??"manual",Y={...Z,providers:{...Z.providers,[W]:{settings:Q,updatedAt:KE(),tokenSource:X}},lastUsedProvider:j?W:Z.lastUsedProvider};return this.write(Y),Y}resolveProviderSettings($,J){let Q=$.providers[J]?.settings,W=Z0(J)?.storageProviderId;if(!W||W===J)return Q;let j=$.providers[W]?.settings;if(!j)return Q;return C8.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Q??{},provider:J})}getProviderSettings($){let J=this.read();return this.resolveProviderSettings(J,$)}resolveLastUsedProviderId($,J){let Q=$.lastUsedProvider;if(Q===FE&&J.isClinePassEnabled===!1)return GE;return Q}getLastUsedProviderSettings($={}){let J=this.read(),Q=this.resolveLastUsedProviderId(J,$);if(!Q)return;return this.resolveProviderSettings(J,Q)}getProviderConfig($,J){let Q=this.getProviderSettings($);if(!Q)return;return d0(Q,J)}getLastUsedProviderConfig($={}){let J=this.getLastUsedProviderSettings($);if(!J)return;return d0(J,$)}async refreshCatalog(){try{await w8({})}catch{}}}O0();l2();function UE($,J){let Q=$?.expiresAt,Z=J?.expiresAt;return $?.accessToken===J?.accessToken&&$?.refreshToken===J?.refreshToken&&$?.accountId===J?.accountId&&Q===Z}class d9 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 Dj{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new _1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let J=Z0($.providerId);if(!J)return null;return this.resolveWithSingleFlight(J.providerId,J.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,J,Q=!1){let Z=this.refreshInFlight.get(J);if(Z)return Z;let W=this.resolveProviderApiKeyInternal($,J,Q).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(J)});return this.refreshInFlight.set(J,W),W}async resolveProviderApiKeyInternal($,J,Q){let Z=Z0($);if(!Z)return null;let W=this.providerSettingsManager.getProviderSettings(J);if(!W)return null;let j=g4($,W);if(!j)return null;let f=await Z.refresh({settings:W,credentials:j,forceRefresh:Q,telemetry:this.telemetry});if(!f)throw new d9($);let X=p$({manager:this.providerSettingsManager,providerId:$,settings:W,credentials:f,setLastUsed:!1,save:!1}),Y=!UE(W.auth,X.auth);if(Y)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:Z.getApiKey(X)??f.access,accountId:f.accountId,refreshed:Y}}}import{normalizeUserInput as RE}from"@cline/shared";import{nanoid as zE}from"nanoid";class ZG{list($){return $?n0($):[]}update($,J){if(!$)return{sessionId:J.sessionId,prompts:[],updated:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((Y)=>Y.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:n0($),updated:!1};let W=$.pendingPrompts[Z];if(!W)return{sessionId:J.sessionId,prompts:n0($),updated:!1};let j=J.prompt===void 0?W.prompt:RE(J.prompt).trim();if(!j)throw Error("prompt cannot be empty");let f=J.delivery??W.delivery,X={...W,prompt:j,mode:J.mode??W.mode,delivery:f};return $.pendingPrompts.splice(Z,1),LE($,X,Z,W.delivery),{sessionId:J.sessionId,prompts:n0($),prompt:l9(X),updated:!0}}delete($,J){if(!$)return{sessionId:J.sessionId,prompts:[],removed:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((j)=>j.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:n0($),removed:!1};let[W]=$.pendingPrompts.splice(Z,1);return{sessionId:J.sessionId,prompts:n0($),prompt:W?l9(W):void 0,removed:!0}}enqueue($,J){let{prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f}=J,X=$.pendingPrompts.findIndex((Y)=>Y.prompt===Q);if(X>=0){let[Y]=$.pendingPrompts.splice(X,1),V={...Y,prompt:Q,mode:Z??Y.mode,userImages:j??Y.userImages,userFiles:f??Y.userFiles};if(W==="steer"||Y.delivery==="steer")$.pendingPrompts.unshift({...V,delivery:"steer"});else $.pendingPrompts.push(V)}else{let Y={id:`pending_${Date.now()}_${zE(5)}`,prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f};if(W==="steer")$.pendingPrompts.unshift(Y);else $.pendingPrompts.push(Y)}return n0($)}consumeSteer($){let J=$.pendingPrompts.findIndex((Z)=>Z.delivery==="steer");if(J<0)return{prompts:n0($)};let[Q]=$.pendingPrompts.splice(J,1);return{entry:Q,prompts:n0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:n0($)}}requeueFront($,J){return $.pendingPrompts.unshift(J),n0($)}clear($){return $.pendingPrompts.length=0,[]}}class Uj{deps;service=new ZG;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Q=this.service.update(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}delete($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Q=this.service.delete(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}enqueue($,J){let Q=this.deps.getSession($);if(!Q||Q.aborting)return;this.service.enqueue(Q,J),this.emitPrompts(Q),this.scheduleDrain($,Q)}consumeSteer($){let J=this.deps.getSession($);if(!J)return;let{entry:Q}=this.service.consumeSteer(J);if(!Q)return;return this.emitPrompts(J),this.emitSubmitted(J,Q),Q}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:n0($)}})}scheduleDrain($,J){if(J.pendingPrompts.length===0||J.aborting||J.drainingPendingPrompts||!J.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let J=this.deps.getSession($);if(!J)return;if(J.aborting||J.drainingPendingPrompts)return;if(!J.agent.canStartRun())return;let{entry:Q}=this.service.shiftNext(J);if(!Q)return;this.emitPrompts(J),this.emitSubmitted(J,Q),J.drainingPendingPrompts=!0;let Z=!0;try{await this.deps.send({sessionId:$,prompt:Q.prompt,...Q.mode?{mode:Q.mode}:{},userImages:Q.userImages,userFiles:Q.userFiles})}catch{Z=!1,this.service.requeueFront(J,Q),this.emitPrompts(J)}finally{if(J.drainingPendingPrompts=!1,Z&&J.pendingPrompts.length>0&&J.status!=="failed"&&J.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,J){let Q=l9(J);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}})}}function l9($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function n0($){return $.pendingPrompts.map(l9)}function LE($,J,Q,Z){if(J.delivery==="steer")$.pendingPrompts.unshift(J);else if(Z==="steer")$.pendingPrompts.push(J);else $.pendingPrompts.splice(Q,0,J)}O0();class zj{deps;constructor($){this.deps=$}dispatchAgentEvent($,J,Q){let Z=this.deps.getSession($),W={sessionId:$,config:J,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=v7(Q),f=!!Z&&(!j.agentId||j.agentId===Rj(Z.agent));c7(W,Q,f?{isPrimaryAgentEvent:!0,agentId:Rj(Z.agent),conversationId:Z.agent.getConversationId(),...Z?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,J){let Q=this.deps.getSession($);if(Q){if(tW(Q,J),J.type==="agent_event"){let Z={sessionId:$,config:Q.config,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};c7(Z,J.event,{agentId:J.agentId,teamRole:"teammate",teamAgentId:J.agentId,isPrimaryAgentEvent:!1})}if(J.type==="teammate_spawned"){let Z=l1({agentId:J.teammate.runtimeAgentId??J.agentId,conversationId:J.teammate.conversationId,parentAgentId:J.teammate.parentAgentId,createdByAgentId:Rj(Q.agent),teamId:Q.runtime.teamRuntime?.getTeamId(),teamName:Q.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:J.agentId});if(Z)Z$(Q.config.telemetry,{ulid:$,modelId:J.teammate.modelId??Q.config.modelId,provider:Q.config.providerId,...Z})}}if(await eW($,J,this.deps.invokeBackendOptional),Q)$3(Q,$,J,this.deps.emit)}async handlePluginEvent($,J,Q){if(J.name==="plugin_log"){this.handlePluginLog($,J.payload);return}if(J.name==="automation_event"){let Y=this.deps.getSession($)?.config.extensionContext?.automation??Q;if(!Y)return;let V=J.payload&&typeof J.payload==="object"?J.payload:void 0;if(!V)return;await Y.ingestEvent(V);return}if(J.name!=="steer_message"&&J.name!=="queue_message"&&J.name!=="pending_prompt")return;let Z=J.payload&&typeof J.payload==="object"?J.payload:void 0,W=typeof Z?.sessionId==="string"&&Z.sessionId.trim().length>0?Z.sessionId.trim():$,j=typeof Z?.prompt==="string"?Z.prompt.trim():"";if(!j)return;let f=J.name==="steer_message"?"steer":J.name==="queue_message"?"queue":Z?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(W,{prompt:j,delivery:f})}handlePluginLog($,J,Q){let Z=this.deps.getSession($),W=Q??Z?.config.extensionContext?.logger??Z?.config.logger;if(!W||!J||typeof J!=="object")return;let j=J,f=typeof j.message==="string"?j.message:"";if(!f)return;let X=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(X.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)X.pluginName=j.pluginName;if(j.level==="debug"){W.debug(f,X);return}if(j.level==="error"){if(W.error)W.error(f,X);else W.log(f,{...X,severity:"error"});return}W.log(f,X)}}function Rj($){return $.getAgentId()}function Lj($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:R$($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function _j($,J){let Q=$[J];return typeof Q==="function"?Q:null}async function WG($,J,...Q){let Z=_j($,J);if(!Z)throw Error(`session service method not available: ${J}`);return Promise.resolve(Z.apply($,Q))}async function jG($,J,...Q){let Z=_j($,J);if(!Z)return;await Promise.resolve(Z.apply($,Q))}async function fG($,J,...Q){let Z=_j($,J);if(!Z)return;return await Promise.resolve(Z.apply($,Q))}t0();O0();function Oj($,J,Q){return{onSubAgentEvent:(Z)=>$.onAgentEvent(Q,J,Z),onSubAgentStart:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime;$.subAgentStarts.set(Z.subAgentId,{startedAt:Date.now(),rootSessionId:Q});let j=l1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId});if(j)Z$(J.telemetry,{ulid:Q,modelId:J.modelId,provider:J.providerId,...j});R4(J.telemetry,{event:"started",ulid:Q,durationMs:0,parentId:Z.parentAgentId,agentId:Z.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Q,Z)},onSubAgentEnd:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime,j=$.subAgentStarts.get(Z.subAgentId),f=j?Date.now()-j.startedAt:0,X=Z.result?.text?Z.result.text.split(`
711
+ `).length:0;R4(J.telemetry,{event:"ended",ulid:Q,durationMs:f,outputLines:X,errorMessage:Z.error?String(Z.error):void 0,agentId:Z.subAgentId,parentId:Z.parentAgentId,...l1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId})}),$.subAgentStarts.delete(Z.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Q,Z)}}}function Tj($,J,Q,Z){let W=Oj($,J,Q);return D$({configProvider:{getRuntimeConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:J.hooks,extensions:J.extensions,logger:J.logger,telemetry:J.telemetry},getConnectionConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let f=J.enableTools?Q2({cwd:J.cwd,...c0[u1({mode:J.mode})],executors:Z}):[];if(J.enableSpawnAgent)f.push(Tj($,J,Q,Z));return E1(f)},...W})}import{readFile as _E,stat as OE}from"node:fs/promises";var TE=20480000;async function XG($){let J=await OE($);if(!J.isFile())throw Error("Path is not a file");if(J.size>TE)throw Error("File is too large to read into context.");let Q=await _E($,"utf8");if(Q.includes("\x00"))throw Error("Cannot read binary file into context.");return Q}var YG=5000;function PJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function yE($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=PJ(J.inputTokens),Z=PJ(J.outputTokens),W=PJ(J.cacheReadTokens),j=PJ(J.cacheWriteTokens),f=PJ(J.totalCost);if(Q===void 0||Z===void 0||W===void 0||j===void 0||f===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:W,cacheWriteTokens:j,totalCost:f}}function EE($,J){return{inputTokens:Math.max($.inputTokens,J.inputTokens),outputTokens:Math.max($.outputTokens,J.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,J.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,J.cacheWriteTokens),totalCost:Math.max($.totalCost,J.totalCost)}}class L1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new ZJ;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new y$;constructor($){let J=qE();if(J)CE(J);let Q=S0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new J4,this.createAgentInstance=$.createAgent??((Z)=>new K$(Z)),this.defaultCapabilities=_0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new _1,this.oauthTokenManager=$.oauthTokenManager??new Dj({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Q),this.defaultFetch=$.fetch,this.pendingPromptsController=new Uj({getSession:(Z)=>this.sessions.get(Z),emit:(Z)=>this.emit(Z),send:(Z)=>this.runTurn(Z)}),this.pendingPrompts={list:async(Z)=>this.pendingPromptsController.list(Z.sessionId),update:async(Z)=>this.pendingPromptsController.update(Z),delete:async(Z)=>this.pendingPromptsController.delete(Z)},this.eventBridge=new zj({getSession:(Z)=>this.sessions.get(Z),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Z)=>this.emit(Z),persistMessages:(Z,W,j)=>{this.invoke("persistSessionMessages",Z,W,j)},enqueuePendingPrompt:(Z,W)=>this.pendingPromptsController.enqueue(Z,W),invokeBackendOptional:(Z,...W)=>this.invokeOptional(Z,...W)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!J?.apiKey)return $;return{...$,config:{...$.config,apiKey:J.apiKey}}}async startSession($){let J=$.source??R0.CLI,Q=e(),Z=$.config.sessionId?.trim()??"",W=Z||NE(),j=await this.applyInitialOAuthCredentials($),f=j.initialMessages??[],X=f.length>0?U8(f):G0(),Y=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Y)throw Error("session service method not available: ensureSessionsDir");let V=Mj(Y,W),H=Mj(V,`${W}.messages.json`),B=Mj(V,`${W}.json`),A=R$($.config),K=y0.parse({version:1,session_id:W,source:J,pid:process.pid,started_at:Q,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:A,team_name:j.config.teamName,enable_tools:j.config.enableTools,enable_spawn:j.config.enableSpawnAgent,enable_teams:j.config.enableAgentTeams,prompt:j.prompt?.trim()||void 0,messages_path:H}),G;if(Z.length>0&&f.length>0&&!j.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",W);if(C)K=C,G={manifestPath:B,messagesPath:C.messages_path||H,manifest:C}}let D=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:V,rootMessagesPath:G?.messagesPath??H,manifest:K});this.usageBySession.set(W,X),this.aggregateUsageBySession.set(W,D);let U=_0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,z,P={getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,F0,f0)=>this.eventBridge.dispatchAgentEvent(C,F0,f0),invokeBackendOptional:(C,...F0)=>this.invokeOptional(C,...F0)};z=await EH({input:j,localRuntime:$.localRuntime,sessionId:W,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(W,C.payload,T);return}this.eventBridge.handlePluginEvent(W,C,L)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(W,C),z.config.onTeamEvent?.(C)},createSpawnTool:()=>Tj(P,z.config,W,F),createSubAgentLifecycleCallbacks:(C)=>Oj(P,C,W),readSessionMetadata:async()=>(await this.getSession(W))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(W,()=>C)}});let S=await this.runtimeBuilder.build(z.runtimeBuilderInput),b=z.config,u=z.providerConfig;if(S.teamRuntime&&!b.teamName?.trim())b.teamName=S.teamRuntime.getTeamName();let o=[...S.tools,...b.extraTools??[]],J0=S.extensions??z.extensions,t={sessionId:W,providerId:u.providerId,modelId:u.modelId,apiKey:u.apiKey,baseUrl:u.baseUrl,headers:u.headers,knownModels:u.knownModels,providerConfig:u,thinking:b.thinking,reasoningEffort:b.reasoningEffort??u.reasoningEffort,systemPrompt:b.systemPrompt,maxIterations:b.maxIterations,execution:b.execution,prepareTurn:l4(b),tools:o,hooks:z.hooks,extensions:J0,hookErrorMode:b.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:XG,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval?async(C)=>{let F0=z.requestToolApproval,f0=this.sessions.get(W);if(f0)await this.markTurnPending(f0);try{if(!F0)return{approved:!1,reason:"Tool approval callback is not configured."};return await F0(C)}finally{let w0=this.sessions.get(W);if(w0?.status==="pending")await this.markTurnRunning(w0)}}:void 0,telemetry:b.telemetry,onConsecutiveMistakeLimitReached:b.onConsecutiveMistakeLimitReached,completionPolicy:S.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(W);return C?AJ(C.prompt,C.mode??b.mode):void 0},logger:S.logger??b.logger,extensionContext:b.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(W,b,C)};t.hooks={...t.hooks,onEvent:async(C)=>{if(await z.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let F0=this.sessions.get(W);if(!F0)return;let f0=F0.agent.getMessages();try{await this.invoke("persistSessionMessages",W,f0,b.systemPrompt)}catch(w0){b.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:W,error:w0}),y2(b.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:w0,severity:"warn",handled:!0,context:{sessionId:W,providerId:b.providerId,modelId:b.modelId}})}}};let o0=this.createAgentInstance(t);if(t.onEvent)o0.subscribeEvents(t.onEvent);S.registerLeadAgent?.(o0);let b$=l1({agentId:o0.getAgentId(),conversationId:o0.getConversationId(),teamId:S.teamRuntime?.getTeamId(),teamName:S.teamRuntime?.getTeamName(),teamRole:S.teamRuntime?"lead":void 0});if(hH(b,W,Z.length>0,A,b$),b$)Z$(b.telemetry,{ulid:W,modelId:b.modelId,provider:b.providerId,...b$});if(S.teamRuntime)sJ(b.telemetry,{ulid:W,teamId:S.teamRuntime.getTeamId(),teamName:S.teamRuntime.getTeamName(),leadAgentId:o0.getAgentId(),restoredFromPersistence:S.teamRestoredFromPersistence===!0});let n={sessionId:W,config:b,sessionMetadata:j.sessionMetadata,...G?{artifacts:G}:{},source:J,startedAt:G?.manifest.started_at??Q,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??Q,pendingPrompt:K.prompt,runtime:S,agent:o0,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:f,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(W,n),this.emitStatus(W,"running"),f.length>0&&!G){if(await this.ensureSessionPersisted(n),await this.invoke("persistSessionMessages",n.sessionId,f,n.config.systemPrompt),!j.prompt?.trim())await this.updateStatus(n,"completed",0)}let O1;try{if(j.prompt?.trim())if(O1=await this.executeTurn(n,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!n.interactive)await this.finalizeSingleRun(n,O1.finishReason);else await this.completeInteractiveTurn(n,O1.finishReason)}catch(C){if(n.interactive&&n.aborting)O1=await this.completeAbortedInteractiveTurn(n);else throw y2(n.config.telemetry,{component:"core",operation:"session.start",error:C,severity:"error",handled:!1,context:{sessionId:n.sessionId,providerId:n.config.providerId,modelId:n.config.modelId}}),await this.failSession(n),C}return{sessionId:W,manifest:K,manifestPath:B,messagesPath:H,result:O1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(J)=>this.getSession(J),readMessages:(J)=>this.readSessionMessages(J),buildStartInput:(J,Q)=>{let Z=J.restoredCheckpointMetadata?{...Q.sessionMetadata??{},checkpoint:J.restoredCheckpointMetadata}:Q.sessionMetadata;return{...Q,...Z?{sessionMetadata:Z}:{},initialMessages:J.initialMessages}},startSession:(J)=>this.startSession(J),getStartedSessionId:(J)=>J.sessionId,readRestoredSession:(J)=>this.getSession(J)})}async runTurn($){let J=this.getSessionOrThrow($.sessionId),Q=J.agent.canStartRun(),Z=$.delivery??(J.interactive&&!Q?"queue":void 0);if(J.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Z??"immediate"}}),Z==="queue"||Z==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Z,userImages:$.userImages,userFiles:$.userFiles});return}try{let W=await this.executeTurn(J,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!J.interactive)await this.finalizeSingleRun(J,W.finishReason);else await this.completeInteractiveTurn(J,W.finishReason);if(W.finishReason==="error"||W.finishReason==="aborted")return W;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),W}catch(W){if(J.interactive&&J.aborting)return await this.completeAbortedInteractiveTurn(J);throw y2(J.config.telemetry,{component:"core",operation:"session.submit",error:W,severity:"error",handled:!1,context:{sessionId:J.sessionId,providerId:J.config.providerId,modelId:J.config.modelId}}),await this.failSession(J),W}}async getAccumulatedUsage($){let J=uW(this.usageBySession.get($)),Q=uW(this.aggregateUsageBySession.get($));return J||Q?{usage:J,aggregateUsage:Q}:void 0}async abort($,J){let Q=this.sessions.get($);if(!Q)return;Q.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Q.aborting=!0,this.pendingPromptsController.clearAborted(Q),Q.agent.abort(J)}async stopSession($){let J=this.sessions.get($);if(!J)return;if(J.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),J.interactive&&!j0(J.status)){await this.releaseSessionRuntime(J,"session_stop");return}if(J.interactive&&J.agent.canStartRun()){await this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:"session_stop",endReason:"stopped"});return}J.aborting=!0,J.agent.abort(Error("session_stop")),await this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let J=[...this.sessions.values()];if(J.length===0)return;await Promise.allSettled(J.map((Q)=>Q.interactive&&!j0(Q.status)?this.releaseSessionRuntime(Q,$):Q.interactive&&Q.agent.canStartRun()?this.shutdownSession(Q,{status:this.resolveInteractiveStopStatus(Q),exitCode:this.resolveInteractiveStopExitCode(Q),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Q,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let J=this.sessions.get($);if(J)return Lj(J);let Q=$.trim();if(!Q)return;let Z=await this.getRow(Q);if(Z)return F6(Z);let W=await this.readManifest(Q);return W?$9(W):void 0}async listSessions($=200){let Q=(await this.listRows($)).map(F6),Z=new Set(Q.map((W)=>W.sessionId));for(let W of this.sessions.values()){if(Z.has(W.sessionId))continue;Q.unshift(Lj(W))}return Q.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let J=await this.invoke("deleteSession",$);if(J.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return J.deleted}async updateSession($,J){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:J.prompt,metadata:J.metadata,title:J.title}))?.updated===!0}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.getRow(J);if(Q?.messagesPath)return N$(Q.messagesPath);let Z=await this.readManifest(J);return N$(Z?.messages_path)}async dispatchHookEvent($){await uB($,{queueSpawnRequest:(J)=>this.invokeOptional("queueSpawnRequest",J),upsertSubagentSessionFromHook:(J)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",J),appendSubagentHookAudit:(J,Q)=>this.invokeOptional("appendSubagentHookAudit",J,Q),applySubagentStatus:(J,Q)=>this.invokeOptional("applySubagentStatus",J,Q)})}subscribe($,J){return this.events.subscribe($,J)}async updateSessionModel($,J){let Q=this.getSessionOrThrow($);Q.config.modelId=J,Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:J}),Q.agent.updateConnection({modelId:J})}handlePluginEvent($,J,Q){return this.eventBridge.handlePluginEvent($,J,Q)}async executeTurn($,J){let Q=await this.prepareTurnInput($,J),Z=Q.prompt.trim();if(!Z)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Z;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let W=await this.executeAgentTurn($,Z,Q.userImages,Q.userFiles);while(J3($,W.finishReason)){let j=await Q3($);if(j.length===0)break;let f=Z3($,j);W=await this.executeAgentTurn($,f)}return W}async completeInteractiveTurn($,J){if(BJ($))return;$.lastInteractiveTurnFinishReason=J,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let J=$.lastInteractiveTurnFinishReason;if(!J)return"cancelled";switch(J){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return J}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let J=new Date,Q=$.agent.getMessages(),Z=G0();return $.persistedMessages=Q,$.started=$.started||Q.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Z}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Z,messages:Q,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:J,endedAt:J,durationMs:0}}async executeAgentTurn($,J,Q,Z){let W=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),f=this.usageBySession.get($.sessionId)??G0(),X=this.aggregateUsageBySession.get($.sessionId)??f;$.turnUsageBaseline=f,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=G0(),$.turnUsageByAgent=new Map,dJ($.config.telemetry,$.sessionId,$.config.mode),u2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let Y=W?()=>$.agent.continue(J,Q,Z):()=>$.agent.run(J,Q,Z),V=await this.runWithAuthRetry($,Y,j);$.started=!0;let H=a5(V.messages,V,j);$.persistedMessages=H;let B=U6($.turnUsageByAgent?.values()??[]),A=H0(f,V.usage),K=H0(H0(G0(),V.usage),B),G=H0(X,K);return this.usageBySession.set($.sessionId,A),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:A.totalCost,aggregatedAgentsCost:G.totalCost,usage:A,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,V),V}catch(Y){throw y2($.config.telemetry,{component:"core",operation:"session.turn",error:Y,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),Y}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,J){if($.submitAndExitObserved)return;if(!J.toolCalls.some((Z)=>Z.name===K0.SUBMIT_AND_EXIT&&Z.error===void 0))return;$.submitAndExitObserved=!0,D4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,J){let Q=R$($.config),Z=SE(J.prompt).trim();if(!Z)return{prompt:"",userImages:J.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles)};let W=await X8(Z,Q);kH($.config.telemetry,W);let j=AJ(W.prompt,J.mode??$.config.mode),f=this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles),X=this.resolveAbsoluteFilePaths(Q,W.matchedFiles),Y=Array.from(new Set([...f,...X]));return{prompt:j,userImages:J.userImages,userFiles:Y.length>0?Y:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let J=R$($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:J,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,J){let Q=this.sessions.get($),Z=await this.invokeOptionalValue("readSessionManifest",$)??Q?.artifacts?.manifest,W=J(Z?.metadata);if(!Q?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:W}))?.updated===!1)return;Q.sessionMetadata=W,Q.artifacts.manifest.metadata=W}async finalizeSingleRun($,J){if(BJ($))return;let Q=J==="aborted"||$.aborting,Z=J==="error";await this.shutdownSession($,{status:Q?"cancelled":Z?"failed":"completed",exitCode:Z?1:0,shutdownReason:Z?"session_error":"session_complete",endReason:J})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,J){if(J.status==="completed"&&!$.submitAndExitObserved)D4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});X9($);let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),y2($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,status:J.status,shutdownReason:J.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,J.status,J.exitCode)}catch(W){Z("update_status",W)}try{await $.agent.shutdown(J.shutdownReason)}catch(W){Z("agent_shutdown",W)}}try{await Promise.resolve($.runtime.shutdown(J.shutdownReason))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:J.endReason,ts:Date.now()}}),Q.length>0&&J.status==="failed")throw Q[0]}async releaseSessionRuntime($,J){let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),y2($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,reason:J,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(J)}catch(W){Z("agent_shutdown",W)}try{await Promise.resolve($.runtime.shutdown(J))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),Q.length>0)throw Q[0]}async updateStatus($,J,Q){if(!$.artifacts)return;let Z=await this.invoke("updateSessionStatus",$.sessionId,J,Q);if(!Z.updated)return;let W=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(W.status=J,j0(J))delete W.ended_at,W.exit_code=null;else W.ended_at=Z.endedAt??e(),W.exit_code=typeof Q==="number"?Q:null;$.artifacts.manifest=W,$.status=J,$.updatedAt=Z.endedAt??e(),$.endedAt=j0(J)?null:W.ended_at,$.exitCode=W.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,W),this.emitStatus($.sessionId,J)}async runWithAuthRetry($,J,Q){try{return await J()}catch(Z){if(!l$($.config.providerId)||!wE(Z))throw Z;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Q),J()}}async syncOAuthCredentials($,J){let Q=null;try{Q=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:J?.forceRefresh})}catch(Z){if(Z instanceof d9)throw Error(`${Z.providerId} requires re-authentication.`);throw Z}if(!Q?.apiKey||$.config.apiKey===Q.apiKey)return;$.config.apiKey=Q.apiKey,$.agent.updateConnection({apiKey:Q.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Q.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Q.apiKey})}getSessionOrThrow($){let J=this.sessions.get($);if(!J){let Q=new h1($);throw y2(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Q,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Q}return J}resolveAbsoluteFilePaths($,J){if(!J||J.length===0)return[];let Q=J.map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>PE(Z)?Z:qj($,Z));return Array.from(new Set(Q))}getSessionAgentTelemetryIdentity($){return l1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let J=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Q=H0($.initialUsage,J);return this.withPersistedAggregateUsageFloor(Q,$.manifest)}async summarizePersistedTeammateUsage($,J,Q){let Z=qj(J),W=`${Q}.messages.json`,j;try{j=ME($)}catch{return G0()}let f=G0();for(let X of j){if(!X.endsWith(".messages.json"))continue;if(X===W)continue;let Y=qj($,X);if(Y===Z)continue;let V=await N$(Y);if(V.length===0)continue;f=H0(f,U8(V))}return f}withPersistedAggregateUsageFloor($,J){let Q=yE(J.metadata?.aggregateUsage);if(Q)return EE($,Q);let Z=J.metadata?.aggregatedAgentsCost;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=$.totalCost)return $;return{...$,totalCost:Z}}emitStatus($,J){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:J}})}async emitSessionSnapshot($){let J=await this.getSession($);if(!J)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:F1({session:J,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),YG))}async getRow($){let J=$.trim();if(!J)return;return(await this.listRows(YG)).find((Z)=>Z.sessionId===J)}async readManifest($){let J=$.trim();if(!J)return;return await this.invokeOptionalValue("readSessionManifest",J)}invoke($,...J){return WG(this.sessionService,$,...J)}invokeOptional($,...J){return jG(this.sessionService,$,...J)}invokeOptionalValue($,...J){return fG(this.sessionService,$,...J)}}function hE($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function kE($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function oK($={}){let J=new L1({sessionService:new z1(new U1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||R0.CLI,interactive:!1,config:{providerId:bE(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:kE(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content)});if(!W)throw Error("local hub schedule runtime returned no turn result");return{result:hE(W)}},async abortSession(Q){return await J.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}import{resolveClineBuildEnv as JF}from"@cline/shared";function IE($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Q)=>{if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text.trim();return""}).filter(Boolean).join(`
712
+ `).trim()||void 0}var VG=120,Pj="...";function OJ($){let J=$.trim();if(!J)return"";if(Buffer.byteLength(J,"utf8")<=VG)return J;let Q=VG-Buffer.byteLength(Pj,"utf8");if(Q<=0)return Pj;let Z="";for(let W of J){if(Buffer.byteLength(Z+W,"utf8")>Q)break;Z+=W}return`${Z}${Pj}`}async function HG($){let J=$?.sessionId?.trim()||"unknown",Q=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,W=[...await N$(Q)].reverse().find((Y)=>Y.role==="assistant"),j=W?IE(W.content):void 0,f=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():f;return{title:`Task completed (${J})`,body:OJ(j&&j.length>0?j:X.length>0?X:f),severity:"info"}}import{captureSdkError as n9,createSessionId as Bb}from"@cline/shared";import{createSessionId as vE}from"@cline/shared";import{createSessionId as mE}from"@cline/shared";function xE($){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 gE($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())J.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())J.parentAgentId=$.parentAgentId;if($.agentId?.trim())J.agentId=$.agentId;if($.conversationId?.trim())J.conversationId=$.conversationId;if($.messagesPath?.trim())J.messagesPath=$.messagesPath;if($.prompt?.trim())J.prompt=$.prompt;if($.provider?.trim())J.provider=$.provider;if($.model?.trim())J.model=$.model;if($.source?.trim())J.source=$.source;if(typeof $.pid==="number")J.pid=$.pid;return Object.keys(J).length>0?J:void 0}function p9($,J,Q,Z){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:J?.createdByClientId??"hub",status:xE($.status),participants:J?[...J.participants.values()]:[],metadata:gE($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Q?{usage:{...Q}}:{},...Z?{aggregateUsage:{...Z}}:{}}}function l($,J){return{version:$.version,requestId:$.requestId,ok:!0,...J!==void 0?{payload:J}:{}}}function v($,J,Q){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:J,message:Q}}}function r9($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function k0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function E2($,J,Q){return{version:"v1",event:$,eventId:mE("hevt_"),sessionId:Q,timestamp:Date.now(),payload:J}}async function a0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let Z=await $.sessionHost.getAccumulatedUsage?.(J);return p9(Q,$.sessionState.get(J),Z?.usage,Z?.aggregateUsage)}async function s0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let[Z,W]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(J):[],$.sessionHost.getAccumulatedUsage?.(J)]);return F1({session:Q,messages:Z,usage:W?.usage,aggregateUsage:W?.aggregateUsage})}function i9($,J,Q,Z,W={}){let j=$.sessionState.get(J);if(j){if(W.interactive!==void 0)j.interactive=W.interactive;if(!j.participants.has(Q))j.participants.set(Q,{clientId:Q,attachedAt:Date.now(),role:Z});return j}let f={createdByClientId:Q,interactive:W.interactive??!0,participants:new Map([[Q,{clientId:Q,attachedAt:Date.now(),role:Z}]])};return $.sessionState.set(J,f),f}async function Nj($,J){let Q=vE("approval_"),Z=J.sessionId;if($.sessionState.get(Z)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Q,{sessionId:Z,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Q,sessionId:J.sessionId,agentId:J.agentId,conversationId:J.conversationId,iteration:J.iteration,toolCallId:J.toolCallId,toolName:J.toolName,inputJson:JSON.stringify(J.input??null),policy:J.policy},Z))})}function wj($,J,Q){let Z=$.pendingApprovals.get(J);if(!Z)return;return $.pendingApprovals.delete(J),Z.resolve(Q),{sessionId:Z.sessionId}}function Sj($,J,Q){let Z=0;for(let[W,j]of[...$.pendingApprovals.entries()]){if(!J({approvalId:W,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(W),j.resolve({approved:!1,reason:Q}),$.publish($.buildEvent("approval.resolved",{approvalId:W,approved:!1,cancelled:!0,reason:Q},j.sessionId)),Z+=1}return Z}async function BG($,J){let Q=typeof J.payload?.approvalId==="string"?J.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Q))return v(J,"approval_not_found",`Unknown approval: ${Q}`);let W=typeof J.payload?.reason==="string"?J.payload.reason:J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)&&typeof J.payload.payload.reason==="string"?J.payload.payload.reason:void 0,j=J.payload?.approved===!0,f=wj($,Q,{approved:j,reason:W});if(!f)return v(J,"approval_not_found",`Unknown approval: ${Q}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Q,approved:j,reason:W},f.sessionId)),l(J,{approvalId:Q,approved:j})}import{createSessionId as dE}from"@cline/shared";function cE($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var AG={debug:10,info:20,warn:30,error:40,silent:50};function uE(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function c($,J,Q={}){if(AG[$]<AG[uE()])return;let Z=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:J,...Object.fromEntries(Object.entries(Q).map(([W,j])=>[W,cE(j)]).filter(([,W])=>W!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Z}`);return}console.log(`[hub] ${Z}`)}function Cj($,J){let Q=J instanceof Error?J.stack||J.message:String(J);c("error",$,{error:Q})}async function KG($,J,Q,Z,W,j){let f=dE("capreq_"),X=performance.now();return c("info","capability.request.start",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W}),await new Promise((Y,V)=>{$.pendingCapabilityRequests.set(f,{sessionId:J,targetClientId:W,capabilityName:Q,onProgress:j,resolve:(H)=>{if(c(H.ok?"info":"warn","capability.request.end",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-X)}),!H.ok){V(Error(H.error||`Capability ${Q} was rejected by ${W}.`));return}Y(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:f,targetClientId:W,capabilityName:Q,payload:Z},J)),c("info","capability.request.published",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W})})}function GG($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return v(J,"capability_not_found",`Unknown capability request: ${Q}`);if((J.clientId?.trim()||"")!==Z.targetClientId)return v(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return v(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{};return Z.onProgress?.(j),l(J,{requestId:Q})}function E$($,J,Q){let Z=0;for(let[W,j]of[...$.pendingCapabilityRequests.entries()]){if(!J({requestId:W,...j}))continue;$.pendingCapabilityRequests.delete(W),c("warn","capability.request.cancelled",{requestId:W,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Q}),j.resolve({ok:!1,error:Q}),$.publish($.buildEvent("capability.resolved",{requestId:W,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Q},j.sessionId)),Z+=1}return Z}async function FG($,J){let Q=typeof J.payload?.sessionId==="string"?J.payload.sessionId.trim():J.sessionId?.trim()||"",Z=typeof J.payload?.capabilityName==="string"?J.payload.capabilityName.trim():"",W=typeof J.payload?.targetClientId==="string"?J.payload.targetClientId.trim():"";if(!Q||!Z||!W)return v(J,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{},f=await $.requestCapability(Q,Z,j,W);return l(J,f)}catch(j){return v(J,"capability_request_failed",j instanceof Error?j.message:String(j))}}function DG($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return v(J,"capability_not_found",`Unknown capability request: ${Q}`);let W=J.clientId?.trim()||"";if(W!==Z.targetClientId)return v(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return v(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);$.pendingCapabilityRequests.delete(Q);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:void 0,f=typeof J.payload?.error==="string"?J.payload.error:void 0,X=J.payload?.ok===!0;return c(X?"info":"warn","capability.respond",{requestId:Q,sessionId:Z.sessionId,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,error:f}),Z.resolve({ok:X,payload:j,error:f}),$.publish($.buildEvent("capability.resolved",{requestId:Q,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,payload:j,error:f},Z.sessionId)),l(J,{requestId:Q,ok:X})}import{createSessionId as lE}from"@cline/shared";function UG($,J){let Q=J.payload,Z=Q?.clientId?.trim()||J.clientId?.trim()||lE("client_");return $.clients.set(Z,{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,actorKind:Q?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Q?.transport??"native",capabilities:Q?.capabilities??[],metadata:Q?.metadata,workspaceContext:Q?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,connectedAt:Date.now()})),l(J,{clientId:Z})}function RG($,J){let Q=J.clientId?.trim(),Z=Q?$.clients.get(Q):void 0;if(!Q||!Z)return v(J,"client_not_found","Client is not registered with this hub.");let W=r9(J.payload?.metadata);if(Z.lastSeenAt=Date.now(),W)Z.metadata=JSON.parse(JSON.stringify(W));return l(J)}function zG($,J,Q){let Z=J.clientId?.trim();if(Z)$.clients.delete(Z),Q(Z),$.publish($.buildEvent("hub.client.disconnected",{clientId:Z}));return l(J)}function LG($,J){return l(J,{clients:[...$.clients.values()]})}var pE=30000;function rE($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function iE($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function nE($,J,Q){let Z=Q instanceof Error&&Q.message.trim()?Q.message:`Unknown session: ${J}`;return v($,g$,Z)}function aE($){return $?$:void 0}function sE($){let J=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J);let Q=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Q&&Number.isFinite(Q)&&Q>0)return Math.floor(Q*1000);return}async function oE($,J,Q,Z){let W=performance.now(),j=!1,f={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q.sessionId,timeoutMs:Z},X=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-W);c("warn","run.heartbeat",{...f,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:J.requestId,elapsedMs:H,...Z?{timeoutMs:Z}:{}},Q.sessionId))},pE),Y=$.sessionHost.runTurn(Q);Y.then((H)=>{if(!j)return;c("warn","run.late_end",{...f,elapsedMs:Math.round(performance.now()-W),finishReason:H?.finishReason})},(H)=>{if(!j)return;c("error","run.late_error",{...f,elapsedMs:Math.round(performance.now()-W),error:H})});let V;try{if(!Z)return await Y;return await Promise.race([Y,new Promise((H,B)=>{V=setTimeout(()=>{let A=`Hub run ${J.command} timed out after ${Z}ms.`;j=!0,clearInterval(X),B(Error(A)),c("error","run.timeout",{...f,elapsedMs:Math.round(performance.now()-W)}),Sj($,(K)=>K.sessionId===Q.sessionId,A),E$($,(K)=>K.sessionId===Q.sessionId,A),$.sessionHost.abort(Q.sessionId,A).catch((K)=>{c("error","run.timeout_abort_failed",{...f,error:K})})},Z)})])}finally{if(j=!0,clearInterval(X),V)clearTimeout(V)}}async function _G($,J){let Q=k0(J),Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.prompt==="string"?Z.prompt:typeof Z.input==="string"?Z.input:"";if(!W.trim())return v(J,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Q));let j=Z.attachments&&typeof Z.attachments==="object"&&!Array.isArray(Z.attachments)?Z.attachments:void 0,f=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,X=sE(Z);$.suppressNextTerminalEventBySession.set(Q,"run.start.reply");let Y;try{Y=await oE($,J,{sessionId:Q,prompt:W,mode:aE(Z.mode),delivery:Z.delivery==="queue"||Z.delivery==="steer"?Z.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:f,timeoutMs:X},X)}catch(H){if($.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q);if(k1(H))return nE(J,Q,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Q)),H}if(Y){let H=await s0($,Q),B=iE(Y);if($.publish($.buildEvent(rE(Y.finishReason),{reason:Y.finishReason,...B?{error:B}:{},result:Y,...H?{snapshot:H}:{}},Q)),$.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q)}else $.suppressNextTerminalEventBySession.delete(Q);let V=await s0($,Q);return l(J,Y||V?{...Y?{result:Y}:{},...V?{snapshot:V}:{}}:void 0)}async function OG($,J){let Q=k0(J),Z=typeof J.payload?.reason==="string"?J.payload.reason:"Run was aborted before pending approval or capability request was resolved.";Sj($,(W)=>W.sessionId===Q,Z);try{await $.sessionHost.abort(Q,J.payload?.reason)}catch(W){c("warn","run.abort_failed",{command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q,error:W})}finally{E$($,(W)=>W.sessionId===Q,Z)}return l(J,{applied:!0})}async function TG($,J){let Q=o8(J.payload?.payload);if(!Q)return v(J,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Q),l(J,{applied:!0})}async function MG($,J){switch(J.type){case"chunk":return;case"agent_event":await tE($,J);return;case"hook":if(J.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:J.payload.toolName},J.payload.sessionId));else if(J.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:J.payload.toolName},J.payload.sessionId));return;case"team_progress":{let Q={type:"team_progress_projection",version:1,sessionId:J.payload.sessionId,summary:J.payload.summary,lastEvent:J.payload.lifecycle};$.publish($.buildEvent("team.progress",Q,J.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:J.payload.sessionId,prompts:J.payload.prompts},J.payload.sessionId));return;case"pending_prompt_submitted":{let Q={id:J.payload.id,prompt:J.payload.prompt,delivery:J.payload.delivery,attachmentCount:J.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:J.payload.sessionId,prompt:Q},J.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:J.payload.sessionId,snapshot:J.payload.snapshot},J.payload.sessionId));return;case"status":{let[Q,Z]=await Promise.all([a0($,J.payload.sessionId),s0($,J.payload.sessionId)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J.payload.sessionId));return}case"ended":await eE($,J);return;default:return}}async function tE($,J){let{sessionId:Q,event:Z}=J.payload;if(Z.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Z.iteration},Q));return}if(Z.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Z.iteration,hadToolCalls:Z.hadToolCalls,toolCallCount:Z.toolCallCount},Q));return}if(Z.type==="content_start"){if(Z.contentType==="text"&&typeof Z.text==="string"&&Z.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Z.text},Q));return}if(Z.contentType==="reasoning"){if(Z.redacted&&!Z.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Q));return}if(typeof Z.reasoning==="string"&&Z.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Z.reasoning,redacted:Z.redacted===!0},Q));return}if(Z.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Z.toolCallId,toolName:Z.toolName,input:Z.input},Q));return}}if(Z.type==="content_end"){switch(Z.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Z.text},Q));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Z.reasoning},Q));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Z.toolCallId,toolName:Z.toolName,output:Z.output,error:Z.error},Q));break}return}if(Z.type==="usage"){let W;try{W=await $.sessionHost.getAccumulatedUsage?.(Q)}catch{W=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Q,delta:{inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadTokens:Z.cacheReadTokens??0,cacheWriteTokens:Z.cacheWriteTokens??0,totalCost:Z.cost??0},totals:{inputTokens:Z.totalInputTokens,outputTokens:Z.totalOutputTokens,cacheReadTokens:Z.totalCacheReadTokens??0,cacheWriteTokens:Z.totalCacheWriteTokens??0,totalCost:Z.totalCost??0},usage:W?.usage,aggregateUsage:W?.aggregateUsage,agent:{kind:J.payload.teamRole==="teammate"?"teammate":Z.parentAgentId?"subagent":"lead",agentId:Z.agentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamAgentId:J.payload.teamAgentId,teamRole:J.payload.teamRole}},Q));return}if(Z.type==="done")$.publish($.buildEvent("agent.done",{reason:Z.reason,text:Z.text,iterations:Z.iterations,usage:Z.usage},Q))}async function eE($,J){let Q=$.suppressNextTerminalEventBySession.get(J.payload.sessionId),Z=Q===J.payload.reason||Q==="run.start.reply";if(Z)$.suppressNextTerminalEventBySession.delete(J.payload.sessionId);let[W,j]=await Promise.all([a0($,J.payload.sessionId),s0($,J.payload.sessionId)]);if(J.payload.reason==="completed"){let f=await HG(W);$.publish($.buildEvent("ui.notify",f,J.payload.sessionId))}if(Z)return;$.publish($.buildEvent(J.payload.reason==="aborted"?"run.aborted":J.payload.reason==="error"||J.payload.reason==="failed"?"run.failed":"run.completed",{reason:J.payload.reason,...j?{snapshot:j}:{}},J.payload.sessionId))}import{createSessionId as NG,parseRuntimeConfigExtensions as wG}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Ta,HUB_COMPACTION_CAPABILITY as Ma,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as qa,HUB_HOOK_CAPABILITY_PREFIX as Pa,HUB_MISTAKE_LIMIT_CAPABILITY as Na,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as wa,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Sa,isHubToolExecutorName as $b}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as ha,HUB_COMPACTION_CAPABILITY as ka,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Ia,HUB_HOOK_CAPABILITY_PREFIX as xa,HUB_MISTAKE_LIMIT_CAPABILITY as ga,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ma,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as va}from"@cline/shared";var Jb=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function b2($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function Qb($,J){let Q=typeof $.name==="string"?$.name.trim():"",Z=typeof $.description==="string"?$.description:"",W=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=b2($.inputSchema);if(!Q||!Z||!j||!W||J.has(W))return;return J.add(W),{kind:"tool",capabilityName:W,name:Q,description:Z,inputSchema:j,...b2($.lifecycle)?{lifecycle:b2($.lifecycle)}:{}}}function Ej($){if(!Array.isArray($))return[];let J=[],Q=new Set;for(let Z of $){if(!Z||typeof Z!=="object"||Array.isArray(Z))continue;let W=Z,j=W.kind,f=typeof W.capabilityName==="string"?W.capabilityName.trim():"";if(!f||Q.has(f))continue;if(j==="tool"){let X=Qb(W,Q);if(X)J.push(X);continue}if(j==="toolExecutor"){let X=W.executor;if(!$b(X))continue;Q.add(f),J.push({kind:"toolExecutor",capabilityName:f,executor:X});continue}if(j==="hook"){let X=typeof W.name==="string"?W.name.trim():"";if(!X)continue;Q.add(f),J.push({kind:"hook",capabilityName:f,name:X});continue}if(j==="compaction"){Q.add(f),J.push({kind:"compaction",capabilityName:f,...b2(W.config)?{config:b2(W.config)}:{}});continue}if(j==="checkpoint"){Q.add(f),J.push({kind:"checkpoint",capabilityName:f,...b2(W.config)?{config:b2(W.config)}:{}});continue}if(j==="mistakeLimit"){Q.add(f),J.push({kind:"mistakeLimit",capabilityName:f});continue}if(j==="userInstructionService")Q.add(f),J.push({kind:"userInstructionService",capabilityName:f})}return J}function PG($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function Zb($){return Object.hasOwn($,"update")?$.update:$}function NJ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function Wb($){let J=($??[]).map(NJ).filter(Boolean);return J.length>0?new Set(J):void 0}function jb($,J,Q){if(!Q)return!0;let Z=NJ($),W=NJ(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function yj($,J){let Q=Wb(J);return $.records.skill.map((Z)=>({id:Z.id,name:Z.item.name,description:"description"in Z.item&&typeof Z.item.description==="string"?Z.item.description:void 0,disabled:Z.item.disabled===!0,skill:Z.item})).filter((Z)=>jb(Z.id,Z.name,Q))}function qG($,J){let Q=async(Z,W)=>{let j=NJ(Z),X=yj($,J).filter((A)=>A.id===j||NJ(A.name)===j||A.id.endsWith(`:${j}`)).filter((A)=>!A.disabled);if(X.length!==1)return X.length>1?`Skill "${Z}" is ambiguous. Use one of: ${X.map((A)=>A.id).join(", ")}`:`Skill "${Z}" not found.`;let Y=X[0].skill,V=W?.trim(),H=V?`
713
+ <command-args>${V}</command-args>`:"",B=Y.description?.trim()?`Description: ${Y.description.trim()}
714
+
715
+ `:"";return`<command-name>${Y.name}</command-name>${H}
706
716
  <command-instructions>
707
- ${H}${Y.instructions}
708
- </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>H3($,f).map(({skill:Q,...Z})=>Z),enumerable:!0}),J}function uS($,f,J,Q){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},W=async()=>{let j=await Q($,J.capabilityName,{},f);if(j?.snapshot)Z=j.snapshot};return{start:W,stop:()=>{},refreshType:async()=>{await W()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let Y=j.match(/^\/(\S+)/)?.[1];if(!Y)return j;let A=Z.runtimeCommands.find((V)=>V.name===Y);return A?`${A.instructions}${j.slice(Y.length+1)}`:j},hasConfiguredSkills:(j)=>H3(Z,j).some((X)=>!X.disabled),createSkillsExecutor:(j)=>lK(Z,j),createExtension:(j)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[j.includeRules?"rules":void 0,j.registerSkillsTool?"tools":void 0,j.includeSkills||j.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(j.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>xf(Z.records.rule.map((Y)=>Y.item).filter((Y)=>Y.disabled!==!0))});if(j.registerSkillsTool)X.registerTool(n$(lK(Z,j.allowedSkillNames)));for(let Y of Z.runtimeCommands.filter((A)=>A.kind==="skill"&&j.includeSkills||A.kind==="workflow"&&j.includeWorkflows))X.registerCommand({name:Y.name,description:Y.description,handler:(A)=>{let V=A.trim();return V?`${Y.instructions}
717
+ ${B}${Y.instructions}
718
+ </command-instructions>`};return Object.defineProperty(Q,"configuredSkills",{get:()=>yj($,J).map(({skill:Z,...W})=>W),enumerable:!0}),Q}function fb($,J,Q,Z){let W={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let f=await Z($,Q.capabilityName,{},J);if(f?.snapshot)W=f.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(f)=>[...W.records[f]],listRuntimeCommands:()=>[...W.runtimeCommands],resolveRuntimeSlashCommand:(f)=>{if(!f.startsWith("/")||f.length<2)return f;let Y=f.match(/^\/(\S+)/)?.[1];if(!Y)return f;let V=W.runtimeCommands.find((H)=>H.name===Y);return V?`${V.instructions}${f.slice(Y.length+1)}`:f},hasConfiguredSkills:(f)=>yj(W,f).some((X)=>!X.disabled),createSkillsExecutor:(f)=>qG(W,f),createExtension:(f)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(f.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>g2(W.records.rule.map((Y)=>Y.item).filter((Y)=>Y.disabled!==!0))});if(f.registerSkillsTool)X.registerTool(n$(qG(W,f.allowedSkillNames)));for(let Y of W.runtimeCommands.filter((V)=>V.kind==="skill"&&f.includeSkills||V.kind==="workflow"&&f.includeWorkflows))X.registerCommand({name:Y.name,description:Y.description,handler:(V)=>{let H=V.trim();return H?`${Y.instructions}
709
719
 
710
- ${V}`:Y.instructions}})}})}}function dS($,f,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let X=j.at(-1),Y=j.slice(0,-1);return(await Q($,W.capabilityName,{executor:W.executor,args:Y,context:pK(X)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function lS($,f,J,Q){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(W,j){return(await Q($,Z.capabilityName,{toolName:Z.name,input:W,context:pK(j)},f,j.emitUpdate?(Y)=>{j.emitUpdate?.(mS(Y))}:void 0))?.result}}))}function pS($,f,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of xS){let X=Z.get(j);if(!X)continue;W[j]=async(Y)=>{return(await Q($,X.capabilityName,{context:Y},f))?.control}}return Object.keys(W).length>0?W:void 0}function K3($){let f=$.contributions.filter((Y)=>Y.kind==="toolExecutor"),J=$.contributions.filter((Y)=>Y.kind==="tool"),Q=$.contributions.filter((Y)=>Y.kind==="hook"),Z=$.contributions.find((Y)=>Y.kind==="compaction"),W=$.contributions.find((Y)=>Y.kind==="checkpoint"),j=$.contributions.find((Y)=>Y.kind==="mistakeLimit"),X=$.contributions.find((Y)=>Y.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:dS($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...Q.length>0?{hooks:pS($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...J.length>0?{extraTools:lS($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(Y)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...W?{checkpoint:{...$.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(Y)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(Y)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:Y},$.targetClientId))?.result}}:{},...X?{userInstructionService:uS($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var nK="hubCapabilityOwnerClientId";function aK($,f){$[nK]=f}function rS($){let f=$?.[nK];return typeof f==="string"&&f.trim()?f.trim():void 0}async function tK($,f,J){let Q=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};c("info","session.create.begin",Z);let W=f.payload&&typeof f.payload==="object"?f.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,Y=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof X?.mode==="string")j.mode=X.mode;else if(typeof Y.mode==="string")j.mode=Y.mode;if(typeof X?.systemPrompt==="string")j.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")j.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)j.checkpointEnabled=!0;let A=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},V=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!V)return c("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),v(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let H=f.clientId?.trim()||"hub-client",B=B3(Y.clientContributions);if(c("info","session.create.contributions_parsed",{...Z,clientId:H,workspaceRoot:V,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:B.length}),B.length>0)aK(j,H);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||rK(),R=iK(Y.configExtensions);c("info","session.create.runtime_build.begin",{...Z,sessionId:G,configExtensionCount:R?.length??0});let P=K3({sessionId:G,targetClientId:H,contributions:B,sessionConfig:X,requestCapability:$.requestCapability});c("info","session.create.start_session.begin",{...Z,sessionId:G,provider:X?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),model:X?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub")});let F=await $.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(W.initialMessages)?W.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:X?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub"),apiKey:X?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:X?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():V),workspaceRoot:X?.workspaceRoot??V,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});c("info","session.create.start_session.end",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!F.result}),b9($,F.sessionId,H,"creator",{interactive:j.interactive!==!1}),c("info","session.create.read_records.begin",{...Z,sessionId:F.sessionId});let[D,z]=await Promise.all([n0($,F.sessionId),a0($,F.sessionId)]);if(c("info","session.create.read_records.end",{...Z,sessionId:F.sessionId,hasSession:!!D,hasSnapshot:!!z,elapsedMs:Math.round(performance.now()-Q)}),D)$.publish($.buildEvent("session.created",{session:D,...z?{snapshot:z}:{}},F.sessionId));return c("info","session.create.reply",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q)}),d(f,{session:D,...z?{snapshot:z}:{}})}async function sK($,f,J){let Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():f.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return v(f,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},X=j.messages!==!1;if(typeof W!=="number")return v(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let Y=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(X&&!Y)return v(f,"invalid_restore","sessionConfig is required when restore.messages is true");let A=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},V=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof Y?.mode==="string")V.mode=Y.mode;else if(typeof A.mode==="string")V.mode=A.mode;if(typeof Y?.systemPrompt==="string")V.systemPrompt=Y.systemPrompt;else if(typeof A.systemPrompt==="string")V.systemPrompt=A.systemPrompt;if(Y?.checkpoint?.enabled===!0)V.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)V.checkpointEnabled=!0;let H=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},B=f.clientId?.trim()||"hub-client",K=B3(A.clientContributions);if(K.length>0)aK(V,B);let R=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||rK(),P=iK(A.configExtensions),F=K3({sessionId:R,targetClientId:B,contributions:K,sessionConfig:Y,requestCapability:$.requestCapability}),z=await new y$().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:Y,cwd:typeof Y?.cwd==="string"&&Y.cwd.trim()||typeof Y?.workspaceRoot==="string"&&Y.workspaceRoot.trim()||void 0,getSession:(w)=>$.sessionHost.getSession(w),readMessages:(w)=>$.sessionHost.readSessionMessages(w),buildStartInput:(w)=>{if(w.restoredCheckpointMetadata)V.checkpoint=w.restoredCheckpointMetadata;let h=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():w.sourceSession.workspaceRoot||w.sourceSession.cwd;return{source:typeof V.source==="string"?V.source:void 0,interactive:V.interactive!==!1,sessionMetadata:{...V,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:w.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:P,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...Y??{},sessionId:R,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:w.sourceSession.provider),modelId:Y?.modelId??(typeof H.model==="string"?H.model:w.sourceSession.model),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:""),cwd:Y?.cwd??w.plan.cwd,workspaceRoot:Y?.workspaceRoot??h,systemPrompt:Y?.systemPrompt??(typeof A.systemPrompt==="string"?A.systemPrompt:""),mode:Y?.mode??(A.mode==="plan"||A.mode==="yolo"?A.mode:"act"),maxIterations:Y?.maxIterations??(typeof A.maxIterations==="number"?A.maxIterations:void 0),enableTools:Y?.enableTools??A.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??A.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??A.enableTeams!==!1,checkpoint:Y?.checkpoint??(A.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof V.teamName==="string"?V.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(w)=>$.sessionHost.startSession(w),getStartedSessionId:(w)=>w.sessionId,readRestoredSession:(w)=>$.sessionHost.getSession(w)});if(!X)return d(f,{checkpoint:z.checkpoint});let T=z.startResult;if(!T)return v(f,"restore_failed","Checkpoint restore did not start a session");b9($,T.sessionId,B,"creator",{interactive:V.interactive!==!1});let[L,U]=await Promise.all([n0($,T.sessionId),a0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...U?{snapshot:U}:{}},T.sessionId));return d(f,{session:L,...U?{snapshot:U}:{},messages:z.messages??[],checkpoint:z.checkpoint})}catch(Y){if(Y instanceof h0)return v(f,Y.code,Y.code==="session_not_found"?`Unknown session: ${Z}`:Y.message);return v(f,"restore_failed",Y instanceof Error?Y.message:String(Y))}}async function oK($,f){let J=b0(f);if(!J)return v(f,"invalid_session_attach","session.attach requires a session id");b9($,J,f.clientId?.trim()||"hub-client","participant");let Q=await n0($,J);if(Q)$.publish($.buildEvent("session.attached",{session:Q},J));return Q?d(f,{session:Q}):v(f,"session_not_found",`Unknown session: ${J}`)}async function eK($,f){let J=b0(f);if(!J)return v(f,"invalid_session_detach","session.detach requires a session id");let Q=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([n0($,J)]),W=rS(Z?.metadata)??Q,j=$.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)$.sessionState.delete(J)}S$($,(A)=>A.sessionId===J&&A.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[X,Y]=await Promise.all([n0($,J),a0($,J)]);return $.publish($.buildEvent("session.detached",X?{session:X,...Y?{snapshot:Y}:{},clientId:Q}:{clientId:Q},J)),d(f)}async function $G($,f){let J=b0(f),Q=f.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([n0($,J),Q?a0($,J):Promise.resolve(void 0)]);return Z?d(f,{session:Z,...W?{snapshot:W}:{}}):v(f,"session_not_found",`Unknown session: ${J}`)}async function fG($,f){let J=b0(f);if(!J)return v(f,"invalid_session_id","session.messages requires a session id");if(!await n0($,J))return v(f,"session_not_found",`Unknown session: ${J}`);let Z=await $.sessionHost.readSessionMessages(J);return d(f,{sessionId:J,messages:Z})}async function JG($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((W)=>E9(W,$.sessionState.get(W.sessionId)));return d(f,{sessions:Z})}async function QG($,f){let J=b0(f),Q=h9(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([n0($,J),a0($,J)]);if(W)$.publish($.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function ZG($,f){let J=b0(f),Q=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),d(f,{deleted:Q})}async function WG($,f){let J=b0(f),Q=$.sessionHost.pendingPrompts;if(!Q)return v(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return d(f,{sessionId:J,prompts:Z})}async function jG($,f){let J=b0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,W=f.payload?.delivery==="queue"||f.payload?.delivery==="steer"?f.payload.delivery:void 0,j=$.sessionHost.pendingPrompts;if(!j)return v(f,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return d(f,X)}async function XG($,f){let J=b0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=$.sessionHost.pendingPrompts;if(!Z)return v(f,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return d(f,W)}function YG($){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 nS=new Set(["skills","workflows","rules","tools","mcp"]);function G3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function LJ($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${f}' must be a string.`);return J}function aS($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${f}' must be a boolean.`);return J}function AG($){if($===void 0)return{};if(!G3($))throw Error("settings.list payload must be an object.");return{cwd:LJ($,"cwd"),workspaceRoot:LJ($,"workspaceRoot"),availabilityContext:G3($.availabilityContext)?$.availabilityContext:void 0}}function tS($){if(!G3($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!nS.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...AG($),type:f,id:LJ($,"id"),path:LJ($,"path"),name:LJ($,"name"),enabled:aS($,"enabled")}}class e2{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=iS("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new U1({sessionService:new D1(new P1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(f)=>this.publish(f),buildEvent:Sf,requestCapability:(f,J,Q,Z,W)=>EK(this.ctx,f,J,Q,Z,W)},this.schedules=new vf({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let Q=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(Sf(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new If(this.schedules),this.settings=$.settingsService??new T$,$.cronOptions)this.cronService=new a4({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{dK(this.ctx,f).catch((J)=>{V3("session event handling failed",J),k9(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:f.type,sessionId:f.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())Y3(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(S$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let f=await this.dispatchCommand($);return this.captureFailedReply($,f),f}catch(f){throw k9(this.options.telemetry,{component:"core",operation:"hub.command",error:f,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),f}}async dispatchCommand($){switch($.command){case"client.register":return IK(this.ctx,$);case"client.update":return xK(this.ctx,$);case"client.unregister":return gK(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return mK(this.ctx,$);case"session.create":return await tK(this.ctx,$,(f)=>X3(this.ctx,f));case"session.restore":return await sK(this.ctx,$,(f)=>X3(this.ctx,f));case"session.attach":return await oK(this.ctx,$);case"session.detach":return await eK(this.ctx,$);case"session.get":return await $G(this.ctx,$);case"session.messages":return await fG(this.ctx,$);case"session.list":return await JG(this.ctx,$);case"session.update":return await QG(this.ctx,$);case"session.pending_prompts":return await WG(this.ctx,$);case"session.update_pending_prompt":return await jG(this.ctx,$);case"session.remove_pending_prompt":return await XG(this.ctx,$);case"session.delete":return await ZG(this.ctx,$);case"session.hook":return await uK(this.ctx,$);case"run.start":case"session.send_input":return await vK(this.ctx,$);case"run.abort":return await cK(this.ctx,$);case"capability.request":return await bK(this.ctx,$);case"approval.respond":return await yK(this.ctx,$);case"capability.respond":return kK(this.ctx,$);case"capability.progress":return hK(this.ctx,$);case"ui.notify":return this.publish(Sf("ui.notify",$.payload??{})),d($);case"ui.show_window":return this.publish(Sf("ui.show_window",$.payload??{})),d($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let f=await this.scheduleCommands.handleCommand($);if(f.ok){let J=YG($.command);if(J)this.publish(Sf(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!sS(f.error.code))return;k9(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(f.error.message),severity:f.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:f.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let f=await this.settings.list(AG($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:f instanceof Error?f.message:String(f)}}}}async handleSettingsToggle($){try{let f=await this.settings.toggle(tS($.payload));return this.publish(Sf("settings.changed",{types:f.changedTypes,snapshot:f.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f.snapshot,changedTypes:f.changedTypes}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:f instanceof Error?f.message:String(f)}}}}subscribe($,f,J){let Q=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return Q.add(Z),this.listeners.set($,Q),()=>{let W=this.listeners.get($);if(!W)return;if(W.delete(Z),W.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[f,J]of this.sessionState.entries())if(J.participants.delete($),J.participants.size===0)this.sessionState.delete(f);S$(this.ctx,(f)=>f.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let f of this.listeners.values())for(let J of f){if(J.sessionId&&J.sessionId!==$.sessionId)continue;try{J.listener($)}catch(Q){V3(`listener threw while publishing ${$.event}`,Q),k9(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function sS($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as fE}from"node:crypto";import JE from"node:http";import QE from"node:net";import{URL as BG}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as KG,HUB_CAPABILITIES as ZE,isHubProtocolCompatible as WE,MAX_CLIENT_HUB_PROTOCOL_VERSION as GG,MIN_CLIENT_HUB_PROTOCOL_VERSION as FG}from"@cline/shared";import{WebSocketServer as jE}from"ws";import{captureSdkError as VG,HUB_COMMAND_SLOW_LOG_MS as oS,resolveHubCommandTimeoutMs as eS,safeJsonParse as $E}from"@cline/shared";function F3($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function HG($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class FJ{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,Q=!1,Z=(Y)=>{try{$.send(JSON.stringify(Y))}catch(A){console.error(`[hub] failed to send websocket frame: ${A instanceof Error?A.stack||A.message:String(A)}`)}},W=(Y)=>{Z({kind:"event",envelope:Y})},j=async(Y)=>{try{let A=JSON.parse(Y.data);switch(A.kind){case"command":{let V=performance.now(),H=!1,B=F3(A);c("info","command.start",B);let K=setTimeout(()=>{if(H)return;c("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},oS),G=this.transport.command(A.envelope);G.then((T)=>{if(!H)return;c(T.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!H)return;c("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:T})});let R=!1,P,F,D=eS(A.envelope.command,A.envelope.timeoutMs);try{F=D===null?await G:await Promise.race([G,new Promise((T)=>{P=setTimeout(()=>{R=!0,VG(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${A.envelope.command} did not complete within ${D}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:D}}),T(HG(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${D}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},D)})])}catch(T){if(clearTimeout(K),P)clearTimeout(P);throw T}if(H=R,clearTimeout(K),P)clearTimeout(P);let z=Math.round(performance.now()-V);if(R)c("error","command.timeout",{...B,durationMs:z,timeoutMs:D});else c(F.ok?"info":"warn","command.end",{...B,durationMs:z,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(A.envelope.command==="client.register"&&F.ok){let L=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(L)J.add(L)}else if(A.envelope.command==="client.unregister"&&F.ok){let T=A.envelope.clientId?.trim();if(T)J.delete(T)}Z({kind:"reply",envelope:F});break}case"stream.subscribe":{let V=`${A.clientId}:${A.sessionId??"*"}`;if(f.has(V))break;let H=await this.transport.subscribe(A.clientId,W,{sessionId:A.sessionId});f.set(V,H);break}case"stream.unsubscribe":{let V=`${A.clientId}:${A.sessionId??"*"}`;f.get(V)?.(),f.delete(V);break}case"reply":case"event":break}}catch(A){let V=typeof Y.data==="string"?$E(Y.data):void 0;if(!V||V.kind!=="command"){c("error","rejected malformed websocket frame",{error:A});return}c("error","command.error",{...F3(V),error:A}),VG(this.telemetry,{component:"core",operation:"hub.websocket_command",error:A,severity:"error",handled:!0,context:F3(V)}),Z({kind:"reply",envelope:HG(V,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},X=()=>{if(Q)return;Q=!0;for(let Y of f.values())Y();f.clear();for(let Y of J)this.transport.command({version:"v1",command:"client.unregister",clientId:Y});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",X)};return $.addEventListener("message",j),$.addEventListener("close",X),X}}class PJ{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function XE($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();return String($)}function YE($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(Q)=>{J({data:XE(Q)})});return}$.on("close",J)},removeEventListener(){}}}function AE($){try{$.write(`HTTP/1.1 400 Bad Request\r
720
+ ${H}`:Y.instructions}})}})}}function Xb($,J,Q,Z){let W=Q.map((j)=>[j.executor,async(...f)=>{let X=f.at(-1),Y=f.slice(0,-1);return(await Z($,j.capabilityName,{executor:j.executor,args:Y,context:PG(X)},J))?.result}]);return W.length>0?Object.fromEntries(W):void 0}function Yb($,J,Q,Z){if(Q.length===0)return;return Q.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema,lifecycle:W.lifecycle,async execute(j,f){return(await Z($,W.capabilityName,{toolName:W.name,input:j,context:PG(f)},J,f.emitUpdate?(Y)=>{f.emitUpdate?.(Zb(Y))}:void 0))?.result}}))}function Vb($,J,Q,Z){let W=new Map(Q.map((f)=>[f.name,f])),j={};for(let f of Jb){let X=W.get(f);if(!X)continue;j[f]=async(Y)=>{return(await Z($,X.capabilityName,{context:Y},J))?.control}}return Object.keys(j).length>0?j:void 0}function bj($){let J=$.contributions.filter((Y)=>Y.kind==="toolExecutor"),Q=$.contributions.filter((Y)=>Y.kind==="tool"),Z=$.contributions.filter((Y)=>Y.kind==="hook"),W=$.contributions.find((Y)=>Y.kind==="compaction"),j=$.contributions.find((Y)=>Y.kind==="checkpoint"),f=$.contributions.find((Y)=>Y.kind==="mistakeLimit"),X=$.contributions.find((Y)=>Y.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:Xb($.sessionId,$.targetClientId,J,$.requestCapability),localRuntime:{...Z.length>0?{hooks:Vb($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...Q.length>0?{extraTools:Yb($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...W?{compaction:{...$.sessionConfig?.compaction??{},...W.config,compact:async(Y)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(Y)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...f?{onConsecutiveMistakeLimitReached:async(Y)=>{return(await $.requestCapability($.sessionId,f.capabilityName,{context:Y},$.targetClientId))?.result}}:{},...X?{userInstructionService:fb($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var SG="hubCapabilityOwnerClientId";function CG($,J){$[SG]=J}function Hb($){let J=$?.[SG];return typeof J==="string"&&J.trim()?J.trim():void 0}async function yG($,J,Q){let Z=performance.now(),W={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:J.sessionId};c("info","session.create.begin",W);let j=J.payload&&typeof J.payload==="object"?J.payload:{},f=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},X=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,Y=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{};if(typeof X?.mode==="string")f.mode=X.mode;else if(typeof Y.mode==="string")f.mode=Y.mode;if(typeof X?.systemPrompt==="string")f.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")f.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)f.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)f.checkpointEnabled=!0;let V=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},H=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!H)return c("warn","session.create.invalid",{...W,reason:"missing_workspace_root"}),v(J,"invalid_session_create","session.create requires workspaceRoot or cwd");let B=J.clientId?.trim()||"hub-client",A=Ej(Y.clientContributions);if(c("info","session.create.contributions_parsed",{...W,clientId:B,workspaceRoot:H,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:A.length}),A.length>0)CG(f,B);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||NG(),R=wG(Y.configExtensions);c("info","session.create.runtime_build.begin",{...W,sessionId:G,configExtensionCount:R?.length??0});let D=bj({sessionId:G,targetClientId:B,contributions:A,sessionConfig:X,requestCapability:$.requestCapability});c("info","session.create.start_session.begin",{...W,sessionId:G,provider:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),model:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub")});let U=await $.sessionHost.startSession({source:typeof f.source==="string"?f.source:void 0,interactive:f.interactive!==!1,sessionMetadata:Object.keys(f).length>0?f:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Q},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),modelId:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub"),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:void 0),cwd:X?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():H),workspaceRoot:X?.workspaceRoot??H,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof f.teamName==="string"?f.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});c("info","session.create.start_session.end",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z),hasImmediateResult:!!U.result}),i9($,U.sessionId,B,"creator",{interactive:f.interactive!==!1}),c("info","session.create.read_records.begin",{...W,sessionId:U.sessionId});let[F,O]=await Promise.all([a0($,U.sessionId),s0($,U.sessionId)]);if(c("info","session.create.read_records.end",{...W,sessionId:U.sessionId,hasSession:!!F,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Z)}),F)$.publish($.buildEvent("session.created",{session:F,...O?{snapshot:O}:{}},U.sessionId));return c("info","session.create.reply",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z)}),l(J,{session:F,...O?{snapshot:O}:{}})}async function EG($,J,Q){let Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.sessionId==="string"?Z.sessionId.trim():J.sessionId?.trim()||"",j=Z.checkpointRunCount;if(!W)return v(J,"invalid_restore","session.restore requires a session id");let f=Z.restore&&typeof Z.restore==="object"?Z.restore:{},X=f.messages!==!1;if(typeof j!=="number")return v(J,"invalid_restore","checkpointRunCount must be a positive integer");try{let Y=Z.sessionConfig&&typeof Z.sessionConfig==="object"?JSON.parse(JSON.stringify(Z.sessionConfig)):void 0;if(X&&!Y)return v(J,"invalid_restore","sessionConfig is required when restore.messages is true");let V=Z.runtimeOptions&&typeof Z.runtimeOptions==="object"?Z.runtimeOptions:{},H=Z.metadata&&typeof Z.metadata==="object"?JSON.parse(JSON.stringify(Z.metadata)):{};if(typeof Y?.mode==="string")H.mode=Y.mode;else if(typeof V.mode==="string")H.mode=V.mode;if(typeof Y?.systemPrompt==="string")H.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")H.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)H.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)H.checkpointEnabled=!0;let B=Z.modelSelection&&typeof Z.modelSelection==="object"?Z.modelSelection:{},A=J.clientId?.trim()||"hub-client",K=Ej(V.clientContributions);if(K.length>0)CG(H,A);let R=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||NG(),D=wG(V.configExtensions),U=bj({sessionId:R,targetClientId:A,contributions:K,sessionConfig:Y,requestCapability:$.requestCapability}),O=await new y$().restoreCheckpoint({sessionId:W,checkpointRunCount:j,restore:{messages:f.messages,workspace:f.workspace,omitCheckpointMessageFromSession:f.omitCheckpointMessageFromSession===!0},start:Y,cwd:typeof Y?.cwd==="string"&&Y.cwd.trim()||typeof Y?.workspaceRoot==="string"&&Y.workspaceRoot.trim()||void 0,getSession:(P)=>$.sessionHost.getSession(P),readMessages:(P)=>$.sessionHost.readSessionMessages(P),buildStartInput:(P)=>{if(P.restoredCheckpointMetadata)H.checkpoint=P.restoredCheckpointMetadata;let S=typeof Z.workspaceRoot==="string"&&Z.workspaceRoot.trim()?Z.workspaceRoot.trim():typeof Z.cwd==="string"&&Z.cwd.trim()?Z.cwd.trim():P.sourceSession.workspaceRoot||P.sourceSession.cwd;return{source:typeof H.source==="string"?H.source:void 0,interactive:H.interactive!==!1,sessionMetadata:{...H,restoredFromSessionId:W,restoredCheckpointRunCount:j},initialMessages:P.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:D,...U.localRuntime},capabilities:{toolExecutors:U.toolExecutors,requestToolApproval:Q},config:{...Y??{},sessionId:R,providerId:Y?.providerId??(typeof B.provider==="string"?B.provider:P.sourceSession.provider),modelId:Y?.modelId??(typeof B.model==="string"?B.model:P.sourceSession.model),apiKey:Y?.apiKey??(typeof B.apiKey==="string"?B.apiKey:""),cwd:Y?.cwd??P.plan.cwd,workspaceRoot:Y?.workspaceRoot??S,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof H.teamName==="string"?H.teamName:void 0)},toolPolicies:Z.toolPolicies&&typeof Z.toolPolicies==="object"&&!Array.isArray(Z.toolPolicies)?JSON.parse(JSON.stringify(Z.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(P)=>$.sessionHost.startSession(P),getStartedSessionId:(P)=>P.sessionId,readRestoredSession:(P)=>$.sessionHost.getSession(P)});if(!X)return l(J,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return v(J,"restore_failed","Checkpoint restore did not start a session");i9($,T.sessionId,A,"creator",{interactive:H.interactive!==!1});let[L,z]=await Promise.all([a0($,T.sessionId),s0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...z?{snapshot:z}:{}},T.sessionId));return l(J,{session:L,...z?{snapshot:z}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(Y){if(Y instanceof h0)return v(J,Y.code,Y.code==="session_not_found"?`Unknown session: ${W}`:Y.message);return v(J,"restore_failed",Y instanceof Error?Y.message:String(Y))}}async function bG($,J){let Q=k0(J);if(!Q)return v(J,"invalid_session_attach","session.attach requires a session id");i9($,Q,J.clientId?.trim()||"hub-client","participant");let Z=await a0($,Q);if(Z)$.publish($.buildEvent("session.attached",{session:Z},Q));return Z?l(J,{session:Z}):v(J,"session_not_found",`Unknown session: ${Q}`)}async function hG($,J){let Q=k0(J);if(!Q)return v(J,"invalid_session_detach","session.detach requires a session id");let Z=J.clientId?.trim()||"hub-client",[W]=await Promise.all([a0($,Q)]),j=Hb(W?.metadata)??Z,f=$.sessionState.get(Q);if(f){if(f.participants.delete(Z),f.createdByClientId===Z)f.createdByClientId=j;if(f.participants.size===0)$.sessionState.delete(Q)}E$($,(V)=>V.sessionId===Q&&V.targetClientId===Z,`Capability owner client ${Z} detached before request was resolved.`);let[X,Y]=await Promise.all([a0($,Q),s0($,Q)]);return $.publish($.buildEvent("session.detached",X?{session:X,...Y?{snapshot:Y}:{},clientId:Z}:{clientId:Z},Q)),l(J)}async function kG($,J){let Q=k0(J),Z=J.payload?.includeSnapshot===!0,[W,j]=await Promise.all([a0($,Q),Z?s0($,Q):Promise.resolve(void 0)]);return W?l(J,{session:W,...j?{snapshot:j}:{}}):v(J,"session_not_found",`Unknown session: ${Q}`)}async function IG($,J){let Q=k0(J);if(!Q)return v(J,"invalid_session_id","session.messages requires a session id");if(!await a0($,Q))return v(J,"session_not_found",`Unknown session: ${Q}`);let W=await $.sessionHost.readSessionMessages(Q);return l(J,{sessionId:Q,messages:W})}async function xG($,J){let Q=typeof J.payload?.limit==="number"?J.payload.limit:200,W=(await $.sessionHost.listSessions(Q)).map((j)=>p9(j,$.sessionState.get(j.sessionId)));return l(J,{sessions:W})}async function gG($,J){let Q=k0(J),Z=r9(J.payload?.metadata),W=await $.sessionHost.updateSession(Q,{metadata:Z}),[j,f]=await Promise.all([a0($,Q),s0($,Q)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...f?{snapshot:f}:{}},Q));return{version:J.version,requestId:J.requestId,ok:W.updated,payload:{updated:W.updated,session:j,...f?{snapshot:f}:{}}}}async function mG($,J){let Q=k0(J),Z=await $.sessionHost.deleteSession(Q);return $.sessionState.delete(Q),l(J,{deleted:Z})}async function vG($,J){let Q=k0(J),Z=$.sessionHost.pendingPrompts;if(!Z)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.list({sessionId:Q});return l(J,{sessionId:Q,prompts:W})}async function cG($,J){let Q=k0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=typeof J.payload?.prompt==="string"?J.payload.prompt:void 0,j=J.payload?.delivery==="queue"||J.payload?.delivery==="steer"?J.payload.delivery:void 0,f=$.sessionHost.pendingPrompts;if(!f)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await f.update({sessionId:Q,promptId:Z,prompt:W,delivery:j});return l(J,X)}async function uG($,J){let Q=k0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=$.sessionHost.pendingPrompts;if(!W)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await W.delete({sessionId:Q,promptId:Z});return l(J,j)}function dG($){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 Ab=new Set(["skills","workflows","rules","tools","mcp"]);function hj($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function wJ($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="string")throw Error(`settings payload '${J}' must be a string.`);return Q}function Kb($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="boolean")throw Error(`settings payload '${J}' must be a boolean.`);return Q}function lG($){if($===void 0)return{};if(!hj($))throw Error("settings.list payload must be an object.");return{cwd:wJ($,"cwd"),workspaceRoot:wJ($,"workspaceRoot"),availabilityContext:hj($.availabilityContext)?$.availabilityContext:void 0}}function Gb($){if(!hj($))throw Error("settings.toggle payload must be an object.");let{type:J}=$;if(typeof J!=="string"||!Ab.has(J))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...lG($),type:J,id:wJ($,"id"),path:wJ($,"path"),name:wJ($,"name"),enabled:Kb($,"enabled")}}class f4{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=Bb("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new L1({sessionService:new z1(new U1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(J)=>this.publish(J),buildEvent:E2,requestCapability:(J,Q,Z,W,j)=>KG(this.ctx,J,Q,Z,W,j)},this.schedules=new c2({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(J,Q)=>{let Z=J==="schedule.execution.completed"?"schedule.execution_completed":J==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Z)return;this.publish(E2(Z,Q&&typeof Q==="object"?Q:void 0))}}),this.scheduleCommands=new x2(this.schedules),this.settings=$.settingsService??new P$,$.cronOptions)this.cronService=new QJ({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((J)=>{MG(this.ctx,J).catch((Q)=>{Cj("session event handling failed",Q),n9(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Q,severity:"error",handled:!0,context:{eventType:J.type,sessionId:J.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())wj(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(E$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let J=await this.dispatchCommand($);return this.captureFailedReply($,J),J}catch(J){throw n9(this.options.telemetry,{component:"core",operation:"hub.command",error:J,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),J}}async dispatchCommand($){switch($.command){case"client.register":return UG(this.ctx,$);case"client.update":return RG(this.ctx,$);case"client.unregister":return zG(this.ctx,$,(J)=>{this.listeners.delete(J),this.detachClientFromSessions(J)});case"client.list":return LG(this.ctx,$);case"session.create":return await yG(this.ctx,$,(J)=>Nj(this.ctx,J));case"session.restore":return await EG(this.ctx,$,(J)=>Nj(this.ctx,J));case"session.attach":return await bG(this.ctx,$);case"session.detach":return await hG(this.ctx,$);case"session.get":return await kG(this.ctx,$);case"session.messages":return await IG(this.ctx,$);case"session.list":return await xG(this.ctx,$);case"session.update":return await gG(this.ctx,$);case"session.pending_prompts":return await vG(this.ctx,$);case"session.update_pending_prompt":return await cG(this.ctx,$);case"session.remove_pending_prompt":return await uG(this.ctx,$);case"session.delete":return await mG(this.ctx,$);case"session.hook":return await TG(this.ctx,$);case"run.start":case"session.send_input":return await _G(this.ctx,$);case"run.abort":return await OG(this.ctx,$);case"capability.request":return await FG(this.ctx,$);case"approval.respond":return await BG(this.ctx,$);case"capability.respond":return DG(this.ctx,$);case"capability.progress":return GG(this.ctx,$);case"ui.notify":return this.publish(E2("ui.notify",$.payload??{})),l($);case"ui.show_window":return this.publish(E2("ui.show_window",$.payload??{})),l($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let J=await this.scheduleCommands.handleCommand($);if(J.ok){let Q=dG($.command);if(Q)this.publish(E2(Q,J.payload))}return J}}}captureFailedReply($,J){if(J.ok||!J.error||!Fb(J.error.code))return;n9(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(J.error.message),severity:J.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:J.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let J=await this.settings.list(lG($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:J instanceof Error?J.message:String(J)}}}}async handleSettingsToggle($){try{let J=await this.settings.toggle(Gb($.payload));return this.publish(E2("settings.changed",{types:J.changedTypes,snapshot:J.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J.snapshot,changedTypes:J.changedTypes}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:J instanceof Error?J.message:String(J)}}}}subscribe($,J,Q){let Z=this.listeners.get($)??new Set,W={sessionId:Q?.sessionId,listener:J};return Z.add(W),this.listeners.set($,Z),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(W),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[J,Q]of this.sessionState.entries())if(Q.participants.delete($),Q.participants.size===0)this.sessionState.delete(J);E$(this.ctx,(J)=>J.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let J of this.listeners.values())for(let Q of J){if(Q.sessionId&&Q.sessionId!==$.sessionId)continue;try{Q.listener($)}catch(Z){Cj(`listener threw while publishing ${$.event}`,Z),n9(this.options.telemetry,{component:"core",operation:"hub.publish",error:Z,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Fb($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as zb}from"node:crypto";import Lb from"node:http";import _b from"node:net";import{URL as iG}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as nG,HUB_CAPABILITIES as Ob,isHubProtocolCompatible as Tb,MAX_CLIENT_HUB_PROTOCOL_VERSION as aG,MIN_CLIENT_HUB_PROTOCOL_VERSION as sG}from"@cline/shared";import{WebSocketServer as Mb}from"ws";import{captureSdkError as pG,HUB_COMMAND_SLOW_LOG_MS as Db,resolveHubCommandTimeoutMs as Ub,safeJsonParse as Rb}from"@cline/shared";function kj($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function rG($,J,Q){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:J,message:Q}}}class TJ{transport;telemetry;constructor($,J){this.transport=$;this.telemetry=J}attach($){let J=new Map,Q=new Set,Z=!1,W=(Y)=>{try{$.send(JSON.stringify(Y))}catch(V){console.error(`[hub] failed to send websocket frame: ${V instanceof Error?V.stack||V.message:String(V)}`)}},j=(Y)=>{W({kind:"event",envelope:Y})},f=async(Y)=>{try{let V=JSON.parse(Y.data);switch(V.kind){case"command":{let H=performance.now(),B=!1,A=kj(V);c("info","command.start",A);let K=setTimeout(()=>{if(B)return;c("warn","command.slow",{...A,elapsedMs:Math.round(performance.now()-H)})},Db),G=this.transport.command(V.envelope);G.then((T)=>{if(!B)return;c(T.ok?"warn":"error","command.late_end",{...A,elapsedMs:Math.round(performance.now()-H),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!B)return;c("error","command.late_error",{...A,elapsedMs:Math.round(performance.now()-H),error:T})});let R=!1,D,U,F=Ub(V.envelope.command,V.envelope.timeoutMs);try{U=F===null?await G:await Promise.race([G,new Promise((T)=>{D=setTimeout(()=>{R=!0,pG(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${V.envelope.command} did not complete within ${F}ms.`),severity:"error",handled:!0,context:{...A,timeoutMs:F}}),T(rG(V,"hub_command_timeout",`Hub command ${V.envelope.command} did not complete within ${F}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${V.envelope.requestId}.`))},F)})])}catch(T){if(clearTimeout(K),D)clearTimeout(D);throw T}if(B=R,clearTimeout(K),D)clearTimeout(D);let O=Math.round(performance.now()-H);if(R)c("error","command.timeout",{...A,durationMs:O,timeoutMs:F});else c(U.ok?"info":"warn","command.end",{...A,durationMs:O,ok:U.ok,errorCode:U.error?.code,errorMessage:U.error?.message});if(V.envelope.command==="client.register"&&U.ok){let L=(V.envelope.payload??{}).clientId?.trim()||V.envelope.clientId?.trim();if(L)Q.add(L)}else if(V.envelope.command==="client.unregister"&&U.ok){let T=V.envelope.clientId?.trim();if(T)Q.delete(T)}W({kind:"reply",envelope:U});break}case"stream.subscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;if(J.has(H))break;let B=await this.transport.subscribe(V.clientId,j,{sessionId:V.sessionId});J.set(H,B);break}case"stream.unsubscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;J.get(H)?.(),J.delete(H);break}case"reply":case"event":break}}catch(V){let H=typeof Y.data==="string"?Rb(Y.data):void 0;if(!H||H.kind!=="command"){c("error","rejected malformed websocket frame",{error:V});return}c("error","command.error",{...kj(H),error:V}),pG(this.telemetry,{component:"core",operation:"hub.websocket_command",error:V,severity:"error",handled:!0,context:kj(H)}),W({kind:"reply",envelope:rG(H,"command_failed",V instanceof Error?V.message:"Unknown hub error")})}},X=()=>{if(Z)return;Z=!0;for(let Y of J.values())Y();J.clear();for(let Y of Q)this.transport.command({version:"v1",command:"client.unregister",clientId:Y});Q.clear(),$.removeEventListener("message",f),$.removeEventListener("close",X)};return $.addEventListener("message",f),$.addEventListener("close",X),X}}class MJ{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,J,Q){return this.transport.subscribe($,J,Q)}}function qb($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();return String($)}function Pb($){return{send(J){$.send(J)},addEventListener(J,Q){if(J==="message"){$.on("message",(Z)=>{Q({data:qb(Z)})});return}$.on("close",Q)},removeEventListener(){}}}function Nb($){try{$.write(`HTTP/1.1 400 Bad Request\r
711
721
  Connection: close\r
712
722
  Content-Length: 0\r
713
723
  \r
714
- `),$.end()}catch{$.destroy()}}function VE($){try{$.write(`HTTP/1.1 401 Unauthorized\r
724
+ `),$.end()}catch{$.destroy()}}function wb($){try{$.write(`HTTP/1.1 401 Unauthorized\r
715
725
  Connection: close\r
716
726
  Content-Length: 0\r
717
727
  \r
718
- `),$.end()}catch{$.destroy()}}function P3($,f){if(!$||!f)return!1;let J=Buffer.from($,"utf8"),Q=Buffer.from(f,"utf8");return J.length===Q.length&&fE(J,Q)}function PG($,f){let J=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",Z=`Failed to start hub server on ${f.host}:${f.port}${f.pathname}: ${Q}`,W=Error(J?`${Z} (${J})`:Z);if(J)$.code=J,W.code=J;if($ instanceof Error&&$.stack)W.stack=`${W.name}: ${W.message}
719
- Caused by: ${$.stack}`;return W}async function HE($){return await new Promise((f,J)=>{let Q=QE.createServer();Q.once("error",J),Q.listen(0,$,()=>{let Z=Q.address();if(!Z||typeof Z==="string"){Q.close(()=>J(Error("Failed to resolve free port")));return}let W=Z.port;Q.close((j)=>{if(j){J(j);return}f(W)})})})}function BE($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var R3=new Map,RG="cline-hub-auth.",KE=30000;function UG($){return Array.isArray($)?$.join(","):$??""}function DG($){return $===32||$===9}function w9($){let f=UG($).trim(),J="bearer";if(f.length<=6||f.slice(0,6).toLowerCase()!=="bearer"||!DG(f.charCodeAt(6)))return null;let Q=7;while(Q<f.length&&DG(f.charCodeAt(Q)))Q+=1;return f.slice(Q).trim()||null}function GE($){for(let f of UG($).split(",")){let J=f.trim();if(J.startsWith(RG))return J.slice(RG.length).trim()||null}return null}async function RJ($){let f=$.owner??k1(),J=$.host??"127.0.0.1",Q=$.pathname??"/hub",Z=$.port??rf(),W=Z===0?await HE(J):Z,j=W,X=s0(J,W,Q),Y=$6(),A=eJ(),V=new e2($);await V.start();let H=new FJ(new PJ(V),$.telemetry),B=new Set,K=new Date().toISOString(),G={protocolVersion:KG,minClientProtocolVersion:FG,maxClientProtocolVersion:GG,capabilities:ZE,coreVersion:L8.version,buildId:Y,pid:process.pid,startedAt:K},R=new Set,P,F,D=async()=>{if(F)return F;return F=(async()=>{if(P)clearInterval(P),P=void 0;for(let U of R)U.terminate?.();R.clear();for(let U of B)U();if(B.clear(),await new Promise((U,w)=>{T.close((h)=>{if(h){w(h);return}U()})}),await new Promise((U,w)=>{z.close((h)=>{if(h){w(h);return}U()})}),await V.stop(),(await Z0(f.discoveryPath))?.url===X)await C0(f.discoveryPath)})(),F},z=JE.createServer((L,U)=>{if((L.url??"/")==="/health"){let h=JSON.stringify({ok:!0,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,coreVersion:G.coreVersion,host:J,port:j,url:X});U.statusCode=200,U.setHeader("content-type","application/json"),U.end(h);return}if((L.url??"/")==="/status"){if(!P3(w9(L.headers.authorization),A)){U.statusCode=401,U.end("Unauthorized");return}let h=JSON.stringify({hubId:V.getHubId(),...G,authToken:A,host:J,port:j,url:X,updatedAt:new Date().toISOString()});U.statusCode=200,U.setHeader("content-type","application/json"),U.end(h);return}if((L.url??"/")==="/version"){U.statusCode=200,U.setHeader("content-type","application/json"),U.end(JSON.stringify(G));return}if(new BG(L.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&L.method==="POST"){if(!P3(w9(L.headers.authorization),A)){U.statusCode=401,U.end("Unauthorized");return}U.statusCode=202,U.setHeader("content-type","application/json"),U.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{D()});return}U.statusCode=404,U.end("Not found")}),T=new jE({noServer:!0});P=setInterval(()=>{for(let L of R){if(L.isAlive===!1){try{L.terminate?.()}catch{}R.delete(L);continue}L.isAlive=!1;try{L.ping?.()}catch{try{L.terminate?.()}catch{}R.delete(L)}}},KE),z.on("upgrade",(L,U,w)=>{if(new BG(L.url??"/",`http://${J}:${j}`).pathname!==Q){U.destroy();return}if(!P3(GE(L.headers["sec-websocket-protocol"]),A)){VE(U);return}try{T.handleUpgrade(L,U,w,(I)=>{let o=I;o.isAlive=!0,o.on("pong",()=>{o.isAlive=!0}),R.add(o);let V0=H.attach(YE(I));B.add(V0),I.once("close",()=>{R.delete(o),V0(),B.delete(V0)})})}catch{AE(U)}});try{await new Promise((L,U)=>{z.once("error",(w)=>{U(PG(w,{host:J,port:W,pathname:Q}))}),z.listen(W,J,()=>{let w=z.address();if(!w||typeof w==="string"){U(PG(Error("Failed to resolve hub port"),{host:J,port:W,pathname:Q}));return}j=w.port,X=s0(J,j,Q),L()})})}catch(L){if(P)clearInterval(P),P=void 0;throw await V.stop().catch(()=>{return}),L}return await f6(f.discoveryPath,{hubId:V.getHubId(),protocolVersion:KG,minClientProtocolVersion:FG,maxClientProtocolVersion:GG,capabilities:[...G.capabilities],coreVersion:L8.version,buildId:Y,authToken:A,host:J,port:j,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:X,authToken:A,close:D}}async function C9($){let f=$.owner??k1(),J=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",Z=$.port??rf(),W=$.pathname??"/hub",j=s0(Q,Z,W),X=f.discoveryPath,Y=(V)=>{if(!J)Q$(V.url,V.authToken);return V},A=R3.get(X);if(A){let V=await A;if(V.url===j)return Y({server:V,url:V.url,authToken:V.authToken,action:"reuse"})}return await J6(f.discoveryPath,async()=>{let V=await Z0(f.discoveryPath);if(V?.url&&(V.url===j||$.allowPortFallback===!0)){let K=await I1(V.url,{authToken:V.authToken});if(K?.url&&WE(K).compatible&&await A1(K.url,{authToken:V.authToken}))return Y({url:K.url,authToken:V.authToken,action:"reuse"})}if(V?.url)await C0(f.discoveryPath);let B=async(K)=>{let G=RJ({...K,owner:f});R3.set(X,G);try{let R=await G;return Y({server:R,url:R.url,authToken:R.authToken,action:"started"})}catch(R){throw R3.delete(X),R}};try{return await B($)}catch(K){if(!$.allowPortFallback||!BE(K))throw K;return await B({...$,port:0})}})}function _G(){return LG()==="production"?Y1():o0()}function FE($){return LG()!=="production"&&!$}async function RK($){let f=X1({host:$.host,port:$.port,pathname:$.pathname});return await RJ({...$,...f,owner:_G()})}async function DK($){let f=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=X1({host:$.host,port:$.port,pathname:$.pathname});return await C9({...$,...J,allowPortFallback:$.allowPortFallback??FE(f),owner:_G()})}export{f6 as writeHubDiscovery,J6 as withHubStartupLock,A1 as verifyHubConnection,GJ as truncateNotificationBody,ZQ as toHubStatusUrl,Q6 as toHubHealthUrl,PQ as stopLocalHubServerGracefully,RJ as startHubWebSocketServer,RK as startHubServer,nf as spawnDetachedHubServerWithRetry,VQ as spawnDetachedHubServer,hj as sendHubCommand,Y6 as restartLocalHubIfIdleAfterStartupTimeout,Pj as resolveWorkspaceHubOwnerContext,o0 as resolveSharedHubOwnerContext,Y1 as resolveProductionHubOwnerContext,RQ as resolveHubUrl,k1 as resolveHubOwnerContext,X1 as resolveHubEndpointOptions,$6 as resolveHubBuildId,rf as resolveDefaultHubPort,AQ as resolveDefaultHubPathname,YQ as resolveDefaultHubHost,O8 as resolveCompatibleLocalHubUrl,Bj as resolveClineDir,m$ as resolveClineDataDir,z8 as requestHubShutdown,Q$ as rememberRecoverableLocalHubUrl,Z0 as readHubDiscovery,w9 as readBearerToken,I1 as probeHubServer,Ej as probeHubConnection,W6 as prewarmDetachedHubServer,Z$ as normalizeHubWebSocketUrl,GQ as isHubReconnectableTransportError,X6 as isHubCommandTimeoutError,Gj as isDiscoveryFilePresent,C9 as ensureHubWebSocketServer,DK as ensureHubServer,zj as ensureDetachedHubServer,u$ as ensureCompatibleLocalHubUrl,PK as createLocalHubScheduleRuntimeHandlers,Kj as createInMemoryHubOwnerContext,s0 as createHubServerUrl,eJ as createHubAuthToken,E1 as createConfiguredTelemetryService,pf as createConfiguredTelemetryHandle,A6 as connectToHub,C0 as clearHubDiscovery,e0 as NodeHubClient,PJ as NativeHubTransportAdapter,LQ as HubUIClient,O0 as HubTransportError,UQ as HubSessionClient,e2 as HubServerTransport,vf as HubScheduleService,If as HubScheduleCommandService,af as HubCommandError,jQ as DEFAULT_HUB_PORT,XQ as DEFAULT_HUB_PATHNAME,WQ as DEFAULT_HUB_HOST,FJ as BrowserWebSocketHubAdapter};
728
+ `),$.end()}catch{$.destroy()}}function Ij($,J){if(!$||!J)return!1;let Q=Buffer.from($,"utf8"),Z=Buffer.from(J,"utf8");return Q.length===Z.length&&zb(Q,Z)}function oG($,J){let Q=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Z=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",W=`Failed to start hub server on ${J.host}:${J.port}${J.pathname}: ${Z}`,j=Error(Q?`${W} (${Q})`:W);if(Q)$.code=Q,j.code=Q;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
729
+ Caused by: ${$.stack}`;return j}async function Sb($){return await new Promise((J,Q)=>{let Z=_b.createServer();Z.once("error",Q),Z.listen(0,$,()=>{let W=Z.address();if(!W||typeof W==="string"){Z.close(()=>Q(Error("Failed to resolve free port")));return}let j=W.port;Z.close((f)=>{if(f){Q(f);return}J(j)})})})}function Cb($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var xj=new Map,tG="cline-hub-auth.",yb=30000;function $F($){return Array.isArray($)?$.join(","):$??""}function eG($){return $===32||$===9}function c9($){let J=$F($).trim(),Q="bearer";if(J.length<=6||J.slice(0,6).toLowerCase()!=="bearer"||!eG(J.charCodeAt(6)))return null;let Z=7;while(Z<J.length&&eG(J.charCodeAt(Z)))Z+=1;return J.slice(Z).trim()||null}function Eb($){for(let J of $F($).split(",")){let Q=J.trim();if(Q.startsWith(tG))return Q.slice(tG.length).trim()||null}return null}async function qJ($){let J=$.owner??I1(),Q=$.host??"127.0.0.1",Z=$.pathname??"/hub",W=$.port??n2(),j=W===0?await Sb(Q):W,f=j,X=e0(Q,j,Z),Y=Y5(),V=X5(),H=new f4($);await H.start();let B=new TJ(new MJ(H),$.telemetry),A=new Set,K=new Date().toISOString(),G={protocolVersion:nG,minClientProtocolVersion:sG,maxClientProtocolVersion:aG,capabilities:Ob,coreVersion:P4.version,buildId:Y,pid:process.pid,startedAt:K},R=new Set,D,U,F=async()=>{if(U)return U;return U=(async()=>{if(D)clearInterval(D),D=void 0;for(let z of R)z.terminate?.();R.clear();for(let z of A)z();if(A.clear(),await new Promise((z,P)=>{T.close((S)=>{if(S){P(S);return}z()})}),await new Promise((z,P)=>{O.close((S)=>{if(S){P(S);return}z()})}),await H.stop(),(await X0(J.discoveryPath))?.url===X)await C0(J.discoveryPath)})(),U},O=Lb.createServer((L,z)=>{if((L.url??"/")==="/health"){let S=JSON.stringify({ok:!0,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,coreVersion:G.coreVersion,host:Q,port:f,url:X});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(S);return}if((L.url??"/")==="/status"){if(!Ij(c9(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}let S=JSON.stringify({hubId:H.getHubId(),...G,authToken:V,host:Q,port:f,url:X,updatedAt:new Date().toISOString()});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(S);return}if((L.url??"/")==="/version"){z.statusCode=200,z.setHeader("content-type","application/json"),z.end(JSON.stringify(G));return}if(new iG(L.url??"/",`http://${Q}:${f}`).pathname==="/shutdown"&&L.method==="POST"){if(!Ij(c9(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}z.statusCode=202,z.setHeader("content-type","application/json"),z.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{F()});return}z.statusCode=404,z.end("Not found")}),T=new Mb({noServer:!0});D=setInterval(()=>{for(let L of R){if(L.isAlive===!1){try{L.terminate?.()}catch{}R.delete(L);continue}L.isAlive=!1;try{L.ping?.()}catch{try{L.terminate?.()}catch{}R.delete(L)}}},yb),O.on("upgrade",(L,z,P)=>{if(new iG(L.url??"/",`http://${Q}:${f}`).pathname!==Z){z.destroy();return}if(!Ij(Eb(L.headers["sec-websocket-protocol"]),V)){wb(z);return}try{T.handleUpgrade(L,z,P,(b)=>{let u=b;u.isAlive=!0,u.on("pong",()=>{u.isAlive=!0}),R.add(u);let o=B.attach(Pb(b));A.add(o),b.once("close",()=>{R.delete(u),o(),A.delete(o)})})}catch{Nb(z)}});try{await new Promise((L,z)=>{O.once("error",(P)=>{z(oG(P,{host:Q,port:j,pathname:Z}))}),O.listen(j,Q,()=>{let P=O.address();if(!P||typeof P==="string"){z(oG(Error("Failed to resolve hub port"),{host:Q,port:j,pathname:Z}));return}f=P.port,X=e0(Q,f,Z),L()})})}catch(L){if(D)clearInterval(D),D=void 0;throw await H.stop().catch(()=>{return}),L}return await V5(J.discoveryPath,{hubId:H.getHubId(),protocolVersion:nG,minClientProtocolVersion:sG,maxClientProtocolVersion:aG,capabilities:[...G.capabilities],coreVersion:P4.version,buildId:Y,authToken:V,host:Q,port:f,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:Q,port:f,url:X,authToken:V,close:F}}async function u9($){let J=$.owner??I1(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.host??"127.0.0.1",W=$.port??n2(),j=$.pathname??"/hub",f=e0(Z,W,j),X=J.discoveryPath,Y=(H)=>{if(!Q)W$(H.url,H.authToken);return H},V=xj.get(X);if(V){let H=await V;if(H.url===f)return Y({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await H5(J.discoveryPath,async()=>{let H=await X0(J.discoveryPath);if(H?.url&&(H.url===f||$.allowPortFallback===!0)){let K=await x1(H.url,{authToken:H.authToken});if(K?.url&&Tb(K).compatible&&await H1(K.url,{authToken:H.authToken}))return Y({url:K.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await C0(J.discoveryPath);let A=async(K)=>{let G=qJ({...K,owner:J});xj.set(X,G);try{let R=await G;return Y({server:R,url:R.url,authToken:R.authToken,action:"started"})}catch(R){throw xj.delete(X),R}};try{return await A($)}catch(K){if(!$.allowPortFallback||!Cb(K))throw K;return await A({...$,port:0})}})}function QF(){return JF()==="production"?V1():$1()}function bb($){return JF()!=="production"&&!$}async function tK($){let J=Y1({host:$.host,port:$.port,pathname:$.pathname});return await qJ({...$,...J,owner:QF()})}async function eK($){let J=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=Y1({host:$.host,port:$.port,pathname:$.pathname});return await u9({...$,...Q,allowPortFallback:$.allowPortFallback??bb(J),owner:QF()})}export{V5 as writeHubDiscovery,H5 as withHubStartupLock,H1 as verifyHubConnection,OJ as truncateNotificationBody,UZ as toHubStatusUrl,B5 as toHubHealthUrl,SZ as stopLocalHubServerGracefully,qJ as startHubWebSocketServer,tK as startHubServer,a2 as spawnDetachedHubServerWithRetry,TZ as spawnDetachedHubServer,$X as sendHubCommand,D5 as restartLocalHubIfIdleAfterStartupTimeout,If as resolveWorkspaceHubOwnerContext,$1 as resolveSharedHubOwnerContext,V1 as resolveProductionHubOwnerContext,CZ as resolveHubUrl,I1 as resolveHubOwnerContext,Y1 as resolveHubEndpointOptions,Y5 as resolveHubBuildId,n2 as resolveDefaultHubPort,OZ as resolveDefaultHubPathname,_Z as resolveDefaultHubHost,S4 as resolveCompatibleLocalHubUrl,Ef as resolveClineDir,m$ as resolveClineDataDir,w4 as requestHubShutdown,W$ as rememberRecoverableLocalHubUrl,X0 as readHubDiscovery,c9 as readBearerToken,x1 as probeHubServer,ef as probeHubConnection,K5 as prewarmDetachedHubServer,j$ as normalizeHubWebSocketUrl,NZ as isHubReconnectableTransportError,F5 as isHubCommandTimeoutError,hf as isDiscoveryFilePresent,u9 as ensureHubWebSocketServer,eK as ensureHubServer,uf as ensureDetachedHubServer,u$ as ensureCompatibleLocalHubUrl,oK as createLocalHubScheduleRuntimeHandlers,bf as createInMemoryHubOwnerContext,e0 as createHubServerUrl,X5 as createHubAuthToken,b1 as createConfiguredTelemetryService,i2 as createConfiguredTelemetryHandle,U5 as connectToHub,C0 as clearHubDiscovery,J1 as NodeHubClient,MJ as NativeHubTransportAdapter,bZ as HubUIClient,M0 as HubTransportError,EZ as HubSessionClient,f4 as HubServerTransport,c2 as HubScheduleService,x2 as HubScheduleCommandService,s2 as HubCommandError,zZ as DEFAULT_HUB_PORT,LZ as DEFAULT_HUB_PATHNAME,RZ as DEFAULT_HUB_HOST,TJ as BrowserWebSocketHubAdapter};