@cline/core 0.0.45 → 0.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hub/index.js CHANGED
@@ -1,44 +1,44 @@
1
- import{createRequire as wK}from"node:module";var{defineProperty:BW,getOwnPropertyNames:MK}=Object;var v7=Object.prototype.hasOwnProperty;function u7($){return this[$]}var M=($,f,J)=>{var W=MK(f);for(let Z of W)if(!v7.call($,Z)&&Z!=="default")BW($,Z,{get:u7.bind(f,Z),enumerable:!0});if(J){for(let Z of W)if(!v7.call(J,Z)&&Z!=="default")BW(J,Z,{get:u7.bind(f,Z),enumerable:!0});return J}};var yK=($)=>$;function qK($,f){this[$]=yK.bind(null,f)}var w=($,f)=>{for(var J in f)BW($,J,{get:f[J],enumerable:!0,configurable:!0,set:qK.bind(f,J)})};var M1=($,f)=>()=>($&&(f=$($=0)),f);var c7=wK(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as BG}from"@cline/shared";function d($,f,J){$?.capture({event:f,properties:J})}function G4($){if(!$)return;return $.substring(0,KG)}function GG($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function PG($){return typeof $==="string"?$:$.message}function H3($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function X3($){d($,x.CLIENT.EXTENSION_ACTIVATED)}function P4($,f){let J=[...f.vcs_types],W={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:H3(J,new Set(["git"])),has_mercurial:H3(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)W.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)W.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)W.is_remote_workspace=f.is_remote_workspace;d($,x.WORKSPACE.INITIALIZED,W)}function U4($,f,J){d($,x.WORKSPACE.INIT_ERROR,{error_type:GG(f),error_message:G4(PG(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function A3($,f){d($,x.WORKSPACE.PATH_RESOLVED,{...f})}function O$($,f){d($,x.USER.AUTH_STARTED,{provider:f})}function z$($,f){d($,x.USER.AUTH_SUCCEEDED,{provider:f})}function _$($,f,J){d($,x.USER.AUTH_FAILED,{provider:f,errorMessage:G4(J)})}function n$($,f,J){d($,x.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function Y3($,f){d($,x.USER.PROVIDER_CONFIGURED,{provider:f})}function V3($,f){$?.captureRequired(x.USER.TELEMETRY_OPT_OUT,f)}function T$($,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 F4($,f){d($,x.TASK.CREATED,f)}function R4($,f){d($,x.TASK.RESTARTED,f)}function e2($,f){d($,x.TASK.COMPLETED,f)}function wf($,f){d($,x.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function D4($,f){d($,x.TASK.TOKEN_USAGE,f)}function L4($,f,J){d($,x.TASK.MODE_SWITCH,{ulid:f,mode:J})}function O4($,f){d($,x.TASK.TOOL_USED,f)}function z4($,f){d($,x.TASK.SKILL_USED,f)}function _4($,f){d($,x.TASK.DIFF_EDIT_FAILED,f)}function $8($,f){d($,x.TASK.PROVIDER_API_ERROR,{...f,errorMessage:G4(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function B3($,f){d($,x.SDK.TOOL_TIMEOUT,UG(f))}function UG($){let f={};for(let[J,W]of Object.entries($))if(W!==void 0)f[J]=W;return f}function T4($,f,J){d($,x.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function N4($,f,J,W){d($,x.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:G4(W),timestamp:new Date().toISOString()})}function M4($,f,J,W,Z){d($,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:W,isEmpty:Z,timestamp:new Date().toISOString()})}function a$($,f){d($,x.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function y4($,f){d($,x.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function f8($,f){d($,f.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function q4($,f,J,W){d($,x.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}function w4($,f){d($,x.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function S4($,f){d($,x.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var KG=500,x;var L0=M1(()=>{x={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:BG,TOOL_TIMEOUT:"sdk.tool_timeout"}}});import{mkdirSync as FG,readFileSync as RG,statSync as DG,writeFileSync as LG}from"node:fs";import{dirname as OG}from"node:path";import{resolveGlobalSettingsPath as G3}from"@cline/shared/storage";import{z as Sf}from"zod";function h4(){return J8.parse({})}function zG(){C4=void 0}function _G($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function TG($){let f;try{f=RG($,"utf8")}catch{return h4()}try{let J=J8.safeParse(JSON.parse(f));return J.success?J.data:h4()}catch{return h4()}}function NG(){let $=G3(),f=DG($,{throwIfNoEntry:!1}),J=f?.mtimeMs??0,W=f?.size??0,Z=C4;if(Z&&Z.path===$&&Z.mtimeMs===J&&Z.size===W)return Z;let Q=_G(f?TG($):h4());return C4={path:$,mtimeMs:J,size:W,value:Q},C4}function O0(){return NG().value}function N$($,f={}){let J=G3(),W=O0();FG(OG(J),{recursive:!0});let Z=J8.parse($);if(!W.telemetryOptOut&&Z.telemetryOptOut)V3(f.telemetry);LG(J,`${JSON.stringify(Z,null,2)}
2
- `,"utf8"),zG()}function E4(){return O0().telemetryOptOut}function P3($,f={}){N$({...O0(),telemetryOptOut:$},f)}function U3(){return O0().autoUpdateEnabled}function F3($,f={}){N$({...O0(),autoUpdateEnabled:$},f)}function W$($){return new Set($??O0().disabledTools??[])}function W8($){return new Set($??O0().disabledPlugins??[])}function R3($){return W$().has($)}function b4($){let f=O0(),J=new Set(f.disabledTools??[]),W=J.has($);if(W)J.delete($);else J.add($);return N$({...f,disabledTools:[...J]}),!W}function NW($,f){let J=[...new Set($.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=O0(),Z=W$(W.disabledTools);for(let Q of J)if(f)Z.add(Q);else Z.delete(Q);N$({...W,disabledTools:[...Z]})}function D3($,f){return NW([$],f),f}function L3($){return W8().has($)}function O3($,f){let J=$.trim();if(!J)return;let W=O0(),Z=W8(W.disabledPlugins);if(f)Z.add(J);else Z.delete(J);N$({...W,disabledPlugins:[...Z]})}function k4($,f){let J=W8(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W))}function S1($,f){let J=W$(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W.name))}function I4($,f){if(!$||$.length===0)return $;let J=W$(f);if(J.size===0)return $;return $.map((W)=>{if(!W.setup)return W;return{...W,setup:(Z,Q)=>W.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},Q)}})}var K3,J8,C4;var Z$=M1(()=>{L0();K3=Sf.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,Sf.array(Sf.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,W)=>J.localeCompare(W));return f.length>0?f:void 0}),J8=Sf.object({telemetryOptOut:Sf.boolean().default(!1).catch(!1),autoUpdateEnabled:Sf.boolean().default(!0).catch(!0),disabledTools:K3.optional(),disabledPlugins:K3.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 MG,mkdirSync as yG,readFileSync as qG,writeFileSync as wG}from"node:fs";import{resolve as SG}from"node:path";import{resolveSessionDataDir as hG}from"@cline/shared/storage";import{nanoid as CG}from"nanoid";import*as EG from"node-machine-id";function h1($){let f=$?.trim();if(f)return f;let J=IG();if(J)return J;return xG()}function kG(){let $=EG;return $.machineIdSync??$.default?.machineIdSync}function IG(){try{let $=kG();if(!$)return;return $().trim()||void 0}catch{return}}function xG(){let $=hG(),f=SG($,bG);try{if(MG(f)){let W=qG(f,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${CG()}`;try{yG($,{recursive:!0}),wG(f,J,"utf8")}catch{}return J}var bG="machine-id";var x4=()=>{};class Q8{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.counters.get($);if(!Q)Q=this.meter.createCounter($,W?{description:W}:void 0),this.counters.set($,Q);Q.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.histograms.get($);if(!Q)Q=this.meter.createHistogram($,W?{description:W}:void 0),this.histograms.set($,Q);Q.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.buildAttributes(J),j=JSON.stringify(Q),H=this.gaugeValues.get($);if(f===null){if(H){if(H.delete(j),H.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let X=H;if(!X)X=new Map,this.gaugeValues.set($,X);if(!this.gauges.has($)){let A=this.meter.createObservableGauge($,W?{description:W}:void 0);A.addCallback((Y)=>{for(let V of this.snapshotGaugeSeries($))Y.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set($,A)}X.set(j,{value:f,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:W})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,W=0){if(!$)return{};let Z={},Q=100,j=10;for(let[H,X]of Object.entries($)){if(H==="__proto__"||H==="constructor"||H==="prototype")continue;let A=f?`${f}.${H}`:H;if(X===null||X===void 0){Z[A]=String(X);continue}if(Array.isArray(X)){let Y=X.length>Q?X.slice(0,Q):X;try{Z[A]=JSON.stringify(Y)}catch{Z[A]="[UnserializableArray]"}if(X.length>Q)Z[`${A}_truncated`]=!0,Z[`${A}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){Z[A]=X.toISOString();continue}if(X instanceof Error){Z[A]=X.message;continue}if(J.has(X)){Z[A]="[Circular]";continue}if(W>=j){Z[A]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(Z,this.flattenProperties(X,A,J,W+1));continue}if(mG(X)){Z[A]=X;continue}try{Z[A]=JSON.stringify(X)}catch{Z[A]=String(X)}}return Z}}function mG($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class j8{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordHistogram($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordGauge($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:W,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class hf{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new j8({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let W of this.adapters)W.emitRequired($,J)}recordCounter($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,Q,W,Z)}recordHistogram($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,Q,W,Z)}recordGauge($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,Q,W,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var MW=()=>{};import{metrics as gG,trace as vG}from"@opentelemetry/api";import{logs as uG}from"@opentelemetry/api-logs";import{OTLPLogExporter as cG}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as dG}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as lG}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as pG}from"@opentelemetry/resources";import{BatchLogRecordProcessor as rG,ConsoleLogRecordExporter as iG,LoggerProvider as nG}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as aG,MeterProvider as tG,PeriodicExportingMetricReader as z3}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as sG,ConsoleSpanExporter as oG,SimpleSpanProcessor as eG}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as $P}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as fP,ATTR_SERVICE_VERSION as JP}from"@opentelemetry/semantic-conventions";class _3{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 Cf{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=pG({[fP]:$.serviceName??"cline",...$.serviceVersion?{[JP]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)gG.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)uG.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return vG.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new Q8({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new hf({...$,adapters:[f],distinctId:h1($.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=yW(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),Z=f.map((Q)=>QP(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(Z.length===0)return null;return new tG({resource:$,readers:Z})}createTracerProvider($){let f=yW(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let Q of f){let j=ZP(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new $P({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=yW(this.options.logsExporter);if(f.length===0)return null;let J=f.map((W)=>{let Z=WP(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new rG(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new nG({resource:$,processors:J})}}function H8($){let f=new Cf($),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 M$($){if(E4())return{telemetry:new _3($)};if($.enabled!==!0)return{telemetry:new hf({...$,distinctId:h1($.distinctId)})};return H8($)}function Ef($){let{telemetry:f,provider:J}=M$($);return{telemetry:f,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function yW($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function WP($,f){if($==="console")return new iG;if(!f.endpoint)return null;let J=qW(f.endpoint,"/v1/logs");return new cG({url:J,headers:f.headers})}function ZP($,f){if($==="console")return new eG(new oG);if(!f.endpoint)return null;let J=qW(f.endpoint,"/v1/traces");return new sG(new lG({url:J,headers:f.headers}))}function QP($,f){if($==="console")return new z3({exporter:new aG,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=qW(f.endpoint,"/v1/metrics");return new z3({exporter:new dG({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function qW($,f){let J=new URL($),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith(f)?W:`${W}${f}`,J.toString()}var m4=M1(()=>{Z$();x4();MW()});var HH={};w(HH,{normalizeUserMessage:()=>qR,buildInitialUserContent:()=>yR});async function yR($,f,J,W){let Z=wR(f),Q=await hR(J,W);if(Z.length===0&&!Q)return $;let j=[{type:"text",text:$},...Z];if(Q)j.push(...Q);return j}function qR($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let W of f)if(W&&typeof W==="object"&&W.type==="text"){let Z=W.text;if(typeof Z==="string")J.push(Z)}return J.join(`
3
- `)}function wR($){if(!$||$.length===0)return[];let f=[];for(let J of $){let W=SR(J);if(W)f.push(W)}return f}function SR($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let W=J[1],Z=J[2];if(!W||!Z)return;return{type:"image",mediaType:W,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function hR($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all($.map(async(Z)=>{let Q=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:Q,content:j}}catch(j){let H=j instanceof Error?j.message:String(j);return{type:"file",path:Q,content:`Error fetching content: ${H}`}}}));if(W.length===0)return;return W}var tA={};w(tA,{updateMcpServerOAuthState:()=>Af,setMcpServerDisabled:()=>Hf,resolveMcpServerRegistrations:()=>Y$,resolveDefaultMcpSettingsPath:()=>T0,registerMcpServersFromSettingsFile:()=>Yf,normalizeMcpServerOAuthState:()=>O2,loadMcpSettingsFile:()=>jf,listMcpServerOAuthStatuses:()=>bJ,hasMcpSettingsFile:()=>m$,getMcpServerOAuthState:()=>Xf});import{existsSync as ez,mkdirSync as lA,readFileSync as x9,writeFileSync as pA}from"node:fs";import{dirname as rA}from"node:path";import{resolveMcpSettingsPath as $_}from"@cline/shared/storage";import{z as S}from"zod";function I9($){if(!$)return;if($==="http")return"streamableHttp";return $}function T0(){return $_()}function V_($){let f=x9($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let Z=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function aA($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function B_($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function jf($={}){let f=$.filePath??T0(),J=x9(f,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=Y_.safeParse(W);if(!Z.success){let Q=Z.error.issues.map((j)=>{let H=j.path.join(".");return H?`${H}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${Q}`)}return Z.data}function K_($){let f=x9($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let W=J,Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return W}function O2($){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 G_($){if($===void 0)return;let f=m9.safeParse($);if(!f.success)return;return O2(f.data)}function m$($={}){let f=$.filePath??T0();return ez(f)}function Y$($={}){let f=jf($);return Object.entries(f.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata,oauth:W.oauth}))}function Hf($){let f=$.filePath??T0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let W=V_(f),Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let Q={...Z},j=aA(Q,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let H={...j};if($.disabled)H.disabled=!0;else delete H.disabled;B_(Q,J,H),lA(rA(f),{recursive:!0}),pA(f,`${JSON.stringify({...W,mcpServers:Q},null,2)}
4
- `)}function Xf($,f={}){let J=jf(f);if(!Object.hasOwn(J.mcpServers,$))return;return O2(J.mcpServers[$]?.oauth)}function Af($,f,J={}){let W=J.filePath??T0(),Z=K_(W),Q=Z.mcpServers,j=aA(Q,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let H=G_(j.oauth)??{},X=O2(f(H));if(X)j.oauth=X;else delete j.oauth;return lA(rA(W),{recursive:!0}),pA(W,`${JSON.stringify(Z,null,2)}
5
- `,"utf8"),X??{}}function bJ($={}){return Y$($).map((J)=>{let W=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:W,oauthConfigured:W&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,W)=>J.serverName.localeCompare(W.serverName))}async function Yf($,f={}){let J=Y$(f);for(let W of J)await $.registerServer(W);return J}var EJ,iA,m9,f_,J_,W_,Z_,Q_,j_,nA,H_,X_,A_,Y_;var Y5=M1(()=>{EJ=S.record(S.string(),S.string()),iA=S.record(S.string(),S.unknown()),m9=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),f_=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:EJ.optional()}),J_=S.object({type:S.literal("sse"),url:S.string().url(),headers:EJ.optional()}),W_=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:EJ.optional()}),Z_=S.discriminatedUnion("type",[f_,J_,W_]),Q_=S.object({transport:Z_,disabled:S.boolean().optional(),metadata:iA.optional(),oauth:m9.optional()}),j_=S.enum(["stdio","sse","http","streamableHttp"]).optional(),nA=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:j_,disabled:S.boolean().optional(),metadata:iA.optional(),oauth:m9.optional()});H_=nA.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:EJ.optional()}).superRefine(($,f)=>{let J=$.type??I9($.transportType);if(J&&J!=="stdio")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),X_=nA.extend({url:S.string().url(),headers:EJ.optional()}).superRefine(($,f)=>{let J=$.type??I9($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??I9($.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}}),A_=S.union([Q_,H_,X_]),Y_=S.object({mcpServers:S.record(S.string(),A_)}).passthrough()});var LV={};w(LV,{createOpenTelemetryTelemetryService:()=>H8,createConfiguredTelemetryService:()=>M$,createConfiguredTelemetryHandle:()=>Ef,OpenTelemetryProvider:()=>Cf,OpenTelemetryAdapter:()=>Q8});var LQ=M1(()=>{m4()});var qB={};w(qB,{writeHubDiscovery:()=>v4,withHubStartupLock:()=>u4,verifyHubConnection:()=>H$,truncateNotificationBody:()=>f4,toHubHealthUrl:()=>CW,stopLocalHubServerGracefully:()=>lW,startHubWebSocketServer:()=>Z4,startHubServer:()=>MB,spawnDetachedHubServerWithRetry:()=>kf,spawnDetachedHubServer:()=>mW,sendHubCommand:()=>n3,restartLocalHubIfIdleAfterStartupTimeout:()=>l4,resolveWorkspaceHubOwnerContext:()=>I3,resolveSharedHubOwnerContext:()=>G0,resolveHubUrl:()=>pW,resolveHubOwnerContext:()=>w$,resolveHubEndpointOptions:()=>j$,resolveHubBuildId:()=>t$,resolveDefaultHubPort:()=>bf,resolveDefaultHubPathname:()=>xW,resolveDefaultHubHost:()=>IW,resolveCompatibleLocalHubUrl:()=>G8,resolveClineDir:()=>C3,resolveClineDataDir:()=>Y8,requestHubShutdown:()=>K8,rememberRecoverableLocalHubUrl:()=>s$,readHubDiscovery:()=>V0,probeHubServer:()=>Q$,probeHubConnection:()=>i3,prewarmDetachedHubServer:()=>c4,normalizeHubWebSocketUrl:()=>o$,isHubReconnectableTransportError:()=>cW,isHubCommandTimeoutError:()=>d4,isDiscoveryFilePresent:()=>b3,ensureHubWebSocketServer:()=>WW,ensureHubServer:()=>yB,ensureDetachedHubServer:()=>m3,ensureCompatibleLocalHubUrl:()=>b1,createLocalHubScheduleRuntimeHandlers:()=>NB,createInMemoryHubOwnerContext:()=>E3,createHubServerUrl:()=>t0,createHubAuthToken:()=>g4,createConfiguredTelemetryService:()=>M$,createConfiguredTelemetryHandle:()=>Ef,connectToHub:()=>p4,clearHubDiscovery:()=>b0,NodeHubClient:()=>s0,NativeHubTransportAdapter:()=>W4,HubUIClient:()=>nW,HubTransportError:()=>z0,HubSessionClient:()=>iW,HubServerTransport:()=>c2,HubScheduleService:()=>qf,HubScheduleCommandService:()=>Tf,HubCommandError:()=>If,DEFAULT_HUB_PORT:()=>bW,DEFAULT_HUB_PATHNAME:()=>kW,DEFAULT_HUB_HOST:()=>EW,BrowserWebSocketHubAdapter:()=>J4});import{createSessionId as SK}from"@cline/shared";function E0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function d7($,f,J){return{version:$.version,requestId:$.requestId??SK("hubreq_"),ok:!1,error:{code:f,message:J}}}class Tf{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return E0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return E0($,{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 E0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return E0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return E0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return E0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return E0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return E0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return E0($,{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 E0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return E0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return E0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return d7($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return d7($,"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 p2{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of f)if(this.materializeOneOff(W))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)try{if(this.materializeSchedule(W))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as vK}from"node:path";import{buildClineSystemPrompt as uK}from"@cline/shared";import{nowIso as a7}from"@cline/shared/db";var J0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},p$=[J0.READ_FILES,J0.SEARCH_CODEBASE,J0.RUN_COMMANDS,J0.FETCH_WEB_CONTENT,J0.APPLY_PATCH,J0.EDITOR,J0.SKILLS,J0.ASK,J0.SUBMIT_AND_EXIT];var p7={};w(p7,{mergeRulesForSystemPrompt:()=>Mf,loadRulesForSystemPromptFromWatcher:()=>KW,listEnabledRulesFromWatcher:()=>l7,isRuleEnabled:()=>A4,formatRulesForSystemPrompt:()=>Nf});function A4($){return $.disabled!==!0}function Nf($){if($.length===0)return"";return`
1
+ import{createRequire as fP}from"node:module";var{defineProperty:C9,getOwnPropertyNames:sK}=Object;var W3=Object.prototype.hasOwnProperty;function j3(f){return this[f]}var z=(f,$,J)=>{var Q=sK($);for(let Z of Q)if(!W3.call(f,Z)&&Z!=="default")C9(f,Z,{get:j3.bind($,Z),enumerable:!0});if(J){for(let Z of Q)if(!W3.call(J,Z)&&Z!=="default")C9(J,Z,{get:j3.bind($,Z),enumerable:!0});return J}};var oK=(f)=>f;function eK(f,$){this[f]=oK.bind(null,$)}var q=(f,$)=>{for(var J in $)C9(f,J,{get:$[J],enumerable:!0,configurable:!0,set:eK.bind($,J)})};var h$=(f,$)=>()=>(f&&($=f(f=0)),$);var H3=fP(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as xP}from"@cline/shared";function p(f,$,J){f?.capture({event:$,properties:J})}function N4(f){if(!f)return;return f.substring(0,gP)}function mP(f){if(typeof f==="string")return"Error";return f.name?.trim()||f.constructor?.name||"Error"}function vP(f){return typeof f==="string"?f:f.message}function N3(f,$){return f.some((J)=>$.has(J.trim().toLowerCase()))}function q3(f){p(f,m.CLIENT.EXTENSION_ACTIVATED)}function q4(f,$){let J=[...$.vcs_types],Q={root_count:$.root_count,vcs_types:J,is_multi_root:$.root_count>1,has_git:N3(J,new Set(["git"])),has_mercurial:N3(J,new Set(["mercurial","hg"]))};if($.init_duration_ms!==void 0)Q.init_duration_ms=$.init_duration_ms;if($.feature_flag_enabled!==void 0)Q.feature_flag_enabled=$.feature_flag_enabled;if($.is_remote_workspace!==void 0)Q.is_remote_workspace=$.is_remote_workspace;p(f,m.WORKSPACE.INITIALIZED,Q)}function y4(f,$,J){p(f,m.WORKSPACE.INIT_ERROR,{error_type:mP($),error_message:N4(vP($)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function y3(f,$){p(f,m.WORKSPACE.PATH_RESOLVED,{...$})}function Nf(f,$){p(f,m.USER.AUTH_STARTED,{provider:$})}function qf(f,$){p(f,m.USER.AUTH_SUCCEEDED,{provider:$})}function yf(f,$,J){p(f,m.USER.AUTH_FAILED,{provider:$,errorMessage:N4(J)})}function f$(f,$,J){p(f,m.USER.AUTH_LOGGED_OUT,{provider:$,reason:J})}function w3(f,$){p(f,m.USER.PROVIDER_CONFIGURED,{provider:$})}function C3(f,$){f?.captureRequired(m.USER.TELEMETRY_OPT_OUT,$)}function wf(f,$){let J=$.id?.trim();if(J)f?.setDistinctId(J);f?.updateCommonProperties({account_id:$.id,account_email:$.email,provider:$.provider,organization_id:$.organizationId,organization_name:$.organizationName,member_id:$.memberId})}function w4(f,$){p(f,m.TASK.CREATED,$)}function C4(f,$){p(f,m.TASK.RESTARTED,$)}function W8(f,$){p(f,m.TASK.COMPLETED,$)}function g1(f,$){p(f,m.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function S4(f,$){p(f,m.TASK.TOKEN_USAGE,$)}function E4(f,$,J){p(f,m.TASK.MODE_SWITCH,{ulid:$,mode:J})}function h4(f,$){p(f,m.TASK.TOOL_USED,$)}function b4(f,$){p(f,m.TASK.SKILL_USED,$)}function k4(f,$){p(f,m.TASK.DIFF_EDIT_FAILED,$)}function j8(f,$){p(f,m.TASK.PROVIDER_API_ERROR,{...$,errorMessage:N4($.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function S3(f,$){p(f,m.SDK.TOOL_TIMEOUT,cP($))}function cP(f){let $={};for(let[J,Q]of Object.entries(f))if(Q!==void 0)$[J]=Q;return $}function I4(f,$,J){p(f,m.TASK.MENTION_USED,{mentionType:$,contentLength:J,timestamp:new Date().toISOString()})}function x4(f,$,J,Q){p(f,m.TASK.MENTION_FAILED,{mentionType:$,errorType:J,errorMessage:N4(Q),timestamp:new Date().toISOString()})}function g4(f,$,J,Q,Z){p(f,m.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:J,searchType:Q,isEmpty:Z,timestamp:new Date().toISOString()})}function $$(f,$){p(f,m.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function m4(f,$){p(f,m.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function H8(f,$){p(f,$.event==="ended"?m.TASK.SUBAGENT_COMPLETED:m.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function v4(f,$,J,Q){p(f,m.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:J,workspaceCount:Q,totalCount:J+Q,timestamp:new Date().toISOString()})}function c4(f,$){p(f,m.TASK.COMPACTION_EXECUTED,{...$,timestamp:new Date().toISOString()})}function u4(f,$){p(f,m.TASK.COMPACTION_SKIPPED,{...$,timestamp:new Date().toISOString()})}var gP=500,m;var O0=h$(()=>{m={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:xP,TOOL_TIMEOUT:"sdk.tool_timeout"}}});import{mkdirSync as uP,readFileSync as dP,statSync as lP,writeFileSync as pP}from"node:fs";import{dirname as rP}from"node:path";import{resolveGlobalSettingsPath as h3}from"@cline/shared/storage";import{z as m1}from"zod";function d4(){return X8.parse({})}function iP(){l4=void 0}function nP(f){if(f.disabledTools)Object.freeze(f.disabledTools);if(f.disabledPlugins)Object.freeze(f.disabledPlugins);return Object.freeze(f)}function aP(f){let $;try{$=dP(f,"utf8")}catch{return d4()}try{let J=X8.safeParse(JSON.parse($));return J.success?J.data:d4()}catch{return d4()}}function tP(){let f=h3(),$=lP(f,{throwIfNoEntry:!1}),J=$?.mtimeMs??0,Q=$?.size??0,Z=l4;if(Z&&Z.path===f&&Z.mtimeMs===J&&Z.size===Q)return Z;let W=nP($?aP(f):d4());return l4={path:f,mtimeMs:J,size:Q,value:W},l4}function _0(){return tP().value}function Cf(f,$={}){let J=h3(),Q=_0();uP(rP(J),{recursive:!0});let Z=X8.parse(f);if(!Q.telemetryOptOut&&Z.telemetryOptOut)C3($.telemetry);pP(J,`${JSON.stringify(Z,null,2)}
2
+ `,"utf8"),iP()}function p4(){return _0().telemetryOptOut}function b3(f,$={}){Cf({..._0(),telemetryOptOut:f},$)}function k3(){return _0().autoUpdateEnabled}function I3(f,$={}){Cf({..._0(),autoUpdateEnabled:f},$)}function Wf(f){return new Set(f??_0().disabledTools??[])}function A8(f){return new Set(f??_0().disabledPlugins??[])}function x3(f){return Wf().has(f)}function r4(f){let $=_0(),J=new Set($.disabledTools??[]),Q=J.has(f);if(Q)J.delete(f);else J.add(f);return Cf({...$,disabledTools:[...J]}),!Q}function d9(f,$){let J=[...new Set(f.map((W)=>W.trim()).filter(Boolean))];if(J.length===0)return;let Q=_0(),Z=Wf(Q.disabledTools);for(let W of J)if($)Z.add(W);else Z.delete(W);Cf({...Q,disabledTools:[...Z]})}function g3(f,$){return d9([f],$),$}function m3(f){return A8().has(f)}function v3(f,$){let J=f.trim();if(!J)return;let Q=_0(),Z=A8(Q.disabledPlugins);if($)Z.add(J);else Z.delete(J);Cf({...Q,disabledPlugins:[...Z]})}function i4(f,$){let J=A8($);if(J.size===0)return[...f];return f.filter((Q)=>!J.has(Q))}function x$(f,$){let J=Wf($);if(J.size===0)return[...f];return f.filter((Q)=>!J.has(Q.name))}function n4(f,$){if(!f||f.length===0)return f;let J=Wf($);if(J.size===0)return f;return f.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(Z,W)=>Q.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},W)}})}var E3,X8,l4;var jf=h$(()=>{O0();E3=m1.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,m1.array(m1.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,Q)=>J.localeCompare(Q));return $.length>0?$:void 0}),X8=m1.object({telemetryOptOut:m1.boolean().default(!1).catch(!1),autoUpdateEnabled:m1.boolean().default(!0).catch(!0),disabledTools:E3.optional(),disabledPlugins:E3.optional()}).strip().transform((f)=>{let $={autoUpdateEnabled:f.autoUpdateEnabled,telemetryOptOut:f.telemetryOptOut};if(f.disabledTools?.length)$.disabledTools=f.disabledTools;if(f.disabledPlugins?.length)$.disabledPlugins=f.disabledPlugins;return $})});import{existsSync as sP,mkdirSync as oP,readFileSync as eP,writeFileSync as fG}from"node:fs";import{resolve as $G}from"node:path";import{resolveSessionDataDir as JG}from"@cline/shared/storage";import{nanoid as QG}from"nanoid";import*as ZG from"node-machine-id";function g$(f){let $=f?.trim();if($)return $;let J=HG();if(J)return J;return XG()}function jG(){let f=ZG;return f.machineIdSync??f.default?.machineIdSync}function HG(){try{let f=jG();if(!f)return;return f().trim()||void 0}catch{return}}function XG(){let f=JG(),$=$G(f,WG);try{if(sP($)){let Q=eP($,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${QG()}`;try{oP(f,{recursive:!0}),fG($,J,"utf8")}catch{}return J}var WG="machine-id";var a4=()=>{};class V8{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(f){this.name=f.name??"OpenTelemetryAdapter",this.metadata={...f.metadata},this.meterProvider=f.meterProvider,this.loggerProvider=f.loggerProvider,this.meter=f.meterProvider?.getMeter("cline")??null,this.logger=f.loggerProvider?.getLogger("cline")??null,this.enabled=f.enabled??!0,this.distinctId=f.distinctId,this.commonProperties=f.commonProperties?{...f.commonProperties}:{}}emit(f,$){if(!this.isEnabled())return;this.emitLog(f,$,!1)}emitRequired(f,$){this.emitLog(f,$,!0)}recordCounter(f,$,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.counters.get(f);if(!W)W=this.meter.createCounter(f,Q?{description:Q}:void 0),this.counters.set(f,W);W.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get(f);if(!W)W=this.meter.createHistogram(f,Q?{description:Q}:void 0),this.histograms.set(f,W);W.record($,this.flattenProperties(this.buildAttributes(J)))}recordGauge(f,$,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.buildAttributes(J),j=JSON.stringify(W),H=this.gaugeValues.get(f);if($===null){if(H){if(H.delete(j),H.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let X=H;if(!X)X=new Map,this.gaugeValues.set(f,X);if(!this.gauges.has(f)){let A=this.meter.createObservableGauge(f,Q?{description:Q}:void 0);A.addCallback((Y)=>{for(let V of this.snapshotGaugeSeries(f))Y.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set(f,A)}X.set(j,{value:$,attributes:W})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(f){this.distinctId=f}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(f,$,J){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes($,J));this.logger.emit({severityText:"INFO",body:f,attributes:Q})}buildAttributes(f,$=!1){return{...this.commonProperties,...this.metadata,...f,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(f){let $=this.gaugeValues.get(f);if(!$)return[];return Array.from($.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties(f,$="",J=new WeakSet,Q=0){if(!f)return{};let Z={},W=100,j=10;for(let[H,X]of Object.entries(f)){if(H==="__proto__"||H==="constructor"||H==="prototype")continue;let A=$?`${$}.${H}`:H;if(X===null||X===void 0){Z[A]=String(X);continue}if(Array.isArray(X)){let Y=X.length>W?X.slice(0,W):X;try{Z[A]=JSON.stringify(Y)}catch{Z[A]="[UnserializableArray]"}if(X.length>W)Z[`${A}_truncated`]=!0,Z[`${A}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){Z[A]=X.toISOString();continue}if(X instanceof Error){Z[A]=X.message;continue}if(J.has(X)){Z[A]="[Circular]";continue}if(Q>=j){Z[A]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(Z,this.flattenProperties(X,A,J,Q+1));continue}if(AG(X)){Z[A]=X;continue}try{Z[A]=JSON.stringify(X)}catch{Z[A]=String(X)}}return Z}}function AG(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class B8{name;logger;enabled;constructor(f={}){this.name=f.name??"TelemetryLoggerSink",this.logger=f.logger,this.enabled=f.enabled??!0}emit(f,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:f,properties:$})}emitRequired(f,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:f,properties:$})}recordCounter(f,$,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,attributes:J,description:Q,required:Z===!0})}recordHistogram(f,$,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:f,value:$,attributes:J,description:Q,required:Z===!0})}recordGauge(f,$,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:f,value:$,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class v1{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new B8({logger:f.logger}));this.metadata={...f.metadata??{}},this.distinctId=f.distinctId,this.commonProperties={...f.commonProperties??{}}}addAdapter(f){this.adapters.push(f)}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return this.adapters.some((f)=>f.isEnabled())}capture(f){let $=this.buildAttributes(f.properties);for(let J of this.adapters)J.emit(f.event,$)}captureRequired(f,$){let J=this.buildAttributes($);for(let Q of this.adapters)Q.emitRequired(f,J)}recordCounter(f,$,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter(f,$,W,Q,Z)}recordHistogram(f,$,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram(f,$,W,Q,Z)}recordGauge(f,$,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge(f,$,W,Q,Z)}async flush(){await Promise.all(this.adapters.map((f)=>f.flush()))}async dispose(){await Promise.all(this.adapters.map((f)=>f.dispose()))}buildAttributes(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var l9=()=>{};import{metrics as YG,trace as VG}from"@opentelemetry/api";import{logs as BG}from"@opentelemetry/api-logs";import{OTLPLogExporter as KG}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as PG}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as GG}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as FG}from"@opentelemetry/resources";import{BatchLogRecordProcessor as UG,ConsoleLogRecordExporter as RG,LoggerProvider as DG}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as LG,MeterProvider as OG,PeriodicExportingMetricReader as c3}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as _G,ConsoleSpanExporter as TG,SimpleSpanProcessor as zG}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as MG}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as NG,ATTR_SERVICE_VERSION as qG}from"@opentelemetry/semantic-conventions";class u3{distinctId;metadata;commonProperties;constructor(f={}){this.distinctId=f.distinctId,this.metadata={...f.metadata??{}},this.commonProperties={...f.commonProperties??{}}}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return!1}capture(f){this.resolveProperties(f.properties)}captureRequired(f,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class c1{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=FG({[NG]:f.serviceName??"cline",...f.serviceVersion?{[qG]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)YG.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)BG.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return VG.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new V8({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new v1({...f,adapters:[$],distinctId:g$(f.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(f){let $=p9(this.options.metricsExporter);if($.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(J*0.8)),Z=$.map((W)=>CG(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 OG({resource:f,readers:Z})}createTracerProvider(f){let $=p9(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of $){let j=wG(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 MG({resource:f,spanProcessors:Z})}createLoggerProvider(f){let $=p9(this.options.logsExporter);if($.length===0)return null;let J=$.map((Q)=>{let Z=yG(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new UG(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 DG({resource:f,processors:J})}}function K8(f){let $=new c1(f),J=$.createTelemetryService(f);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:f.enabled??!0,logsExporter:Array.isArray(f.logsExporter)?f.logsExporter.join(","):f.logsExporter,metricsExporter:Array.isArray(f.metricsExporter)?f.metricsExporter.join(","):f.metricsExporter,tracesExporter:Array.isArray(f.tracesExporter)?f.tracesExporter.join(","):f.tracesExporter,otlpProtocol:f.otlpProtocol,hasOtlpEndpoint:Boolean(f.otlpEndpoint),serviceName:f.serviceName,serviceVersion:f.serviceVersion}),{provider:$,telemetry:J}}function Sf(f){if(p4())return{telemetry:new u3(f)};if(f.enabled!==!0)return{telemetry:new v1({...f,distinctId:g$(f.distinctId)})};return K8(f)}function u1(f){let{telemetry:$,provider:J}=Sf(f);return{telemetry:$,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function p9(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function yG(f,$){if(f==="console")return new RG;if(!$.endpoint)return null;let J=r9($.endpoint,"/v1/logs");return new KG({url:J,headers:$.headers})}function wG(f,$){if(f==="console")return new zG(new TG);if(!$.endpoint)return null;let J=r9($.endpoint,"/v1/traces");return new _G(new GG({url:J,headers:$.headers}))}function CG(f,$){if(f==="console")return new c3({exporter:new LG,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=r9($.endpoint,"/v1/metrics");return new c3({exporter:new PG({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function r9(f,$){let J=new URL(f),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith($)?Q:`${Q}${$}`,J.toString()}var t4=h$(()=>{jf();a4();l9()});var fX={};q(fX,{normalizeUserMessage:()=>mD,buildInitialUserContent:()=>gD});async function gD(f,$,J,Q){let Z=vD($),W=await uD(J,Q);if(Z.length===0&&!W)return f;let j=[{type:"text",text:f},...Z];if(W)j.push(...W);return j}function mD(f){if(f==null)return"";if(typeof f==="string")return f;let $=f.content;if(typeof $==="string")return $;if(!Array.isArray($))return"";let J=[];for(let Q of $)if(Q&&typeof Q==="object"&&Q.type==="text"){let Z=Q.text;if(typeof Z==="string")J.push(Z)}return J.join(`
3
+ `)}function vD(f){if(!f||f.length===0)return[];let $=[];for(let J of f){let Q=cD(J);if(Q)$.push(Q)}return $}function cD(f){let $=f.trim();if(!$)return;let J=$.match(/^data:([^;,]+);base64,(.+)$/);if(J){let Q=J[1],Z=J[2];if(!Q||!Z)return;return{type:"image",mediaType:Q,data:Z}}return{type:"image",mediaType:"image/png",data:$}}async function uD(f,$){if(!f||f.length===0)return;let J=$??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all(f.map(async(Z)=>{let W=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:W,content:j}}catch(j){let H=j instanceof Error?j.message:String(j);return{type:"file",path:W,content:`Error fetching content: ${H}`}}}));if(Q.length===0)return;return Q}var GY={};q(GY,{updateMcpServerOAuthState:()=>U1,setMcpServerDisabled:()=>G1,resolveMcpServerRegistrations:()=>Bf,resolveDefaultMcpSettingsPath:()=>M0,registerMcpServersFromSettingsFile:()=>R1,normalizeMcpServerOAuthState:()=>N2,loadMcpSettingsFile:()=>P1,listMcpServerOAuthStatuses:()=>cJ,hasMcpSettingsFile:()=>df,getMcpServerOAuthState:()=>F1});import{existsSync as bT,mkdirSync as AY,readFileSync as fW,writeFileSync as YY}from"node:fs";import{dirname as VY}from"node:path";import{resolveMcpSettingsPath as kT}from"@cline/shared/storage";import{z as C}from"zod";function eZ(f){if(!f)return;if(f==="http")return"streamableHttp";return f}function M0(){return kT()}function rT(f){let $=fW(f,"utf8"),J;try{J=JSON.parse($)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${f}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${f}": expected object.`);return J}function PY(f,$){if(!Object.hasOwn(f,$))return;let J=f[$];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function iT(f,$,J){Object.defineProperty(f,$,{value:J,enumerable:!0,configurable:!0,writable:!0})}function P1(f={}){let $=f.filePath??M0(),J=fW($,"utf8"),Q;try{Q=JSON.parse(J)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}let Z=pT.safeParse(Q);if(!Z.success){let W=Z.error.issues.map((j)=>{let H=j.path.join(".");return H?`${H}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${$}": ${W}`)}return Z.data}function nT(f){let $=fW(f,"utf8"),J;try{J=JSON.parse($)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${f}": expected object`);let Q=J,Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object`);return Q}function N2(f){if(!f)return;let $={...f.clientInformation?{clientInformation:f.clientInformation}:{},...f.tokens?{tokens:f.tokens}:{},...f.codeVerifier?{codeVerifier:f.codeVerifier}:{},...f.discoveryState?{discoveryState:f.discoveryState}:{},...f.redirectUrl?{redirectUrl:f.redirectUrl}:{},...f.lastError?{lastError:f.lastError}:{},...f.lastAuthenticatedAt?{lastAuthenticatedAt:f.lastAuthenticatedAt}:{}};return Object.keys($).length>0?$:void 0}function aT(f){if(f===void 0)return;let $=$W.safeParse(f);if(!$.success)return;return N2($.data)}function df(f={}){let $=f.filePath??M0();return bT($)}function Bf(f={}){let $=P1(f);return Object.entries($.mcpServers).map(([J,Q])=>({name:J,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function G1(f){let $=f.filePath??M0(),J=f.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=rT($),Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object.`);let W={...Z},j=PY(W,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let H={...j};if(f.disabled)H.disabled=!0;else delete H.disabled;iT(W,J,H),AY(VY($),{recursive:!0}),YY($,`${JSON.stringify({...Q,mcpServers:W},null,2)}
4
+ `)}function F1(f,$={}){let J=P1($);if(!Object.hasOwn(J.mcpServers,f))return;return N2(J.mcpServers[f]?.oauth)}function U1(f,$,J={}){let Q=J.filePath??M0(),Z=nT(Q),W=Z.mcpServers,j=PY(W,f);if(!j)throw Error(`Unknown MCP server: ${f}`);let H=aT(j.oauth)??{},X=N2($(H));if(X)j.oauth=X;else delete j.oauth;return AY(VY(Q),{recursive:!0}),YY(Q,`${JSON.stringify(Z,null,2)}
5
+ `,"utf8"),X??{}}function cJ(f={}){return Bf(f).map((J)=>{let Q=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:Q,oauthConfigured:Q&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,Q)=>J.serverName.localeCompare(Q.serverName))}async function R1(f,$={}){let J=Bf($);for(let Q of J)await f.registerServer(Q);return J}var vJ,BY,$W,IT,xT,gT,mT,vT,cT,KY,uT,dT,lT,pT;var N5=h$(()=>{vJ=C.record(C.string(),C.string()),BY=C.record(C.string(),C.unknown()),$W=C.object({clientInformation:C.record(C.string(),C.unknown()).optional(),tokens:C.record(C.string(),C.unknown()).optional(),codeVerifier:C.string().optional(),discoveryState:C.record(C.string(),C.unknown()).optional(),redirectUrl:C.string().url().optional(),lastError:C.string().optional(),lastAuthenticatedAt:C.number().int().positive().optional()}).strip(),IT=C.object({type:C.literal("stdio"),command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:vJ.optional()}),xT=C.object({type:C.literal("sse"),url:C.string().url(),headers:vJ.optional()}),gT=C.object({type:C.literal("streamableHttp"),url:C.string().url(),headers:vJ.optional()}),mT=C.discriminatedUnion("type",[IT,xT,gT]),vT=C.object({transport:mT,disabled:C.boolean().optional(),metadata:BY.optional(),oauth:$W.optional()}),cT=C.enum(["stdio","sse","http","streamableHttp"]).optional(),KY=C.object({type:C.enum(["stdio","sse","streamableHttp"]).optional(),transportType:cT,disabled:C.boolean().optional(),metadata:BY.optional(),oauth:$W.optional()});uT=KY.extend({command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:vJ.optional()}).superRefine((f,$)=>{let J=f.type??eZ(f.transportType);if(J&&J!=="stdio")$.addIssue({code:C.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((f)=>({transport:{type:"stdio",command:f.command,args:f.args,cwd:f.cwd,env:f.env},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth})),dT=KY.extend({url:C.string().url(),headers:vJ.optional()}).superRefine((f,$)=>{let J=f.type??eZ(f.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")$.addIssue({code:C.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((f)=>{if((f.type??eZ(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth}}),lT=C.union([vT,uT,dT]),pT=C.object({mcpServers:C.record(C.string(),lT)}).passthrough()});var lV={};q(lV,{createOpenTelemetryTelemetryService:()=>K8,createConfiguredTelemetryService:()=>Sf,createConfiguredTelemetryHandle:()=>u1,OpenTelemetryProvider:()=>c1,OpenTelemetryAdapter:()=>V8});var gW=h$(()=>{t4()});var sB={};q(sB,{writeHubDiscovery:()=>o4,withHubStartupLock:()=>e4,verifyHubConnection:()=>Af,truncateNotificationBody:()=>V4,toHubHealthUrl:()=>t9,stopLocalHubServerGracefully:()=>XQ,startHubWebSocketServer:()=>P4,startHubServer:()=>aB,spawnDetachedHubServerWithRetry:()=>l1,spawnDetachedHubServer:()=>JQ,sendHubCommand:()=>Kj,restartLocalHubIfIdleAfterStartupTimeout:()=>J6,resolveWorkspaceHubOwnerContext:()=>$j,resolveSharedHubOwnerContext:()=>F0,resolveHubUrl:()=>AQ,resolveHubOwnerContext:()=>bf,resolveHubEndpointOptions:()=>Xf,resolveHubBuildId:()=>J$,resolveDefaultHubPort:()=>d1,resolveDefaultHubPathname:()=>$Q,resolveDefaultHubHost:()=>fQ,resolveCompatibleLocalHubUrl:()=>L8,resolveClineDir:()=>s3,resolveClineDataDir:()=>F8,requestHubShutdown:()=>D8,rememberRecoverableLocalHubUrl:()=>Q$,readHubDiscovery:()=>V0,probeHubServer:()=>Hf,probeHubConnection:()=>Bj,prewarmDetachedHubServer:()=>f6,normalizeHubWebSocketUrl:()=>Z$,isHubReconnectableTransportError:()=>jQ,isHubCommandTimeoutError:()=>$6,isDiscoveryFilePresent:()=>e3,ensureHubWebSocketServer:()=>O9,ensureHubServer:()=>tB,ensureDetachedHubServer:()=>Qj,ensureCompatibleLocalHubUrl:()=>c$,createLocalHubScheduleRuntimeHandlers:()=>nB,createInMemoryHubOwnerContext:()=>o3,createHubServerUrl:()=>o0,createHubAuthToken:()=>s4,createConfiguredTelemetryService:()=>Sf,createConfiguredTelemetryHandle:()=>u1,connectToHub:()=>Q6,clearHubDiscovery:()=>x0,NodeHubClient:()=>e0,NativeHubTransportAdapter:()=>K4,HubUIClient:()=>BQ,HubTransportError:()=>T0,HubSessionClient:()=>VQ,HubServerTransport:()=>a2,HubScheduleService:()=>x1,HubScheduleCommandService:()=>h1,HubCommandError:()=>p1,DEFAULT_HUB_PORT:()=>o9,DEFAULT_HUB_PATHNAME:()=>e9,DEFAULT_HUB_HOST:()=>s9,BrowserWebSocketHubAdapter:()=>B4});import{createSessionId as $P}from"@cline/shared";function I0(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function X3(f,$,J){return{version:f.version,requestId:f.requestId??$P("hubreq_"),ok:!1,error:{code:$,message:J}}}class h1{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return I0(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return I0(f,{schedules:this.schedules.listSchedules({enabled:typeof f.payload?.enabled==="boolean"?f.payload.enabled:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0,tags:Array.isArray(f.payload?.tags)?f.payload?.tags:void 0})});case"schedule.get":return I0(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return I0(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return I0(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return I0(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return I0(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return I0(f,{execution:f.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String(f.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return I0(f,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof f.payload?.scheduleId==="string"?f.payload.scheduleId:void 0,status:typeof f.payload?.status==="string"?f.payload.status:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0})});case"schedule.stats":return I0(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return I0(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return I0(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return X3(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return X3(f,"schedule_command_failed",$ instanceof Error?$.message:String($))}}toCreateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider&&f.model?{providerId:String(f.provider),modelId:String(f.model)}:void 0;return{...f,modelSelection:$}}toUpdateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider||f.model?{providerId:typeof f.provider==="string"?f.provider:"",modelId:typeof f.model==="string"?f.model:""}:void 0;return{...f,modelSelection:$}}}class s2{store;nowFn;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now())}materializeAll(){let f={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of $)if(this.materializeOneOff(Q))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of J)try{if(this.materializeSchedule(Q))f.scheduleQueued+=1}catch{}return f}materializeOneOff(f){if(f.triggerKind!=="one_off")return!1;if(!f.enabled||f.removed)return!1;if(this.store.hasOneOffRunForRevision(f.specId,f.revision))return!1;return this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(f){if(f.triggerKind!=="schedule")return!1;if(!f.enabled||f.removed)return!1;if(!f.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:f.specId,nowMs:this.nowFn()}).queued}}import{basename as VP}from"node:path";import{buildClineSystemPrompt as BP}from"@cline/shared";import{nowIso as P3}from"@cline/shared/db";var Y0={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"},sf=[Y0.READ_FILES,Y0.SEARCH_CODEBASE,Y0.RUN_COMMANDS,Y0.FETCH_WEB_CONTENT,Y0.APPLY_PATCH,Y0.EDITOR,Y0.SKILLS,Y0.ASK,Y0.SUBMIT_AND_EXIT];var Y3={};q(Y3,{mergeRulesForSystemPrompt:()=>k1,loadRulesForSystemPromptFromWatcher:()=>S9,listEnabledRulesFromWatcher:()=>A3,isRuleEnabled:()=>O4,formatRulesForSystemPrompt:()=>b1});function O4(f){return f.disabled!==!0}function b1(f){if(f.length===0)return"";return`
6
6
 
7
7
  # Rules
8
- ${$.map((J)=>`## ${J.name}
8
+ ${f.map((J)=>`## ${J.name}
9
9
  ${J.instructions}`).join(`
10
10
 
11
- `)}`}function Mf($,f){let J=$?.trim(),W=f?.trim();if(J&&W)return`${J}
11
+ `)}`}function k1(f,$){let J=f?.trim(),Q=$?.trim();if(J&&Q)return`${J}
12
12
 
13
- ${W}`;return J||W||void 0}function l7($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(A4).sort((J,W)=>J.name.localeCompare(W.name))}function KW($){return Nf(l7($))}var n7={};w(n7,{normalizeWorkspacePath:()=>L$,generateWorkspaceInfoWithDiagnostics:()=>r2,generateWorkspaceInfo:()=>yf,buildWorkspaceMetadataWithInfo:()=>GW,buildWorkspaceMetadata:()=>i2});import{basename as hK,resolve as CK}from"node:path";import{performance as r7}from"node:perf_hooks";import{processWorkspaceInfo as i7}from"@cline/shared";import EK from"simple-git";function L$($){return CK($)}async function yf($){return(await r2($)).info}function Y4($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function r2($){let f=L$($),J={rootPath:f,hint:hK(f)},W;try{let Z=EK({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let H=j.map((X)=>{let A=X.refs.fetch||X.refs.push;return`${X.name}: ${A}`});J.associatedRemoteUrls=H}}catch(j){W??=Y4(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){W??=Y4(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){W??=Y4(j)}return{info:J,vcsType:"git",error:W}}catch(Z){return{info:J,vcsType:"none",error:Y4(Z)}}}async function i2($){let f=await yf($);return i7(f)}async function GW($){let f=r7.now(),J=await r2($),W=r7.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:i7(Z),durationMs:W,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as bK,writeFileSync as kK}from"node:fs";import{join as IK}from"node:path";import{resolveCronReportsDir as xK}from"@cline/shared/storage";function r$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function y1($,f){if(f===void 0||f===null)return;return`${$}: ${r$(f)}`}function mK($,f,J){let W=[`runId: ${r$($.runId)}`,`specId: ${r$(f.specId)}`,`externalId: ${r$(f.externalId)}`,`title: ${r$(f.title)}`,`triggerKind: ${r$($.triggerKind)}`,`status: ${r$($.status)}`,`sourcePath: ${r$(f.sourcePath)}`],Z=[y1("sessionId",$.sessionId),y1("startedAt",$.startedAt),y1("completedAt",$.completedAt),y1("triggerEventId",$.triggerEventId),y1("triggerEventType",J?.eventType),y1("triggerEventSource",J?.source),y1("triggerEventSubject",J?.subject)];for(let Q of Z)if(Q)W.push(Q);return`---
14
- ${W.join(`
13
+ ${Q}`;return J||Q||void 0}function A3(f){return[...f.getSnapshot("rule").values()].map((J)=>J.item).filter(O4).sort((J,Q)=>J.name.localeCompare(Q.name))}function S9(f){return b1(A3(f))}var K3={};q(K3,{normalizeWorkspacePath:()=>Mf,generateWorkspaceInfoWithDiagnostics:()=>o2,generateWorkspaceInfo:()=>I1,buildWorkspaceMetadataWithInfo:()=>E9,buildWorkspaceMetadata:()=>e2});import{basename as JP,resolve as QP}from"node:path";import{performance as V3}from"node:perf_hooks";import{processWorkspaceInfo as B3}from"@cline/shared";import ZP from"simple-git";function Mf(f){return QP(f)}async function I1(f){return(await o2(f)).info}function _4(f){if(f instanceof Error)return{errorType:f.name?.trim()||f.constructor.name||"Error",message:f.message};return{errorType:"Error",message:String(f)}}async function o2(f){let $=Mf(f),J={rootPath:$,hint:JP($)},Q;try{let Z=ZP({baseDir:$});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let H=j.map((X)=>{let A=X.refs.fetch||X.refs.push;return`${X.name}: ${A}`});J.associatedRemoteUrls=H}}catch(j){Q??=_4(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){Q??=_4(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){Q??=_4(j)}return{info:J,vcsType:"git",error:Q}}catch(Z){return{info:J,vcsType:"none",error:_4(Z)}}}async function e2(f){let $=await I1(f);return B3($)}async function E9(f){let $=V3.now(),J=await o2(f),Q=V3.now()-$,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:B3(Z),durationMs:Q,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as WP,writeFileSync as jP}from"node:fs";import{join as HP}from"node:path";import{resolveCronReportsDir as XP}from"@cline/shared/storage";function of(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function b$(f,$){if($===void 0||$===null)return;return`${f}: ${of($)}`}function AP(f,$,J){let Q=[`runId: ${of(f.runId)}`,`specId: ${of($.specId)}`,`externalId: ${of($.externalId)}`,`title: ${of($.title)}`,`triggerKind: ${of(f.triggerKind)}`,`status: ${of(f.status)}`,`sourcePath: ${of($.sourcePath)}`],Z=[b$("sessionId",f.sessionId),b$("startedAt",f.startedAt),b$("completedAt",f.completedAt),b$("triggerEventId",f.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(`
15
15
  `)}
16
16
  ---
17
- `}function gK($){let f=[];if($.triggerEvent){let J=$.triggerEvent,W=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((Z)=>Z.length>0);f.push(`## Trigger Event
17
+ `}function YP(f){let $=[];if(f.triggerEvent){let J=f.triggerEvent,Q=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((Z)=>Z.length>0);$.push(`## Trigger Event
18
18
 
19
- ${W.join(`
19
+ ${Q.join(`
20
20
  `)}
21
- `)}if($.error)f.push(`## Error
21
+ `)}if(f.error)$.push(`## Error
22
22
 
23
- ${$.error}
24
- `);if($.finalText&&$.finalText.trim().length>0)f.push(`## Summary
23
+ ${f.error}
24
+ `);if(f.finalText&&f.finalText.trim().length>0)$.push(`## Summary
25
25
 
26
- ${$.finalText.trim()}
27
- `);if($.usage){let J=$.usage,W=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",$.durationMs!==void 0?`- durationMs: ${$.durationMs}`:""].filter((Z)=>Z.length>0);if(W.length>0)f.push(`## Usage
26
+ ${f.finalText.trim()}
27
+ `);if(f.usage){let J=f.usage,Q=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",f.durationMs!==void 0?`- durationMs: ${f.durationMs}`:""].filter((Z)=>Z.length>0);if(Q.length>0)$.push(`## Usage
28
28
 
29
- ${W.join(`
29
+ ${Q.join(`
30
30
  `)}
31
- `)}if($.toolCalls&&$.toolCalls.length>0){let J=$.toolCalls.map((W)=>{let Z=[`- ${W.name}`];if(W.durationMs!==void 0)Z.push(`(${W.durationMs}ms)`);if(W.error)Z.push(`error: ${W.error}`);return Z.join(" ")});f.push(`## Tool Calls
31
+ `)}if(f.toolCalls&&f.toolCalls.length>0){let J=f.toolCalls.map((Q)=>{let Z=[`- ${Q.name}`];if(Q.durationMs!==void 0)Z.push(`(${Q.durationMs}ms)`);if(Q.error)Z.push(`error: ${Q.error}`);return Z.join(" ")});$.push(`## Tool Calls
32
32
 
33
33
  ${J.join(`
34
34
  `)}
35
- `)}return f.join(`
36
- `)}function PW($){let f=xK($.specs);bK(f,{recursive:!0});let J=IK(f,`${$.run.runId}.md`),W=`${mK($.run,$.spec,$.data.triggerEvent)}
37
- ${gK($.data)}`;return kK(J,W,"utf8"),J}class UW{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=W)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var cK=15000,dK=90,t7=["rules","skills","plugins"];function lK($,f){return new Set($.extensions??t7).has(f)}function pK($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of $.tools)J[W]={enabled:!0,autoApprove:!0};if(f==="yolo")J[J0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function rK($){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 FW extends Error{constructor($){super($);this.name="TimeoutError"}}async function iK($,f){if(f<=0)return $;let J,W=new Promise((Z,Q)=>{J=setTimeout(()=>{Q(new FW("cron run timed out"))},f)});try{return await Promise.race([$,W])}finally{if(J)clearTimeout(J)}}class n2{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 UW($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??dK)*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??cK);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:W.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:a7(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,W)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let Q=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,H,X=Date.now(),A;if(J.timeoutSeconds&&J.timeoutSeconds>0)A=X+J.timeoutSeconds*1000;try{H=this.startClaimLeaseHeartbeat($);let Y=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(Y)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let B={config:Y,prompt:this.buildPrompt(J,Q)},K=this.options.runtimeHandlers.sendSession(j,B),G=A?Math.max(1,A-Date.now()):0,P=(await iK(K,G)).result,U=Date.now(),F=PW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:P.text,usage:P.usage,toolCalls:P.toolCalls,durationMs:U-X,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,a7())}catch(Y){let V=Y instanceof FW;if(j&&V)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=Y instanceof Error?Y.message:String(Y),K=Date.now(),G=PW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-X,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:B,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(H?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let W=this.store.getRun(J);if(!W)return;let Z=W.status==="done"?"success":W.status==="cancelled"?"aborted":W.status==="running"?"running":W.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.externalId,executionId:W.runId,sessionId:W.sessionId,triggeredAt:new Date(W.scheduledFor??W.createdAt).getTime(),startedAt:W.startedAt?new Date(W.startedAt).getTime():void 0,endedAt:W.completedAt?new Date(W.completedAt).getTime():void 0,status:Z,errorMessage:W.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let W={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
35
+ `)}return $.join(`
36
+ `)}function h9(f){let $=XP(f.specs);WP($,{recursive:!0});let J=HP($,`${f.run.runId}.md`),Q=`${AP(f.run,f.spec,f.data.triggerEvent)}
37
+ ${YP(f.data)}`;return jP(J,Q,"utf8"),J}class b9{globalMaxConcurrency;activeExecutions=new Map;constructor(f){this.globalMaxConcurrency=Math.max(1,Math.floor(f))}acquire(f,$,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get(f)??new Set;if(Z.size>=Q)return!1;return Z.add($),this.activeExecutions.set(f,Z),!0}release(f,$){let J=this.activeExecutions.get(f);if(!J)return;if(J.delete($),J.size===0)this.activeExecutions.delete(f)}getGlobalActiveCount(){let f=0;for(let $ of this.activeExecutions.values())f+=$.size;return f}}var KP=15000,PP=90,G3=["rules","skills","plugins"];function GP(f,$){return new Set(f.extensions??G3).has($)}function FP(f,$){if(f.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let Q of f.tools)J[Q]={enabled:!0,autoApprove:!0};if($==="yolo")J[Y0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function UP(f){let $=f?.trim();if(!$)return;return["# Notes Directory",`Use ${$} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
38
+ `)}class k9 extends Error{constructor(f){super(f);this.name="TimeoutError"}}async function RP(f,$){if($<=0)return f;let J,Q=new Promise((Z,W)=>{J=setTimeout(()=>{W(new k9("cron run timed out"))},$)});try{return await Promise.race([f,Q])}finally{if(J)clearTimeout(J)}}class f8{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor(f){this.store=f.store,this.materializer=f.materializer,this.options=f,this.limiter=new b9(f.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,(f.claimLeaseSeconds??PP)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let f=Math.max(2000,this.options.pollIntervalMs??KP);await this.tick(),this.timer=setInterval(()=>void this.tick(),f)}async stop(){let f=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!f)return;let $=[...this.activeRuns.entries()];await Promise.all($.map(async([J,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let f=this.store.claimDueRuns({nowIso:P3(),leaseMs:this.claimLeaseMs});await Promise.allSettled(f.map(($)=>this.executeClaim($)))}catch(f){let $=this.options.logger;if($)if($.error)$.error("cron.runner.tick.failed",{error:f});else $.log("cron.runner.tick.failed",{error:f})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([f,$])=>{let J=this.store.getRun(f);return J?[{...J,...$}]:[]})}async executeClaim(f){let $=f.run,J=this.store.getSpec($.specId);if(!J){this.store.completeRun($.runId,{status:"failed",error:"spec not found",claimToken:f.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun($.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:f.claimToken});return}let Q=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,$.runId,Q)){this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,$.runId),this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set($.runId,{claimToken:f.claimToken});let W=$.triggerEventId?this.store.getEventLog($.triggerEventId):void 0,j,H,X=Date.now(),A;if(J.timeoutSeconds&&J.timeoutSeconds>0)A=X+J.timeoutSeconds*1000;try{H=this.startClaimLeaseHeartbeat(f);let Y=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(Y)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set($.runId,{claimToken:f.claimToken,sessionId:j}),this.store.attachSessionIdToRun($.runId,j);let B={config:Y,prompt:this.buildPrompt(J,W)},K=this.options.runtimeHandlers.sendSession(j,B),P=A?Math.max(1,A-Date.now()):0,G=(await RP(K,P)).result,F=Date.now(),U=h9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:j,status:"done"},spec:J,data:{finalText:G.text,usage:G.usage,toolCalls:G.toolCalls,durationMs:F-X,triggerEvent:W}});this.store.completeRun($.runId,{status:"done",sessionId:j,reportPath:U,claimToken:f.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,$.runId),this.store.updateSpecLastRunAt(J.specId,P3())}catch(Y){let V=Y instanceof k9;if(j&&V)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=Y instanceof Error?Y.message:String(Y),K=Date.now(),P=h9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-X,triggerEvent:W}});this.store.completeRun($.runId,{status:"failed",sessionId:j,reportPath:P,error:B,claimToken:f.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,$.runId)}finally{if(H?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete($.runId),this.limiter.release(J.specId,$.runId)}}publishScheduleExecutionEvent(f,$,J){if($.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(J);if(!Q)return;let Z=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher(f,{scheduleId:$.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:Z,errorMessage:Q.error})}buildPrompt(f,$){let J=f.prompt??"";if(!$)return J;let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload};return`${J}
39
39
 
40
40
  Trigger event:
41
- ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,W))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,W){let Z=rK($.notesDirectory),Q=Mf(void 0,Z),j=await i2(f),H=uK({ide:"Cline Cron",workspaceRoot:f,workspaceName:vK(f),metadata:j,rules:$.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?Mf(H,Q)??H:H}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),W=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,Q=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:Q,provider:J,model:W,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:pK($,j),configExtensions:t7.filter((H)=>lK($,H))}}}function a2($,f,J,W){let Z=new Set;function Q(j){let H=j.toLowerCase();if(W){let A=W.indexOf(H);if(A!==-1)return A+f}let X=Number(j);if(!Number.isInteger(X)||X<f||X>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return X}for(let j of $.split(",")){if(j==="*"){for(let A=f;A<=J;A+=1)Z.add(A);continue}let H=j.indexOf("/");if(H!==-1){let A=j.slice(0,H),Y=Number(j.slice(H+1));if(!Number.isInteger(Y)||Y<1)throw Error(`Invalid step "${j.slice(H+1)}"`);let V=f,B=J;if(A!=="*"){let K=A.indexOf("-");if(K!==-1)V=Q(A.slice(0,K)),B=Q(A.slice(K+1));else V=Q(A)}if(V>B)throw Error(`Invalid cron range "${A}"`);for(let K=V;K<=B;K+=Y)Z.add(K);continue}let X=j.indexOf("-");if(X!==-1){let A=Q(j.slice(0,X)),Y=Q(j.slice(X+1));if(A>Y)throw Error(`Invalid cron range "${j}"`);for(let V=A;V<=Y;V+=1)Z.add(V);continue}Z.add(Q(j))}return[...Z].sort((j,H)=>j-H)}var nK=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],o7=["sun","mon","tue","wed","thu","fri","sat"];function t2($,f,J){let W=$[f];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return W}function RW($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function DW($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:a2(t2(f,0,$),0,59),hours:a2(t2(f,1,$),0,23),daysOfMonth:a2(t2(f,2,$),1,31),months:a2(t2(f,3,$),1,12,nK),daysOfWeek:a2(t2(f,4,$),0,6,o7)}}function LW($){DW($)}function e7($,f,J=Date.now()){q1($,J,f)}var s7=new Map,aK=new Map(o7.map(($,f)=>[$,f]));function $3($){let f=$?.trim();return f?f:void 0}function f3($){let f=s7.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 s7.set($,J),J}function tK($){let f=$3($);if(!f)return;f3(f).format(new Date)}function sK($,f){let J=f3(f).formatToParts(new Date($)),W=new Map(J.map((j)=>[j.type,j.value])),Z=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=aK.get(Z);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function oK($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function eK($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function $G($,f,J){let W=DW($),Z=new Date(f);Z.setSeconds(0,0);let Q=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let H=j.getTime();while(Q<=H){if(eK(W,sK(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function q1($,f,J){let W=$3(J);if(W)return tK(W),$G($,f,W);let Z=DW($),Q=new Date(f);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(Q<=j){let{month:H,dayOfMonth:X,dayOfWeek:A,hour:Y,minute:V}=oK(Q.getTime());if(!Z.months.includes(H)){let B=Z.months.find((G)=>G>H)??RW(Z.months,"months"),K=B<=H?1:0;Q=new Date(Q.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(X)||!Z.daysOfWeek.includes(A)){Q=new Date(Q.getFullYear(),Q.getMonth(),X+1,0,0,0,0);continue}if(!Z.hours.includes(Y)){let B=Z.hours.find((G)=>G>Y)??RW(Z.hours,"hours"),K=B<=Y?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(V)){let B=Z.minutes.find((G)=>G>V)??RW(Z.minutes,"minutes"),K=B<=V?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+K,B,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as s2}from"node:crypto";import{asOptionalString as I,asString as a,loadSqliteDb as JG,nowIso as K0}from"@cline/shared/db";import{resolveCronDbPath as WG}from"@cline/shared/storage";var fG=[`CREATE TABLE IF NOT EXISTS cron_specs (
41
+ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim(f.run.runId,f.claimToken,Q))clearInterval(J)},$);return()=>clearInterval(J)}async buildSystemPrompt(f,$,J,Q){let Z=UP(f.notesDirectory),W=k1(void 0,Z),j=await e2($),H=BP({ide:"Cline Cron",workspaceRoot:$,workspaceName:VP($),metadata:j,rules:f.systemPrompt?void 0:W,mode:J,providerId:Q,overridePrompt:f.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return f.systemPrompt?k1(H,W)??H:H}async buildStartRequest(f){let $=(f.workspaceRoot??"").trim(),J=(f.providerId??"").trim(),Q=(f.modelId??"").trim(),Z=f.metadata?.__hubRuntimeOptions&&typeof f.metadata.__hubRuntimeOptions==="object"&&!Array.isArray(f.metadata.__hubRuntimeOptions)?f.metadata.__hubRuntimeOptions:void 0,W=typeof f.metadata?.__hubScheduleCwd==="string"&&f.metadata.__hubScheduleCwd.trim()?f.metadata.__hubScheduleCwd.trim():$;if(!$)throw Error("cron spec requires workspaceRoot");let j=f.mode==="plan"?"plan":f.mode==="act"?"act":"yolo";return{workspaceRoot:$,cwd:W,provider:J,model:Q,mode:j,source:f.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt(f,$,j,J),maxIterations:f.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:FP(f,j),configExtensions:G3.filter((H)=>GP(f,H))}}}function $8(f,$,J,Q){let Z=new Set;function W(j){let H=j.toLowerCase();if(Q){let A=Q.indexOf(H);if(A!==-1)return A+$}let X=Number(j);if(!Number.isInteger(X)||X<$||X>J)throw Error(`Invalid cron value "${j}" for range [${$}-${J}]`);return X}for(let j of f.split(",")){if(j==="*"){for(let A=$;A<=J;A+=1)Z.add(A);continue}let H=j.indexOf("/");if(H!==-1){let A=j.slice(0,H),Y=Number(j.slice(H+1));if(!Number.isInteger(Y)||Y<1)throw Error(`Invalid step "${j.slice(H+1)}"`);let V=$,B=J;if(A!=="*"){let K=A.indexOf("-");if(K!==-1)V=W(A.slice(0,K)),B=W(A.slice(K+1));else V=W(A)}if(V>B)throw Error(`Invalid cron range "${A}"`);for(let K=V;K<=B;K+=Y)Z.add(K);continue}let X=j.indexOf("-");if(X!==-1){let A=W(j.slice(0,X)),Y=W(j.slice(X+1));if(A>Y)throw Error(`Invalid cron range "${j}"`);for(let V=A;V<=Y;V+=1)Z.add(V);continue}Z.add(W(j))}return[...Z].sort((j,H)=>j-H)}var DP=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],U3=["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 ${$+1}`);return Q}function I9(f,$){let J=f[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${$}`);return J}function x9(f){let $=f.trim().split(/\s+/);if($.length!==5)throw Error(`Invalid cron pattern "${f}": expected 5 fields, got ${$.length}`);return{minutes:$8(J8($,0,f),0,59),hours:$8(J8($,1,f),0,23),daysOfMonth:$8(J8($,2,f),1,31),months:$8(J8($,3,f),1,12,DP),daysOfWeek:$8(J8($,4,f),0,6,U3)}}function g9(f){x9(f)}function R3(f,$,J=Date.now()){k$(f,J,$)}var F3=new Map,LP=new Map(U3.map((f,$)=>[f,$]));function D3(f){let $=f?.trim();return $?$:void 0}function L3(f){let $=F3.get(f);if($)return $;let J=new Intl.DateTimeFormat("en-US",{timeZone:f,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return F3.set(f,J),J}function OP(f){let $=D3(f);if(!$)return;L3($).format(new Date)}function _P(f,$){let J=L3($).formatToParts(new Date(f)),Q=new Map(J.map((j)=>[j.type,j.value])),Z=Q.get("weekday")?.toLowerCase().slice(0,3)??"",W=LP.get(Z);if(W===void 0)throw Error(`Unable to resolve weekday for timezone "${$}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:W,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function TP(f){let $=new Date(f);return{month:$.getMonth()+1,dayOfMonth:$.getDate(),dayOfWeek:$.getDay(),hour:$.getHours(),minute:$.getMinutes()}}function zP(f,$){return f.months.includes($.month)&&f.daysOfMonth.includes($.dayOfMonth)&&f.daysOfWeek.includes($.dayOfWeek)&&f.hours.includes($.hour)&&f.minutes.includes($.minute)}function MP(f,$,J){let Q=x9(f),Z=new Date($);Z.setSeconds(0,0);let W=Z.getTime()+60000,j=new Date($);j.setFullYear(j.getFullYear()+4);let H=j.getTime();while(W<=H){if(zP(Q,_P(W,J)))return W;W+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${f}" in timezone "${J}"`)}function k$(f,$,J){let Q=D3(J);if(Q)return OP(Q),MP(f,$,Q);let Z=x9(f),W=new Date($);W.setSeconds(0,0),W=new Date(W.getTime()+60000);let j=new Date($);j.setFullYear(j.getFullYear()+4);while(W<=j){let{month:H,dayOfMonth:X,dayOfWeek:A,hour:Y,minute:V}=TP(W.getTime());if(!Z.months.includes(H)){let B=Z.months.find((P)=>P>H)??I9(Z.months,"months"),K=B<=H?1:0;W=new Date(W.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(X)||!Z.daysOfWeek.includes(A)){W=new Date(W.getFullYear(),W.getMonth(),X+1,0,0,0,0);continue}if(!Z.hours.includes(Y)){let B=Z.hours.find((P)=>P>Y)??I9(Z.hours,"hours"),K=B<=Y?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(V)){let B=Z.minutes.find((P)=>P>V)??I9(Z.minutes,"minutes"),K=B<=V?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate(),W.getHours()+K,B,0,0);continue}return W.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${f}"`)}import{randomUUID as Q8}from"node:crypto";import{asOptionalString as x,asString as n,loadSqliteDb as qP,nowIso as G0}from"@cline/shared/db";import{resolveCronDbPath as yP}from"@cline/shared/storage";var NP=[`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(W,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 J3($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of fG)$.exec(f)}function V4($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function OW($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let W=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function w1($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function i$($){return{specId:a($.spec_id),externalId:a($.external_id),sourcePath:a($.source_path),triggerKind:a($.trigger_kind),sourceMtimeMs:w1($.source_mtime_ms),sourceHash:I($.source_hash),parseStatus:a($.parse_status)==="invalid"?"invalid":"valid",parseError:I($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:a($.title),prompt:I($.prompt),workspaceRoot:I($.workspace_root),scheduleExpr:I($.schedule_expr),timezone:I($.timezone),eventType:I($.event_type),filters:V4(I($.filters_json)),debounceSeconds:w1($.debounce_seconds),dedupeWindowSeconds:w1($.dedupe_window_seconds),cooldownSeconds:w1($.cooldown_seconds),mode:I($.mode),systemPrompt:I($.system_prompt),providerId:I($.provider_id),modelId:I($.model_id),maxIterations:w1($.max_iterations),timeoutSeconds:w1($.timeout_seconds),maxParallel:w1($.max_parallel),tools:OW(I($.tools_json),{preserveEmpty:!0}),notesDirectory:I($.notes_directory),extensions:OW(I($.extensions_json),{preserveEmpty:!0}),source:I($.source),tags:OW(I($.tags_json)),metadata:V4(I($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:I($.last_materialized_run_id),lastRunAt:I($.last_run_at),nextRunAt:I($.next_run_at),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function zW($){return{runId:a($.run_id),specId:a($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:a($.trigger_kind),status:a($.status),claimToken:I($.claim_token),claimStartedAt:I($.claim_started_at),claimUntilAt:I($.claim_until_at),scheduledFor:I($.scheduled_for),triggerEventId:I($.trigger_event_id),startedAt:I($.started_at),completedAt:I($.completed_at),sessionId:I($.session_id),reportPath:I($.report_path),error:I($.error),attemptCount:Number($.attempt_count??0),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function W3($){return{eventId:a($.event_id),eventType:a($.event_type),source:a($.source),subject:I($.subject),occurredAt:a($.occurred_at),receivedAt:a($.received_at),workspaceRoot:I($.workspace_root),dedupeKey:I($.dedupe_key),payload:V4(I($.payload_json)),attributes:V4(I($.attributes_json)),processingStatus:a($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:I($.error),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function Z3($){return $?JSON.stringify($):null}var ZG=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function Q3($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function QG($,f,J,W){for(let Z of ZG){let Q=$[Z],j=f[Z];if(Q3(Q)!==Q3(j))return!0}if(J===!1&&W===!0)return!0;return!1}function jG($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function HG($){return`hub/schedules/${$}.cron.md`}function XG($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function _W($){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:XG($)}}function j3($){return JSON.stringify(_W($))}function AG($,f){let J=$.metadata?{...$.metadata}:{},W=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:W,tags:f.tags??$.tags,runtimeOptions:Q,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class o2{db;constructor($={}){let f=$.dbPath??WG();this.db=JG(f),J3(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?i$(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?i$(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?i$(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>i$(j))}createHubSchedule($){let f=`sched_${s2()}`,J=this.upsertSpec({externalId:f,sourcePath:HG(f),triggerKind:"schedule",sourceHash:j3($),parseStatus:"valid",spec:_W($)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
132
+ ON cron_specs(source_path);`];function O3(f){f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec("PRAGMA foreign_keys = ON;");for(let $ of NP)f.exec($)}function T4(f){if(!f)return;try{let $=JSON.parse(f);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return}function m9(f,$={}){if(!f)return;try{let J=JSON.parse(f);if(!Array.isArray(J))return;let Q=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if($.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function I$(f){if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="bigint")return Number(f);return}function ef(f){return{specId:n(f.spec_id),externalId:n(f.external_id),sourcePath:n(f.source_path),triggerKind:n(f.trigger_kind),sourceMtimeMs:I$(f.source_mtime_ms),sourceHash:x(f.source_hash),parseStatus:n(f.parse_status)==="invalid"?"invalid":"valid",parseError:x(f.parse_error),enabled:Number(f.enabled??0)===1,removed:Number(f.removed??0)===1,title:n(f.title),prompt:x(f.prompt),workspaceRoot:x(f.workspace_root),scheduleExpr:x(f.schedule_expr),timezone:x(f.timezone),eventType:x(f.event_type),filters:T4(x(f.filters_json)),debounceSeconds:I$(f.debounce_seconds),dedupeWindowSeconds:I$(f.dedupe_window_seconds),cooldownSeconds:I$(f.cooldown_seconds),mode:x(f.mode),systemPrompt:x(f.system_prompt),providerId:x(f.provider_id),modelId:x(f.model_id),maxIterations:I$(f.max_iterations),timeoutSeconds:I$(f.timeout_seconds),maxParallel:I$(f.max_parallel),tools:m9(x(f.tools_json),{preserveEmpty:!0}),notesDirectory:x(f.notes_directory),extensions:m9(x(f.extensions_json),{preserveEmpty:!0}),source:x(f.source),tags:m9(x(f.tags_json)),metadata:T4(x(f.metadata_json)),revision:Number(f.revision??1),lastMaterializedRunId:x(f.last_materialized_run_id),lastRunAt:x(f.last_run_at),nextRunAt:x(f.next_run_at),createdAt:n(f.created_at),updatedAt:n(f.updated_at)}}function v9(f){return{runId:n(f.run_id),specId:n(f.spec_id),specRevision:Number(f.spec_revision??1),triggerKind:n(f.trigger_kind),status:n(f.status),claimToken:x(f.claim_token),claimStartedAt:x(f.claim_started_at),claimUntilAt:x(f.claim_until_at),scheduledFor:x(f.scheduled_for),triggerEventId:x(f.trigger_event_id),startedAt:x(f.started_at),completedAt:x(f.completed_at),sessionId:x(f.session_id),reportPath:x(f.report_path),error:x(f.error),attemptCount:Number(f.attempt_count??0),createdAt:n(f.created_at),updatedAt:n(f.updated_at)}}function _3(f){return{eventId:n(f.event_id),eventType:n(f.event_type),source:n(f.source),subject:x(f.subject),occurredAt:n(f.occurred_at),receivedAt:n(f.received_at),workspaceRoot:x(f.workspace_root),dedupeKey:x(f.dedupe_key),payload:T4(x(f.payload_json)),attributes:T4(x(f.attributes_json)),processingStatus:n(f.processing_status),matchedSpecCount:Number(f.matched_spec_count??0),queuedRunCount:Number(f.queued_run_count??0),suppressedCount:Number(f.suppressed_count??0),error:x(f.error),createdAt:n(f.created_at),updatedAt:n(f.updated_at)}}function T3(f){return f?JSON.stringify(f):null}var wP=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function z3(f){if(f===void 0)return null;if(f&&typeof f==="object")return JSON.stringify(f);return f}function CP(f,$,J,Q){for(let Z of wP){let W=f[Z],j=$[Z];if(z3(W)!==z3(j))return!0}if(J===!1&&Q===!0)return!0;return!1}function SP(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function EP(f){return`hub/schedules/${f}.cron.md`}function hP(f){let $={...f.metadata??{},...f.createdBy?{__hubScheduleCreatedBy:f.createdBy}:{},...f.cwd?{__hubScheduleCwd:f.cwd}:{},...f.runtimeOptions?{__hubRuntimeOptions:f.runtimeOptions}:{}};return Object.keys($).length>0?$:void 0}function c9(f){return{triggerKind:"schedule",title:f.name.trim(),prompt:f.prompt,workspaceRoot:f.workspaceRoot.trim(),schedule:f.cronPattern.trim(),mode:f.mode??"act",systemPrompt:f.systemPrompt,modelSelection:f.modelSelection?JSON.parse(JSON.stringify(f.modelSelection)):void 0,maxIterations:typeof f.maxIterations==="number"?Math.floor(f.maxIterations):void 0,timeoutSeconds:typeof f.timeoutSeconds==="number"?Math.floor(f.timeoutSeconds):void 0,maxParallel:typeof f.maxParallel==="number"?Math.max(1,Math.floor(f.maxParallel)):1,source:"hub-schedule",tags:f.tags?.filter(($)=>$.trim().length>0),enabled:f.enabled!==!1,metadata:hP(f)}}function M3(f){return JSON.stringify(c9(f))}function bP(f,$){let J=f.metadata?{...f.metadata}:{},Q=$.createdBy===null?void 0:$.createdBy!==void 0?$.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=$.cwd!==void 0?$.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,W=$.runtimeOptions!==void 0?$.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:$.name??f.title,cronPattern:$.cronPattern??f.scheduleExpr??"",prompt:$.prompt??f.prompt??"",workspaceRoot:$.workspaceRoot??f.workspaceRoot??"",cwd:Z,modelSelection:$.modelSelection!==void 0?$.modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:$.enabled??f.enabled,mode:$.mode??(f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"),systemPrompt:$.systemPrompt===null?void 0:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,maxIterations:$.maxIterations===null?void 0:$.maxIterations!==void 0?$.maxIterations:f.maxIterations,timeoutSeconds:$.timeoutSeconds===null?void 0:$.timeoutSeconds!==void 0?$.timeoutSeconds:f.timeoutSeconds,maxParallel:$.maxParallel??f.maxParallel??1,createdBy:Q,tags:$.tags??f.tags,runtimeOptions:W,metadata:$.metadata!==void 0?$.metadata:Object.keys(J).length>0?J:void 0}}class Z8{db;constructor(f={}){let $=f.dbPath??yP();this.db=qP($),O3(this.db)}close(){this.db.close?.()}getSpecBySourcePath(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get(f);return $?ef($):void 0}getSpec(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f);return $?ef($):void 0}getSpecByExternalId(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get(f);return $?ef($):void 0}listSpecs(f={}){let $=[],J=[];if(f.triggerKind)$.push("trigger_kind = ?"),J.push(f.triggerKind);if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.parseStatus)$.push("parse_status = ?"),J.push(f.parseStatus);if(!f.includeRemoved)$.push("removed = 0");let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"",Z=Math.max(1,Math.floor(f.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>ef(j))}createHubSchedule(f){let $=`sched_${Q8()}`,J=this.upsertSpec({externalId:$,sourcePath:EP($),triggerKind:"schedule",sourceHash:M3(f),parseStatus:"valid",spec:c9(f)});this.initializeScheduleNextRun(J.record.specId);let Q=this.getSpec(J.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule(f){let $=this.db.prepare(`SELECT * FROM cron_specs
133
133
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
134
- ORDER BY created_at ASC LIMIT 1`).get($);return f?i$(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let Q of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
135
- WHERE ${f.join(" AND ")}
136
- ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>i$(Q))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let W=AG(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:j3(W),parseStatus:"valid",spec:_W(W)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:K0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
134
+ ORDER BY created_at ASC LIMIT 1`).get(f);return $?ef($):void 0}listHubSchedules(f={}){let $=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.tags&&f.tags.length>0)for(let W of f.tags)$.push("tags_json LIKE ?"),J.push(`%"${W.trim()}"%`);let Q=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
135
+ WHERE ${$.join(" AND ")}
136
+ ORDER BY created_at DESC LIMIT ?`).all(...J,Q).map((W)=>ef(W))}updateHubSchedule(f,$){let J=this.getHubSchedule(f);if(!J)return;let Q=bP(J,$),Z=this.upsertSpec({externalId:f,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:M3(Q),parseStatus:"valid",spec:c9(Q)});if($.cronPattern!==void 0||$.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule(f){let $=this.getHubSchedule(f);if(!$)return!1;return this.markSpecRemoved($.specId),this.cancelQueuedRunsForSpec($.specId),!0}enqueueHubScheduleRun(f,$="manual"){let J=this.getHubSchedule(f);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:$,scheduledFor:G0()})}listEventSpecsForType(f){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)=>i$(J))}upsertSpec($){let f=K0(),J=this.getSpecBySourcePath($.sourcePath),W=$.spec,Z={title:W?.title??J?.title??jG($.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},Q=$.parseStatus==="valid"&&(W?.enabled??!0);if(!J){let Y=`cspec_${s2()}`;this.insertSpecRow(Y,$,Z,Q,f);let V=this.getSpec(Y);if(!V)throw Error("failed to insert cron_spec row");return{record:V,created:!0,revisionChanged:!0}}let H=J.sourceHash!==$.sourceHash&&QG(J,Z,J.enabled,Q),X=H?J.revision+1:J.revision;this.updateSpecRow(J.specId,$,Z,Q,X,f);let A=this.getSpec(J.specId);if(!A)throw Error("failed to reload cron_spec after update");return{record:A,created:!1,revisionChanged:H}}insertSpecRow($,f,J,W,Z){let Q=f.spec;this.db.prepare(`INSERT INTO cron_specs (
142
+ ORDER BY created_at ASC`).all(f).map((J)=>ef(J))}upsertSpec(f){let $=G0(),J=this.getSpecBySourcePath(f.sourcePath),Q=f.spec,Z={title:Q?.title??J?.title??SP(f.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},W=f.parseStatus==="valid"&&(Q?.enabled??!0);if(!J){let Y=`cspec_${Q8()}`;this.insertSpecRow(Y,f,Z,W,$);let V=this.getSpec(Y);if(!V)throw Error("failed to insert cron_spec row");return{record:V,created:!0,revisionChanged:!0}}let H=J.sourceHash!==f.sourceHash&&CP(J,Z,J.enabled,W),X=H?J.revision+1:J.revision;this.updateSpecRow(J.specId,f,Z,W,X,$);let A=this.getSpec(J.specId);if(!A)throw Error("failed to reload cron_spec after update");return{record:A,created:!1,revisionChanged:H}}insertSpecRow(f,$,J,Q,Z){let W=$.spec;this.db.prepare(`INSERT INTO cron_specs (
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(W,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,W?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Q?.tags?JSON.stringify(Q.tags):null,Q?.metadata?JSON.stringify(Q.metadata):null,1,Z,Z)}updateSpecRow($,f,J,W,Z,Q){let j=f.spec;this.db.prepare(`UPDATE cron_specs SET
153
+ ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f,$.externalId,$.sourcePath,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,Q?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,W?.tags?JSON.stringify(W.tags):null,W?.metadata?JSON.stringify(W.metadata):null,1,Z,Z)}updateSpecRow(f,$,J,Q,Z,W){let j=$.spec;this.db.prepare(`UPDATE cron_specs SET
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,63 +162,63 @@ ${JSON.stringify(W,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,W?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,Z,Q,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(K0(),$)}updateSpecNextRunAt($,f){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f??null,K0(),$)}updateSpecLastRunAt($,f){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f,K0(),$)}updateLastMaterializedRunId($,f){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(f,K0(),$)}initializeScheduleNextRun($){let f=this.getSpec($);if(!f||f.triggerKind!=="schedule"||!f.enabled||!f.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let J=new Date(q1(f.scheduleExpr,Date.now(),f.timezone)).toISOString();this.updateSpecNextRunAt($,J)}materializeDueScheduleRun($){let f=$.nowMs,J=new Date(f).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let Z=i$(W);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let Q=Z.nextRunAt;if(!Q){let X=new Date(q1(Z.scheduleExpr,f,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(X,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X}}if(new Date(Q).getTime()>f)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Q};let j=`crun_${s2()}`,H;try{H=new Date(q1(Z.scheduleExpr,f,Z.timezone)).toISOString()}catch{H=void 0}return this.db.prepare(`INSERT INTO cron_runs (
165
+ WHERE spec_id = ?`).run($.externalId,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,Q?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,Z,W,f)}markSpecRemoved(f){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(G0(),f)}updateSpecNextRunAt(f,$){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run($??null,G0(),f)}updateSpecLastRunAt(f,$){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run($,G0(),f)}updateLastMaterializedRunId(f,$){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run($,G0(),f)}initializeScheduleNextRun(f){let $=this.getSpec(f);if(!$||$.triggerKind!=="schedule"||!$.enabled||!$.scheduleExpr){this.updateSpecNextRunAt(f,void 0);return}let J=new Date(k$($.scheduleExpr,Date.now(),$.timezone)).toISOString();this.updateSpecNextRunAt(f,J)}materializeDueScheduleRun(f){let $=f.nowMs,J=new Date($).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let Z=ef(Q);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let W=Z.nextRunAt;if(!W){let X=new Date(k$(Z.scheduleExpr,$,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(X,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X}}if(new Date(W).getTime()>$)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:W};let j=`crun_${Q8()}`,H;try{H=new Date(k$(Z.scheduleExpr,$,Z.timezone)).toISOString()}catch{H=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",Q,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
169
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(j,Z.specId,Z.revision,"schedule","queued",W,null,0,J,J),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,H??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:H}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?zW(f):void 0}insertEventLog($,f={}){let J=K0(),W=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let Q=$.eventType.trim();if(!Q)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let H=$.occurredAt.trim()||W,X=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
174
+ WHERE spec_id = ?`).run(j,J,H??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:H}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun(f){let $=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get(f);return $?v9($):void 0}insertEventLog(f,$={}){let J=G0(),Q=$.receivedAtIso??J,Z=f.eventId.trim();if(!Z)throw Error("automation event requires eventId");let W=f.eventType.trim();if(!W)throw Error("automation event requires eventType");let j=f.source.trim();if(!j)throw Error("automation event requires source");let H=f.occurredAt.trim()||Q,X=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
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,Q,j,$.subject?.trim()||null,H,W,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,Z3($.payload),Z3($.attributes),"received",0,0,0,null,J,J).changes??0,A=this.getEventLog(Z);if(!A)throw Error("failed to insert cron_event_log row");return{record:A,created:X===1}}getEventLog($){let f=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return f?W3(f):void 0}listEventLogs($={}){let f=[],J=[];if($.eventType)f.push("event_type = ?"),J.push($.eventType);if($.source)f.push("source = ?"),J.push($.source);if($.processingStatus)f.push("processing_status = ?"),J.push($.processingStatus);let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${W}
180
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,W,j,f.subject?.trim()||null,H,Q,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,T3(f.payload),T3(f.attributes),"received",0,0,0,null,J,J).changes??0,A=this.getEventLog(Z);if(!A)throw Error("failed to insert cron_event_log row");return{record:A,created:X===1}}getEventLog(f){let $=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get(f);return $?_3($):void 0}listEventLogs(f={}){let $=[],J=[];if(f.eventType)$.push("event_type = ?"),J.push(f.eventType);if(f.source)$.push("source = ?"),J.push(f.source);if(f.processingStatus)$.push("processing_status = ?"),J.push(f.processingStatus);let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"",Z=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
181
181
  ORDER BY received_at DESC, created_at DESC
182
- LIMIT ?`).all(...J,Z).map((j)=>W3(j))}updateEventLogProcessing($,f){return(this.db.prepare(`UPDATE cron_event_log SET
182
+ LIMIT ?`).all(...J,Z).map((j)=>_3(j))}updateEventLogProcessing(f,$){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,K0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let H=j.map(()=>"?").join(",");f.push(`status IN (${H})`);for(let X of j)J.push(X)}}let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>zW(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
189
+ WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,G0(),f).changes??0)===1}listRuns(f={}){let $=[],J=[];if(f.specId)$.push("spec_id = ?"),J.push(f.specId);if(f.status){let j=Array.isArray(f.status)?f.status:[f.status];if(j.length>0){let H=j.map(()=>"?").join(",");$.push(`status IN (${H})`);for(let X of j)J.push(X)}}let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"",Z=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>v9(j))}hasRecentEventRunForDedupe(f){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'
193
193
  AND e.dedupe_key = ?
194
194
  AND e.received_at >= ?
195
- LIMIT 1`).get($.specId,$.dedupeKey,$.sinceIso)}hasRecentEventRunForSpec($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
195
+ LIMIT 1`).get(f.specId,f.dedupeKey,f.sinceIso)}hasRecentEventRunForSpec(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
196
196
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
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(f.specId,f.sinceIso)}findQueuedEventRunForDedupe(f){let $=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?zW(f):void 0}updateQueuedEventRunForDebounce($){let f=K0();if((this.db.prepare(`UPDATE cron_runs SET
207
+ LIMIT 1`).get(f.specId,f.dedupeKey);return $?v9($):void 0}updateQueuedEventRunForDebounce(f){let $=G0();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(f.triggerEventId,f.scheduledFor,$,f.runId).changes??0)!==1)return;return this.getRun(f.runId)}hasOneOffRunForRevision(f,$){return!!this.db.prepare(`SELECT run_id FROM cron_runs
214
214
  WHERE spec_id = ? AND spec_revision = ?
215
215
  AND trigger_kind = 'one_off'
216
- LIMIT 1`).get($,f)}enqueueRun($){let f=`crun_${s2()}`,J=K0();this.db.prepare(`INSERT INTO cron_runs (
216
+ LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${Q8()}`,J=G0();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 W=this.getRun(f);if(!W)throw Error("failed to insert cron_run row");return W}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
221
- WHERE spec_id = ? AND status = 'queued'`).run(K0(),$).changes??0}claimDueRuns($){let f=$.nowIso,J=Math.max(1000,Math.floor($.leaseMs)),W=new Date(new Date(f).getTime()+J).toISOString(),Z=Math.max(1,Math.floor($.limit??25)),Q=[];this.db.exec("BEGIN IMMEDIATE;");try{let j=this.db.prepare(`SELECT * FROM cron_runs
220
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run($,f.specId,f.specRevision,f.triggerKind,"queued",f.scheduledFor??null,f.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId(f.specId,$);let Q=this.getRun($);if(!Q)throw Error("failed to insert cron_run row");return Q}cancelQueuedRunsForSpec(f){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
221
+ WHERE spec_id = ? AND status = 'queued'`).run(G0(),f).changes??0}claimDueRuns(f){let $=f.nowIso,J=Math.max(1000,Math.floor(f.leaseMs)),Q=new Date(new Date($).getTime()+J).toISOString(),Z=Math.max(1,Math.floor(f.limit??25)),W=[];this.db.exec("BEGIN IMMEDIATE;");try{let j=this.db.prepare(`SELECT * FROM cron_runs
222
222
  WHERE (
223
223
  status = 'queued'
224
224
  OR (
@@ -230,7 +230,7 @@ ${JSON.stringify(W,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 H of j){let X=a(H.run_id);if(!X)continue;let A=`cclaim_${s2()}`;if((this.db.prepare(`UPDATE cron_runs SET
233
+ LIMIT ?`).all($,$,Z);for(let H of j){let X=n(H.run_id);if(!X)continue;let A=`cclaim_${Q8()}`;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(W,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,W,f,f,X,f).changes??0)!==1)continue;let V=this.getRun(X);if(!V)continue;Q.push({run:V,claimToken:A,claimUntilAt:W})}this.db.exec("COMMIT;")}catch(j){throw this.db.exec("ROLLBACK;"),j}return Q}renewClaim($,f,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
255
- WHERE run_id = ? AND claim_token = ?`).run(J,K0(),$,f).changes??0)===1}completeRun($,f){let J=f.completedAtIso??K0(),W=f.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
254
+ )`).run(A,$,Q,$,$,X,$).changes??0)!==1)continue;let V=this.getRun(X);if(!V)continue;W.push({run:V,claimToken:A,claimUntilAt:Q})}this.db.exec("COMMIT;")}catch(j){throw this.db.exec("ROLLBACK;"),j}return W}renewClaim(f,$,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
255
+ WHERE run_id = ? AND claim_token = ?`).run(J,G0(),f,$).changes??0)===1}completeRun(f,$){let J=$.completedAtIso??G0(),Q=$.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(W,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
- ${W}`).run(f.status,f.sessionId??null,f.reportPath??null,f.error??null,J,J,$,...f.claimToken?[f.claimToken]:[]).changes??0)>0}requeueRun($){let f=K0();return(this.db.prepare(`UPDATE cron_runs SET
265
+ ${Q}`).run($.status,$.sessionId??null,$.reportPath??null,$.error??null,J,J,f,...$.claimToken?[$.claimToken]:[]).changes??0)>0}requeueRun(f){let $=G0();return(this.db.prepare(`UPDATE cron_runs SET
266
266
  status = 'queued',
267
267
  claim_started_at = NULL,
268
268
  claim_token = NULL,
@@ -274,24 +274,65 @@ ${JSON.stringify(W,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,K0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,K0(),$)}}function K4($){return $?new Date($).getTime():void 0}function YG($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function B4($){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:K4($.nextRunAt),lastRunAt:K4($.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:YG($)}}function VG($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function TW($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:K4($.startedAt),endedAt:K4($.completedAt),status:VG($.status),errorMessage:$.error}}class qf{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new o2({dbPath:$.dbPath}),this.materializer=new p2({store:this.store}),this.runner=new n2({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(LW($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return B4(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?B4(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>B4(f))}updateSchedule($,f){if(f.cronPattern!==void 0)LW(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let W=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule($,{...f,scheduleId:$});return Q?B4(Q):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return TW(J,$)}triggerScheduleNowDetached($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;return this.runner.tick().catch(()=>{return}),TW(f,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let Q=f??this.store.getSpec(Z.specId);if(!Q||Q.source!=="hub-schedule")return;return TW(Z,Q.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,Z=0,Q;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!Q&&j.status!=="success"&&j.status!=="completed")Q=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,W+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:W>0?Z/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}m4();import{createSessionId as aP,resolveHubCommandTimeoutMs as tP}from"@cline/shared";var T3={};w(T3,{splitCoreSessionConfig:()=>X8,isSessionNotFoundError:()=>q$,SessionNotFoundError:()=>y$,SESSION_NOT_FOUND_ERROR_CODE:()=>C1});var C1="session_not_found";class y$ extends Error{sessionId;code="session_not_found";constructor($,f){super(f??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function q$($){return $ instanceof y$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function X8($){let{hooks:f,logger:J,telemetry:W,extensionContext:Z,extraTools:Q,extensions:j,onTeamEvent:H,onConsecutiveMistakeLimitReached:X,checkpoint:A,compaction:Y,...V}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(W)B.telemetry=W;if(Z)B.extensionContext=Z;if(Q)B.extraTools=Q;if(j)B.extensions=j;if(H)B.onTeamEvent=H;if(X)B.onConsecutiveMistakeLimitReached=X;if(A?.createCheckpoint)B.checkpoint=A;if(Y?.compact)B.compaction=Y;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...A?{checkpoint:{enabled:A.enabled}}:{},...Y?{compaction:{enabled:Y.enabled,strategy:Y.strategy,thresholdRatio:Y.thresholdRatio,reserveTokens:Y.reserveTokens,preserveRecentTokens:Y.preserveRecentTokens,maxInputTokens:Y.maxInputTokens,summarizer:Y.summarizer}}:{}},...K?{localRuntime:K}:{}}}import{spawn as yP}from"node:child_process";import{closeSync as qP,mkdirSync as wP,openSync as SP}from"node:fs";import{basename as hP,dirname as CP,join as EP}from"node:path";import{fileURLToPath as bP}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as kP,isHubDaemonProcess as x3,withResolvedClineBuildEnv as IP}from"@cline/shared";import{createHash as jP,randomBytes as HP}from"node:crypto";import{existsSync as XP}from"node:fs";import{chmod as AP,mkdir as wW,readFile as w3,rm as SW,writeFile as S3}from"node:fs/promises";import{dirname as h3,join as hW}from"node:path";import{resolveClineDataDir as Y8,resolveClineDir as C3}from"@cline/shared/storage";var M3="0.0.45";var A8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:M3,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",VP="CLINE_HUB_BUILD_ID",y3=30000,BP=15000,KP=100;function GP($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function PP($){return jP("sha256").update($).digest("hex").slice(0,12)}function UP($){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 g4(){return HP(32).toString("hex")}function FP($){return new Promise((f)=>setTimeout(f,$))}function RP($){return`${$}.lock`}async function DP($){try{let f=JSON.parse(await w3(hW($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function q3($){await SW($,{recursive:!0,force:!0}).catch(()=>{return})}function t$(){return process.env[VP]?.trim()||String(A8.version)}function w$($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${PP($)}`,J=process.env[YP]?.trim()||hW(Y8(),"locks","hub","owners",`${GP(f)}.json`);return{ownerId:f,discoveryPath:J}}function E3($=`hub-${Date.now().toString(36)}`){return w$($)}async function V0($){try{let f=JSON.parse(await w3($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,coreVersion:typeof f.coreVersion==="string"?f.coreVersion:void 0,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function v4($,f){await wW(h3($),{recursive:!0}),await SW($,{force:!0}).catch(()=>{return}),await S3($,`${JSON.stringify(f,null,2)}
278
- `,{encoding:"utf8",mode:384}),await AP($,384)}async function b0($){await SW($,{force:!0}).catch(()=>{return})}async function u4($,f){let J=RP($);await wW(h3(J),{recursive:!0});let W=Date.now()+BP;while(!0)try{await wW(J,{recursive:!1}),await S3(hW(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
279
- `,"utf8");try{return await f()}finally{await q3(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await DP(J),H=j?Date.now()-Date.parse(j.acquiredAt):y3+1;if(!j||!UP(j.pid)||H>y3){await q3(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await FP(KP)}}async function Q$($){try{let f=await fetch(CW($));if(!f.ok)return;return await f.json()}catch{return}}function t0($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function CW($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function b3($){return XP($)}import{CLINE_HUB_DEV_PORT as LP,CLINE_HUB_PORT as OP,resolveClineBuildEnv as zP}from"@cline/shared";var _P="CLINE_HUB_HOST",TP="CLINE_HUB_PORT",NP="CLINE_HUB_PATHNAME",EW="127.0.0.1",bW=OP,kW="/hub";function k3($){return zP($)==="development"?LP:bW}function IW($={}){return($.env??process.env)[_P]?.trim()||EW}function bf($={}){let J=($.env??process.env)[TP]?.trim();if(!J)return k3($);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return k3($);return W}function xW($={}){return($.env??process.env)[NP]?.trim()||kW}function j$($={},f={}){return{host:$.host??IW(f),port:$.port??bf(f),pathname:$.pathname??xW(f)}}var MP="shared:cline";function I3($){let f=L$($.trim());return w$(`workspace:${f||$.trim()}`)}function G0($=MP){return w$($)}var xP=8000,mP=200,gP=3000,vP=100,uP=[100,250,500,1000,2000],cP="--cline-hub-daemon";function dP($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function lP(){try{let $=EP(Y8(),"logs","hub-daemon.log");return wP(CP($),{recursive:!0}),{fd:SP($,"a"),logPath:$}}catch{return}}function V8($){let f=$.buildId?.trim();return!!f&&f===t$()}async function E1($){try{return await Q$($)}catch{return}}async function pP($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await E1($))?.url)return!0;await new Promise((Z)=>setTimeout(Z,vP))}return!1}async function B8($,f){if(V8($))return;if(await K8($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await pP($.url,gP),await b0(f).catch(()=>{return})}function rP(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return bP(new URL(`./entry.${$}`,import.meta.url))}function iP($,f){let J=rP(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let Z=hP(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),H=Q?[cP]:[...j?["--conditions=development"]:[],J];return{launcher:W,args:[...H,"--cwd",$,...dP(f)],cwd:$,env:{...IP(process.env),CLINE_NO_INTERACTIVE:"1",[kP]:"1"}}}function nP($){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 mW($,f={}){if(x3())return;let J=iP($,f),W=lP();try{yP(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)qP(W.fd)}}async function kf($,f={}){for(let J=0;;J++)try{mW($,f);return}catch(W){let Z=uP[J];if(!nP(W)||Z===void 0)throw W;await new Promise((Q)=>setTimeout(Q,Z))}}function c4($,f={}){if(x3())return;let J=G0(),W=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=j$(f),Q=t0(Z.host,Z.port,Z.pathname);V0(J.discoveryPath).then(async(j)=>{if(j?.url){let Y=await E1(j.url);if(Y?.url&&V8(Y)&&await H$(Y.url,{authToken:j.authToken}))return;if(Y?.url)await B8({...Y,authToken:j.authToken},J.discoveryPath);else await b0(J.discoveryPath).catch(()=>{return})}let H=await E1(Q);if(H?.url)await B8(H,J.discoveryPath);let A=!W&&Z.port!==0?{...Z,port:0}:Z;await kf($,A)}).catch(()=>{})}async function m3($,f={}){let J=G0(),W=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=j$(f),j=t0(Q.host,Q.port,Q.pathname),H=(K)=>{if(!W)s$(K.url,K.authToken);return K},X=await V0(J.discoveryPath);if(X?.url){let K=await E1(X.url);if(K?.url&&V8(K)&&await H$(K.url,{authToken:X.authToken}))return H({url:K.url,authToken:X.authToken});if(K?.url)await B8({...K,authToken:X.authToken},J.discoveryPath);else await b0(J.discoveryPath).catch(()=>{return})}let A=await E1(j);if(A?.url)await B8(A,J.discoveryPath);let V=!Z&&Q.port!==0?{...Q,port:0}:Q;await kf($,V);let B=Date.now()+xP;while(Date.now()<B){let K=await V0(J.discoveryPath);if(K?.url){let R=await E1(K.url);if(R?.url&&V8(R)&&await H$(R.url,{authToken:K.authToken}))return H({url:R.url,authToken:K.authToken})}let G=await E1(j);if(G?.url&&!V8(G))await B8(G,J.discoveryPath);await new Promise((R)=>setTimeout(R,mP))}throw Error("Timed out waiting for detached hub startup.")}function sP(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function d3($){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 d3($.data);return String($)}function oP($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function g3($){let f=$,J=oP(f.reason);return new z0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:gW,{closeCode:f.code,closeReason:J||void 0})}function eP($,f){if($ instanceof z0)return $;if($ instanceof Error)return new z0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new z0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new z0("hub_connect_failed",J);let W=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new z0("hub_connect_failed",W?`Failed to connect to hub at ${f.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var $U=8000,fU=200,v3="*",u3=8000,JU="cline-hub-auth.",l3=new Map,p3=new Set,WU=3000,ZU=3000,QU=100,gW="Hub connection closed",jU=250,HU=5000,c3=0.5;class z0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function cW($){return $ instanceof z0}class If extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function d4($,f){return $ instanceof If&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function r3($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=dW($.toString());return J?l3.get(J):void 0}function XU($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function dW($){if(!XU($))return;let f=new URL(o$($));return f.search="",f.hash="",f.toString()}function vW($){let f=dW($);return!!f&&p3.has(f)}function s$($,f){let J=dW($);if(J){if(p3.add(J),f?.trim())l3.set(J,f)}return $}class s0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new z0("hub_connection_closed",gW);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()||r3($);$.hash="";let W=new(sP())($.toString(),f?[`${JU}${f}`]:void 0);this.socket=W;let Z=!1;this.connectPromise=new Promise((Q,j)=>{let H=!1,X=setTimeout(()=>{if(H)return;H=!0,Z=!0,this.lastCloseError=new z0("hub_connect_timeout",`Timed out connecting to hub after ${u3}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}j(this.lastCloseError)},u3);W.addEventListener("open",()=>{if(H)return;H=!0,clearTimeout(X),Q()}),W.addEventListener("error",(A)=>{if(H)return;H=!0,clearTimeout(X),this.lastCloseError=eP(A,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),W.addEventListener("close",(A)=>{if(H)return;if(H=!0,clearTimeout(X),!Z)this.lastCloseError=g3(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(d3(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!Z)this.lastCloseError=g3(Q),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,W={listener:$,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,W){let Z=0,Q=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,W)}catch(j){if(!Q||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,W){await this.connect();let Z=aP("hubreq_"),Q=tP($,W?.timeoutMs),j=new Promise((X,A)=>{let Y=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;A(new If($,"hub_command_timeout",`Hub command ${$} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(Z,{resolve:(V)=>{if(Y)clearTimeout(Y);X(V)},reject:(V)=>{if(Y)clearTimeout(Y);A(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:f}})}catch(X){throw this.pendingReplies.delete(Z),X}let H=await j;if(!H.ok){if(H.error?.code===C1){let X=J??(typeof f?.sessionId==="string"?f.sessionId:void 0);throw new y$(X,H.error.message)}throw new If($,H.error?.code,H.error?.message??`Hub command ${$} failed`)}return H}async recoverLocalHubTransport($){if(!vW(this.currentUrl)||!cW($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await b1({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(jU*2**this.reconnectAttempt,HU),f=Math.round($*(1-c3)+Math.random()*$*c3);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(!vW(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await b1({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 z0("hub_connection_closed",gW),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 z0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),W=(this.subscriptionCounts.get(J)??0)+f;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,W),f>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??v3}subscriptionSessionIdFromKey($){return $===v3?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 o$($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function H$($,f){let J=new s0({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 uW($,f){let J=o$($),W=await Q$(J);if(!W)return{status:"unreachable",url:J};let Z=t$(),Q=W.buildId?.trim();if(!Q||Q!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await H$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function AU($){let f=Date.now()+$U;while(Date.now()<f){let J=await V0($.discoveryPath);if(J?.url){let W=await uW(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return s$(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,fU))}return}async function YU($){let f=Date.now()+ZU;while(Date.now()<f){if(!(await Q$($).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,QU))}return!1}function VU($,f){try{return o$($)===o$(f)}catch{return!1}}function BU($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle"||W.status==="pending")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function KU($,f,J){let W=new s0({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await W.command("session.list",{limit:500},void 0,{timeoutMs:WU});return!BU(Z.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function G8($={}){if($.endpoint?.trim()){let Z=await uW($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=G0(),J=await V0(f.discoveryPath);if(!J?.url)return;let W=await uW(J.url);if(W.status==="compatible")return s$(W.url,J.authToken);if(W.status==="build_mismatch")await b0(f.discoveryPath).catch(()=>{return});return}async function b1($={}){let f=await G8($);if(f&&await H$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=G0();return await kf($.workspaceRoot??process.cwd()),await AU(J)}async function K8($,f){let J=new URL($),W=f?.trim()||r3(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function lW(){let $=G0(),f=await V0($.discoveryPath);if(!f?.url)return!1;try{if(await K8(f.url,f.authToken))return!0}catch{}return!1}async function l4($){if(!vW($.url))return;let f=G0(),J=await V0(f.discoveryPath);if(!J?.url||!VU(J.url,$.url))return;if(!await KU(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await lW())return;if(!await YU(J.url))return;return await b0(f.discoveryPath).catch(()=>{return}),await b1({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}function GU($,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 PU="cline-hub-auth.";function UU($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function FU($,f){let J=new URL($),W=new URL(f);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function RU($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=G0(),W=await V0(J.discoveryPath);if(W?.url&&FU($.toString(),W.url))return W.authToken;return}async function pW($={}){let f=j$($);if(!UU($)){let J=G0(),W=await V0(J.discoveryPath);if(W?.url)return W.url}return t0(f.host,f.port,f.pathname)}async function p4($){return await new Promise((f,J)=>{(async()=>{let W=new URL($),Z=await RU(W);W.hash="";let Q=new WebSocket(W.toString(),Z?[`${PU}${Z}`]:void 0),j=new Map,H=0;Q.addEventListener("open",()=>{f({send(X){let A=X.requestId??`hub-client-${++H}`;return new Promise((Y,V)=>{j.set(A,{resolve:Y,reject:V});let B={kind:"command",envelope:{...X,requestId:A}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(X)=>{let A=JSON.parse(String(X.data));if(A.kind==="reply"&&A.envelope.requestId){let Y=j.get(A.envelope.requestId);if(Y)j.delete(A.envelope.requestId),Y.resolve(A.envelope)}}),Q.addEventListener("close",()=>{for(let X of j.values())X.reject(Error("Hub connection closed"));j.clear()}),Q.addEventListener("error",(X)=>{J(GU(X,$))})})().catch(J)})}async function i3($){try{return(await p4($)).close(),!0}catch{return!1}}async function n3($,f){let J=await pW($),W=await p4(J);try{return await W.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{W.close()}}function rW($){return $?JSON.parse(JSON.stringify($)):{}}function r4($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?rW(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 a3($,f){return $.error?.message??`hub command failed: ${f}`}function DU($){let f=rW($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...f,error:W.message.trim()};return f}function t3($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function LU($){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 OU($){let f=rW($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||t3(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||t3(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:DU($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class iW{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new s0({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=r4(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(q$(J))return;throw J}return r4(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(a3(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},f);if(!Z.ok)throw Error(a3(Z,"session.restore"));let Q=r4(Z.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,H=LU(Z.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:H}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((W)=>r4({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),W=this.client.subscribe((Z)=>{let Q=OU(Z);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;f.onEvent?.(Q)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),W}streamTeamProgress($,f){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;f.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{f.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class nW{client;constructor($){this.client=new s0({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 cw}from"@cline/llms";var TB={};w(TB,{LocalRuntimeHost:()=>F$});import{readdirSync as Ew}from"node:fs";import{homedir as bw}from"node:os";import{isAbsolute as kw,join as N7,resolve as M7}from"node:path";import{captureSdkError as Df,createSessionId as Iw,isLikelyAuthError as xw,normalizeUserInput as mw}from"@cline/shared";import{setHomeDirIfUnset as gw}from"@cline/shared/storage";L0();var zj={};w(zj,{createContextCompactionPrepareTurn:()=>L8});import{createHandlerAsync as MU}from"@cline/llms";import{estimateTokens as aW}from"@cline/shared";var e3=200000,tW=0.9,$j=16384,sW=20000,s3=1024,o3=2000,fj=2000,Jj=8;function e$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
280
- ...[truncated ${$.length-f} chars]`}function zU($){let f=oW($);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}">
277
+ WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,G0(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,G0(),f)}}function M4(f){return f?new Date(f).getTime():void 0}function kP(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function z4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:M4(f.nextRunAt),lastRunAt:M4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:kP(f)}}function IP(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function u9(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:M4(f.startedAt),endedAt:M4(f.completedAt),status:IP(f.status),errorMessage:f.error}}class x1{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new Z8({dbPath:f.dbPath}),this.materializer=new s2({store:this.store}),this.runner=new f8({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,eventPublisher:f.eventPublisher,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(f){if(g9(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return z4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?z4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>z4($))}updateSchedule(f,$){if($.cronPattern!==void 0)g9($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let Q=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule(f,{...$,scheduleId:f});return W?z4(W):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return u9(J,f)}triggerScheduleNowDetached(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;return this.runner.tick().catch(()=>{return}),u9($,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((Z)=>{let W=$??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return u9(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!f.status||Z.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,Q=0,Z=0,W;for(let j of $){if(j.status==="success"||j.status==="completed")J+=1;if(!W&&j.status!=="success"&&j.status!=="completed")W=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,Q+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,Q)=>String(J.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}t4();import{createSessionId as LF,resolveHubCommandTimeoutMs as OF}from"@cline/shared";var d3={};q(d3,{splitCoreSessionConfig:()=>P8,isSessionNotFoundError:()=>hf,SessionNotFoundError:()=>Ef,SESSION_NOT_FOUND_ERROR_CODE:()=>m$});var m$="session_not_found";class Ef extends Error{sessionId;code="session_not_found";constructor(f,$){super($??(f?`session not found: ${f}`:"session not found"));this.sessionId=f;this.name="SessionNotFoundError"}}function hf(f){return f instanceof Ef||typeof f==="object"&&f!==null&&"code"in f&&f.code==="session_not_found"}function P8(f){let{hooks:$,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:H,onConsecutiveMistakeLimitReached:X,checkpoint:A,compaction:Y,...V}=f,B={};if($)B.hooks=$;if(J)B.logger=J;if(Q)B.telemetry=Q;if(Z)B.extensionContext=Z;if(W)B.extraTools=W;if(j)B.extensions=j;if(H)B.onTeamEvent=H;if(X)B.onConsecutiveMistakeLimitReached=X;if(A?.createCheckpoint)B.checkpoint=A;if(Y?.compact)B.compaction=Y;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...A?{checkpoint:{enabled:A.enabled}}:{},...Y?{compaction:{enabled:Y.enabled,strategy:Y.strategy,thresholdRatio:Y.thresholdRatio,reserveTokens:Y.reserveTokens,preserveRecentTokens:Y.preserveRecentTokens,maxInputTokens:Y.maxInputTokens,summarizer:Y.summarizer}}:{}},...K?{localRuntime:K}:{}}}import{spawn as oG}from"node:child_process";import{closeSync as eG,mkdirSync as fF,openSync as $F}from"node:fs";import{basename as JF,dirname as QF,join as ZF}from"node:path";import{fileURLToPath as WF}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as jF,isHubDaemonProcess as Jj,withResolvedClineBuildEnv as HF}from"@cline/shared";import{createHash as SG,randomBytes as EG}from"node:crypto";import{existsSync as hG}from"node:fs";import{chmod as bG,mkdir as i9,readFile as n3,rm as n9,writeFile as a3}from"node:fs/promises";import{dirname as t3,join as a9}from"node:path";import{resolveClineDataDir as F8,resolveClineDir as s3}from"@cline/shared/storage";var p3="0.0.46";var G8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:p3,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 kG="CLINE_HUB_DISCOVERY_PATH",IG="CLINE_HUB_BUILD_ID",r3=30000,xG=15000,gG=100;function mG(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function vG(f){return SG("sha256").update(f).digest("hex").slice(0,12)}function cG(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function s4(){return EG(32).toString("hex")}function uG(f){return new Promise(($)=>setTimeout($,f))}function dG(f){return`${f}.lock`}async function lG(f){try{let $=JSON.parse(await n3(a9(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function i3(f){await n9(f,{recursive:!0,force:!0}).catch(()=>{return})}function J$(){return process.env[IG]?.trim()||String(G8.version)}function bf(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${vG(f)}`,J=process.env[kG]?.trim()||a9(F8(),"locks","hub","owners",`${mG($)}.json`);return{ownerId:$,discoveryPath:J}}function o3(f=`hub-${Date.now().toString(36)}`){return bf(f)}async function V0(f){try{let $=JSON.parse(await n3(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function o4(f,$){await i9(t3(f),{recursive:!0}),await n9(f,{force:!0}).catch(()=>{return}),await a3(f,`${JSON.stringify($,null,2)}
278
+ `,{encoding:"utf8",mode:384}),await bG(f,384)}async function x0(f){await n9(f,{force:!0}).catch(()=>{return})}async function e4(f,$){let J=dG(f);await i9(t3(J),{recursive:!0});let Q=Date.now()+xG;while(!0)try{await i9(J,{recursive:!1}),await a3(a9(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
279
+ `,"utf8");try{return await $()}finally{await i3(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await lG(J),H=j?Date.now()-Date.parse(j.acquiredAt):r3+1;if(!j||!cG(j.pid)||H>r3){await i3(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await uG(gG)}}async function Hf(f){try{let $=await fetch(t9(f));if(!$.ok)return;return await $.json()}catch{return}}function o0(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function t9(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function e3(f){return hG(f)}import{CLINE_HUB_DEV_PORT as pG,CLINE_HUB_PORT as rG,resolveClineBuildEnv as iG}from"@cline/shared";var nG="CLINE_HUB_HOST",aG="CLINE_HUB_PORT",tG="CLINE_HUB_PATHNAME",s9="127.0.0.1",o9=rG,e9="/hub";function fj(f){return iG(f)==="development"?pG:o9}function fQ(f={}){return(f.env??process.env)[nG]?.trim()||s9}function d1(f={}){let J=(f.env??process.env)[aG]?.trim();if(!J)return fj(f);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return fj(f);return Q}function $Q(f={}){return(f.env??process.env)[tG]?.trim()||e9}function Xf(f={},$={}){return{host:f.host??fQ($),port:f.port??d1($),pathname:f.pathname??$Q($)}}var sG="shared:cline";function $j(f){let $=Mf(f.trim());return bf(`workspace:${$||f.trim()}`)}function F0(f=sG){return bf(f)}var XF=8000,AF=200,YF=3000,VF=100,BF=[100,250,500,1000,2000],KF="--cline-hub-daemon";function PF(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function GF(){try{let f=ZF(F8(),"logs","hub-daemon.log");return fF(QF(f),{recursive:!0}),{fd:$F(f,"a"),logPath:f}}catch{return}}function U8(f){let $=f.buildId?.trim();return!!$&&$===J$()}async function v$(f){try{return await Hf(f)}catch{return}}async function FF(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await v$(f))?.url)return!0;await new Promise((Z)=>setTimeout(Z,VF))}return!1}async function R8(f,$){if(U8(f))return;if(await D8(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await FF(f.url,YF),await x0($).catch(()=>{return})}function UF(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return WF(new URL(`./entry.${f}`,import.meta.url))}function RF(f,$){let J=UF(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=JF(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),H=W?[KF]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...H,"--cwd",f,...PF($)],cwd:f,env:{...HF(process.env),CLINE_NO_INTERACTIVE:"1",[jF]:"1"}}}function DF(f){if(!f||typeof f!=="object")return!1;if(("code"in f?f.code:void 0)==="ETXTBSY")return!0;let J="message"in f?f.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function JQ(f,$={}){if(Jj())return;let J=RF(f,$),Q=GF();try{oG(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(Q)eG(Q.fd)}}async function l1(f,$={}){for(let J=0;;J++)try{JQ(f,$);return}catch(Q){let Z=BF[J];if(!DF(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function f6(f,$={}){if(Jj())return;let J=F0(),Q=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=Xf($),W=o0(Z.host,Z.port,Z.pathname);V0(J.discoveryPath).then(async(j)=>{if(j?.url){let Y=await v$(j.url);if(Y?.url&&U8(Y)&&await Af(Y.url,{authToken:j.authToken}))return;if(Y?.url)await R8({...Y,authToken:j.authToken},J.discoveryPath);else await x0(J.discoveryPath).catch(()=>{return})}let H=await v$(W);if(H?.url)await R8(H,J.discoveryPath);let A=!Q&&Z.port!==0?{...Z,port:0}:Z;await l1(f,A)}).catch(()=>{})}async function Qj(f,$={}){let J=F0(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=Xf($),j=o0(W.host,W.port,W.pathname),H=(K)=>{if(!Q)Q$(K.url,K.authToken);return K},X=await V0(J.discoveryPath);if(X?.url){let K=await v$(X.url);if(K?.url&&U8(K)&&await Af(K.url,{authToken:X.authToken}))return H({url:K.url,authToken:X.authToken});if(K?.url)await R8({...K,authToken:X.authToken},J.discoveryPath);else await x0(J.discoveryPath).catch(()=>{return})}let A=await v$(j);if(A?.url)await R8(A,J.discoveryPath);let V=!Z&&W.port!==0?{...W,port:0}:W;await l1(f,V);let B=Date.now()+XF;while(Date.now()<B){let K=await V0(J.discoveryPath);if(K?.url){let R=await v$(K.url);if(R?.url&&U8(R)&&await Af(R.url,{authToken:K.authToken}))return H({url:R.url,authToken:K.authToken})}let P=await v$(j);if(P?.url&&!U8(P))await R8(P,J.discoveryPath);await new Promise((R)=>setTimeout(R,AF))}throw Error("Timed out waiting for detached hub startup.")}function _F(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function Xj(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return Xj(f.data);return String(f)}function TF(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function Zj(f){let $=f,J=TF($.reason);return new T0("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:QQ,{closeCode:$.code,closeReason:J||void 0})}function zF(f,$){if(f instanceof T0)return f;if(f instanceof Error)return new T0("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new T0("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new T0("hub_connect_failed",J);let Q=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new T0("hub_connect_failed",Q?`Failed to connect to hub at ${$.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var MF=8000,NF=200,Wj="*",jj=8000,qF="cline-hub-auth.",Aj=new Map,Yj=new Set,yF=3000,wF=3000,CF=100,QQ="Hub connection closed",SF=250,EF=5000,Hj=0.5;class T0 extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function jQ(f){return f instanceof T0}class p1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function $6(f,$){return f instanceof p1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function Vj(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=HQ(f.toString());return J?Aj.get(J):void 0}function hF(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function HQ(f){if(!hF(f))return;let $=new URL(Z$(f));return $.search="",$.hash="",$.toString()}function ZQ(f){let $=HQ(f);return!!$&&Yj.has($)}function Q$(f,$){let J=HQ(f);if(J){if(Yj.add(J),$?.trim())Aj.set(J,$)}return f}class e0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new T0("hub_connection_closed",QQ);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||Vj(f);f.hash="";let Q=new(_F())(f.toString(),$?[`${qF}${$}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let H=!1,X=setTimeout(()=>{if(H)return;H=!0,Z=!0,this.lastCloseError=new T0("hub_connect_timeout",`Timed out connecting to hub after ${jj}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},jj);Q.addEventListener("open",()=>{if(H)return;H=!0,clearTimeout(X),W()}),Q.addEventListener("error",(A)=>{if(H)return;H=!0,clearTimeout(X),this.lastCloseError=zF(A,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(A)=>{if(H)return;if(H=!0,clearTimeout(X),!Z)this.lastCloseError=Zj(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(Xj(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=Zj(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,Q={listener:f,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,Q){let Z=0,W=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce(f,$,J,Q){await this.connect();let Z=LF("hubreq_"),W=OF(f,Q?.timeoutMs),j=new Promise((X,A)=>{let Y=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;A(new p1(f,"hub_command_timeout",`Hub command ${f} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(V)=>{if(Y)clearTimeout(Y);X(V)},reject:(V)=>{if(Y)clearTimeout(Y);A(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:$}})}catch(X){throw this.pendingReplies.delete(Z),X}let H=await j;if(!H.ok){if(H.error?.code===m$){let X=J??(typeof $?.sessionId==="string"?$.sessionId:void 0);throw new Ef(X,H.error.message)}throw new p1(f,H.error?.code,H.error?.message??`Hub command ${f} failed`)}return H}async recoverLocalHubTransport(f){if(!ZQ(this.currentUrl)||!jQ(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await c$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let f=Math.min(SF*2**this.reconnectAttempt,EF),$=Math.round(f*(1-Hj)+Math.random()*f*Hj);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!ZQ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await c$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new T0("hub_connection_closed",QQ),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new T0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),Q=(this.subscriptionCounts.get(J)??0)+$;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,Q),$>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??Wj}subscriptionSessionIdFromKey(f){return f===Wj?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Z$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function Af(f,$){let J=new e0({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function WQ(f,$){let J=Z$(f),Q=await Hf(J);if(!Q)return{status:"unreachable",url:J};let Z=J$(),W=Q.buildId?.trim();if(!W||W!==Z)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await Af(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function bF(f){let $=Date.now()+MF;while(Date.now()<$){let J=await V0(f.discoveryPath);if(J?.url){let Q=await WQ(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return Q$(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,NF))}return}async function kF(f){let $=Date.now()+wF;while(Date.now()<$){if(!(await Hf(f).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,CF))}return!1}function IF(f,$){try{return Z$(f)===Z$($)}catch{return!1}}function xF(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function gF(f,$,J){let Q=new e0({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:yF});return!xF(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function L8(f={}){if(f.endpoint?.trim()){let Z=await WQ(f.endpoint);return Z.status==="compatible"?Z.url:void 0}let $=F0(),J=await V0($.discoveryPath);if(!J?.url)return;let Q=await WQ(J.url);if(Q.status==="compatible")return Q$(Q.url,J.authToken);if(Q.status==="build_mismatch")await x0($.discoveryPath).catch(()=>{return});return}async function c$(f={}){let $=await L8(f);if($&&await Af($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=F0();return await l1(f.workspaceRoot??process.cwd()),await bF(J)}async function D8(f,$){let J=new URL(f),Q=$?.trim()||Vj(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 XQ(){let f=F0(),$=await V0(f.discoveryPath);if(!$?.url)return!1;try{if(await D8($.url,$.authToken))return!0}catch{}return!1}async function J6(f){if(!ZQ(f.url))return;let $=F0(),J=await V0($.discoveryPath);if(!J?.url||!IF(J.url,f.url))return;if(!await gF(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await XQ())return;if(!await kF(J.url))return;return await x0($.discoveryPath).catch(()=>{return}),await c$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}function mF(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var vF="cline-hub-auth.";function cF(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function uF(f,$){let J=new URL(f),Q=new URL($);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}async function dF(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=F0(),Q=await V0(J.discoveryPath);if(Q?.url&&uF(f.toString(),Q.url))return Q.authToken;return}async function AQ(f={}){let $=Xf(f);if(!cF(f)){let J=F0(),Q=await V0(J.discoveryPath);if(Q?.url)return Q.url}return o0($.host,$.port,$.pathname)}async function Q6(f){return await new Promise(($,J)=>{(async()=>{let Q=new URL(f),Z=await dF(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${vF}${Z}`]:void 0),j=new Map,H=0;W.addEventListener("open",()=>{$({send(X){let A=X.requestId??`hub-client-${++H}`;return new Promise((Y,V)=>{j.set(A,{resolve:Y,reject:V});let B={kind:"command",envelope:{...X,requestId:A}};W.send(JSON.stringify(B))})},close(){W.close()}})}),W.addEventListener("message",(X)=>{let A=JSON.parse(String(X.data));if(A.kind==="reply"&&A.envelope.requestId){let Y=j.get(A.envelope.requestId);if(Y)j.delete(A.envelope.requestId),Y.resolve(A.envelope)}}),W.addEventListener("close",()=>{for(let X of j.values())X.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(X)=>{J(mF(X,f))})})().catch(J)})}async function Bj(f){try{return(await Q6(f)).close(),!0}catch{return!1}}async function Kj(f,$){let J=await AQ(f),Q=await Q6(J);try{return await Q.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{Q.close()}}function YQ(f){return f?JSON.parse(JSON.stringify(f)):{}}function Z6(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?YQ($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function Pj(f,$){return f.error?.message??`hub command failed: ${$}`}function lF(f){let $=YQ(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,error:J.text.trim()};let Q=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...$,error:Q.message.trim()};return $}function Gj(f){let $=f?.sessionId;return typeof $==="string"&&$.trim()?$.trim():void 0}function pF(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function rF(f){let $=YQ(f.payload);if(f.event==="schedule.execution_completed")return{sessionId:f.sessionId?.trim()||Gj($)||"",eventType:"schedule.execution.completed",payload:$};if(f.event==="schedule.execution_failed")return{sessionId:f.sessionId?.trim()||Gj($)||"",eventType:"schedule.execution.failed",payload:$};let J=f.sessionId?.trim();if(!J)return;switch(f.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:$};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:$};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:$};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:$};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:$};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:$};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:$};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:$};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:lF(f.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:$};default:return}}class VQ{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new e0({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=Z6($.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession(f,$,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,mode:$.config.mode,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $;try{$=await this.client.command("session.get",void 0,f)}catch(J){if(hf(J))return;throw J}return Z6($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(Pj(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=f.config,Z=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},$);if(!Z.ok)throw Error(Pj(Z,"session.restore"));let W=Z6(Z.payload);if(J&&!W?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,H=pF(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:H}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((Q)=>Z6({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=rF(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;$.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{$.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}streamTeamProgress(f,$){let J=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;$.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{$.onError?.(Q instanceof Error?Q:Error(String(Q)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class BQ{client;constructor(f){this.client=new e0({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as SC}from"@cline/llms";var iB={};q(iB,{LocalRuntimeHost:()=>Df});import{readdirSync as _C}from"node:fs";import{homedir as TC}from"node:os";import{isAbsolute as zC,join as l7,resolve as p7}from"node:path";import{captureSdkError as q1,createSessionId as MC,isLikelyAuthError as NC,normalizeUserInput as qC}from"@cline/shared";import{setHomeDirIfUnset as yC}from"@cline/shared/storage";var dj={};q(dj,{saveProviderOAuthCredentials:()=>l$,resolveProviderApiKeyFromSettings:()=>zQ,loginAndSaveProviderOAuthCredentials:()=>y8,isOAuthProvider:()=>d$,getProviderOAuthCredentialsFromSettings:()=>w8,getProviderAuthStorageId:()=>TQ,getProviderAuthHandler:()=>B0,getPersistedProviderApiKey:()=>F6,formatProviderOAuthApiKey:()=>MQ});import{getClineEnvironmentConfig as uj}from"@cline/shared";O0();var Mj={};q(Mj,{startClineDeviceAuth:()=>RQ,refreshClineToken:()=>X6,loginClineOAuth:()=>O8,getValidClineCredentials:()=>_8,completeClineDeviceAuth:()=>DQ});import{getClineEnvironmentConfig as KQ}from"@cline/shared";var Fj={};q(Fj,{startLocalOAuthServer:()=>ff});function iF(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function ff(f){let $=await import("node:http"),J=f.host??"127.0.0.1",Q=f.timeoutMs??300000,Z=f.successHtml??nF,W=iF(),j=!1,H=null,X=null,A=null,Y=(K)=>{if(j)return;j=!0,W.resolve(K)},V=()=>{if(H)clearTimeout(H),H=null;let K=A;if(A=null,X)X.close(),X=null;if(K!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return H=setTimeout(()=>{V(),Y(null)},Q),W.promise};for(let K of f.ports){let P=$.createServer((G,F)=>{try{let U=new URL(G.url||"",`http://${J}:${K}`);if(U.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let _={url:U,code:U.searchParams.get("code")??void 0,state:U.searchParams.get("state")??void 0,provider:U.searchParams.get("provider")??void 0,error:U.searchParams.get("error")??void 0};if(_.error){F.statusCode=400,F.end(`Authentication failed: ${_.error}`),V(),Y(_);return}if(!_.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&_.state!==f.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(Z),V(),Y(_)}catch{F.statusCode=500,F.end("Internal error")}}),R=await new Promise((G)=>{let F=(U)=>{P.off("error",F),G({bound:!1,error:U})};P.once("error",F),P.listen(K,J,()=>{P.off("error",F),X=P,G({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){A=K;let G=`http://${J}:${K}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:K,callbackUrl:G})).catch(()=>{});return{callbackUrl:G,waitForCallback:B,cancelWait:()=>{V(),Y(null)},close:()=>{V(),Y(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var nF=`<!DOCTYPE html>
280
+ <html lang="en">
281
+ <head>
282
+ <meta charset="utf-8">
283
+ <meta name="viewport" content="width=device-width, initial-scale=1">
284
+ <title>Authentication Successful</title>
285
+ <style>
286
+ * { margin: 0; padding: 0; box-sizing: border-box; }
287
+ body {
288
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
289
+ min-height: 100vh;
290
+ display: flex;
291
+ align-items: center;
292
+ justify-content: center;
293
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
294
+ color: #fff;
295
+ }
296
+ .container { text-align: center; padding: 48px; max-width: 420px; }
297
+ .icon {
298
+ width: 72px; height: 72px; margin: 0 auto 24px;
299
+ background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%);
300
+ border-radius: 50%;
301
+ display: flex; align-items: center; justify-content: center;
302
+ }
303
+ .icon svg { width: 36px; height: 36px; stroke: #fff; stroke-width: 3; fill: none; }
304
+ h1 { font-size: 24px; font-weight: 600; margin-bottom: 12px; }
305
+ p { font-size: 15px; color: rgba(255,255,255,0.7); line-height: 1.5; }
306
+ .closing { margin-top: 32px; font-size: 13px; color: rgba(255,255,255,0.5); }
307
+ </style>
308
+ </head>
309
+ <body>
310
+ <div class="container">
311
+ <div class="icon">
312
+ <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
313
+ </div>
314
+ <h1>Authentication Successful</h1>
315
+ <p>You're now signed in. You can close this window.</p>
316
+ <p class="closing">This window will close automatically...</p>
317
+ </div>
318
+ <script>setTimeout(() => window.close(), 3000);</script>
319
+ </body>
320
+ </html>`;function Uj(f){let $="";for(let J=0;J<f.length;J+=1)$+=String.fromCharCode(f[J]??0);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function aF(f){let J=new TextEncoder().encode(f),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function tF(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),Uj($)}async function W6(){let f=tF(),$=Uj(await aF(f));return{verifier:f,challenge:$}}function j6(f){return f.endsWith("/")?f.slice(0,-1):f}function u$(f,$){return new URL($,`${j6(f)}/`).toString()}function r1(f,$={}){let J=f.trim();if(!J)return{};try{let Q=new URL(J);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:$.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if($.allowHashCodeState&&J.includes("#")){let[Q,Z]=J.split("#",2);return{code:Q||void 0,state:Z||void 0}}if(J.includes("code=")){let Q=new URLSearchParams(J);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:$.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function sF(f){if(typeof atob==="function")try{return atob(f)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from(f,"base64").toString("utf8")}catch{return null}return null}function z0(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=sF(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function i1(f){try{let $=JSON.parse(f),J=$.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function n1(f,$){return Date.now()>=f.expires-$}async function a1(f){if(!f.onManualCodeInput){let W=await f.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let $,J,Q=f.onManualCodeInput().then((W)=>{$=W,f.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),f.cancelWait()}),Z=await f.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if($)return r1($,f.parseOptions);if(await Q,J)throw J;if($)return r1($,f.parseOptions);return{}}var H6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},Oj={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},PQ="https://api.workos.com",oF="/auth",Rj=Array.from({length:11},(f,$)=>48801+$),eF=300000,fU=30000,t1=30000,$U=300,JU=5;class W$ extends Error{status;errorCode;constructor(f,$){super(f);this.name="ClineOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function QU(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function GQ(f,$,J={}){let Q=f.userInfo.clineUserId??J.accountId,Z=f.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:Z,expires:QU(f.expiresAt),accountId:Q??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function FQ(f){if(!f)return{};return typeof f==="function"?await f():f}function Dj(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function Lj(f){await new Promise(($)=>setTimeout($,f))}function UQ(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function _j(f,$){let J=await fetch(u$(PQ,Oj.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??t1)}),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:Dj(Q.expires_in,$U),pollIntervalSeconds:Dj(Q.interval,JU)}}async function Tj(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let Q=await fetch(u$(f.workosApiBaseUrl,Oj.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:f.deviceCode,client_id:f.clientId}),signal:AbortSignal.timeout(f.requestTimeoutMs)}),Z=await Q.json().catch(()=>({}));if(Q.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await Lj(J*1000);break}case"slow_down":{J+=1,await Lj(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})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function zj(f,$,J){let Q={accessToken:f.accessToken,refreshToken:f.refreshToken},Z=await fetch(u$($.apiBaseUrl,H6.register),{method:"POST",headers:{"Content-Type":"application/json",...await FQ($.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout($.requestTimeoutMs??t1)});if(!Z.ok){let j=await Z.text().catch(()=>""),H=i1(j);throw new W$(`Token registration failed: ${Z.status}${H.message?` - ${H.message}`:""}`,{status:Z.status,errorCode:H.code})}let W=await Z.json();return GQ(UQ(W,"Invalid token exchange response"),J??$.provider)}async function ZU(f,$,J,Q){let Z={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:Q??J.provider},W=await fetch(u$(J.apiBaseUrl,H6.token),{method:"POST",headers:{"Content-Type":"application/json",...await FQ(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??t1)});if(!W.ok){let H=await W.text().catch(()=>""),X=i1(H);throw new W$(`Token exchange failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return GQ(UQ(j,"Invalid token exchange response"),Q??J.provider)}async function O8(f){Nf(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:Rj,Q=f.callbackPath??oF,Z=$?null:await ff({ports:J,callbackPath:Q,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??Rj[0]}${Q}`;try{let j;if($){let H=KQ().workOsClientId,X=await _j(H,f);f.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await Tj({clientId:H,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??t1,workosApiBaseUrl:PQ,onProgress:f.callbacks.onProgress});j=await zj(A,f,f.provider)}else{let H=new URL(u$(f.apiBaseUrl,H6.authorize));H.searchParams.set("client_type","extension"),H.searchParams.set("callback_url",W),H.searchParams.set("redirect_uri",W),f.callbacks.onAuth({url:H.toString(),instructions:"Continue the authentication process in your browser."});let X,A=f.provider,Y=await a1({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(Y.error)throw Error(`OAuth error: ${Y.error}`);if(X=Y.code,A=Y.provider??A,!X){let V=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=r1(V,{includeProvider:!0});X=B.code,A=B.provider??A}if(!X)throw Error("Missing authorization code");j=await ZU(X,W,f,A)}return qf(f.telemetry,f.provider??"cline"),wf(f.telemetry,{id:j.accountId,email:j.email,provider:f.provider??"cline"}),j}catch(j){throw yf(f.telemetry,f.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function RQ(f){return await _j(KQ().workOsClientId,f)}async function DQ(f){let $=f.provider??"cline";Nf(f.telemetry,$);try{let J=await Tj({clientId:KQ().workOsClientId,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??t1,workosApiBaseUrl:PQ}),Q=await zj(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return qf(f.telemetry,$),wf(f.telemetry,{id:Q.accountId,email:Q.email,provider:$}),Q}catch(J){throw yf(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function X6(f,$){let J=await fetch(u$($.apiBaseUrl,H6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await FQ($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??t1)});if(!J.ok){let W=await J.text().catch(()=>""),j=i1(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=f.metadata?.provider??$.provider;return GQ(UQ(Q,"Invalid token refresh response"),Z,f)}async function _8(f,$,J){if(!f)return null;let Q=J?.refreshBufferMs??eF,Z=J?.retryableTokenGraceMs??fU;if(J?.forceRefresh!==!0&&!n1(f,Q))return f;try{return await X6(f,$)}catch(j){if(j instanceof W$&&j.isLikelyInvalidGrant())return f$($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>Z)return f;return null}}O0();var qj={};q(qj,{refreshOpenAICodexToken:()=>Y6,loginOpenAICodex:()=>T8,getValidOpenAICodexCredentials:()=>z8,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as WU}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 A6 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OpenAICodexOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function jU(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:f,code_verifier:$,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 HU(f){try{let $=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!$.ok){let Q=await $.text().catch(()=>""),Z=i1(Q);throw new A6(`Token refresh failed: ${$.status}${Z.message?` - ${Z.message}`:""}`,{status:$.status,errorCode:Z.code})}let J=await $.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch($){if($ instanceof A6)throw $;return{type:"failed"}}}async function XU(f="pi"){let{verifier:$,challenge:J}=await W6(),Q=WU(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",f),{verifier:$,state:Q,url:Z.toString()}}function AU(){try{let f=new URL(e.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):e.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:e.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function YU(f,$){let J=$?z0($):z0(f),Q=J?J:z0(f),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 X=j[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let H=Q?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;return null}function Nj(f,$){let J=YU(f.access,f.idToken)??$?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:f.access,refresh:f.refresh||$?.refresh||"",expires:f.expires,accountId:J,email:f.email??$?.email,metadata:{...$?.metadata??{},provider:"openai-codex"}}}async function T8(f){Nf(f.telemetry,"openai-codex");let $=AU(),{verifier:J,state:Q,url:Z}=await XU(f.originator),W=await ff({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:Q});f.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let H=await a1({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(H.state&&H.state!==Q)throw Error("State mismatch");if(j=H.code,!j){let Y=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=r1(Y,{allowHashCodeState:!0});if(V.state&&V.state!==Q)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let X=await jU(j,J,$.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=Nj(X);return qf(f.telemetry,"openai-codex"),wf(f.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(H){throw yf(f.telemetry,"openai-codex",H instanceof Error?H.message:String(H)),H}finally{W.close()}}async function Y6(f,$){let J=await HU(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=Nj(J,$);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function z8(f,$){if(!f)return null;let J=$?.refreshBufferMs??e.refreshBufferMs,Q=$?.retryableTokenGraceMs??e.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!n1(f,J))return f;try{return await Y6(f.refresh,f)}catch(W){if(W instanceof A6&&W.isLikelyInvalidGrant())return f$($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>Q)return f;return null}}O0();var cj={};q(cj,{refreshOcaToken:()=>P6,loginOcaOAuth:()=>N8,getValidOcaCredentials:()=>q8,OCI_HEADER_OPC_REQUEST_ID:()=>VU,DEFAULT_INTERNAL_OCA_BASE_URL:()=>V6,DEFAULT_INTERNAL_IDCS_URL:()=>Cj,DEFAULT_INTERNAL_IDCS_SCOPES:()=>Sj,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>wj,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>B6,DEFAULT_EXTERNAL_IDCS_URL:()=>hj,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>bj,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>Ej});import{nanoid as yj}from"nanoid";class LQ{ttlMs;maxEntries;entries=new Map;constructor(f,$){this.ttlMs=f;this.maxEntries=$}get(f,$=Date.now()){this.pruneExpired($);let J=this.entries.get(f);if(!J)return;return this.entries.delete(f),this.entries.set(f,J),J.value}set(f,$,J=Date.now(),Q=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set(f,{value:$,expiresAt:J+Q})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var wj="a8331954c0cf48ba99b5dd223a14c6ea",Cj="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",Sj="openid offline_access",V6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Ej="c1aba3deed5740659981a752714eba33",hj="https://login-ext.identity.oraclecloud.com",bj="openid offline_access",B6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",VU="opc-request-id",BU="/auth/oca",KU=Array.from({length:11},(f,$)=>48801+$),PU=300000,GU=30000,kj=30000,FU=600000;class K6 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OcaOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var j$={internal:{clientId:wj,idcsUrl:Cj,scopes:Sj,baseUrl:V6},external:{clientId:Ej,idcsUrl:hj,scopes:bj,baseUrl:B6}},M8=new Map,UU=86400000,RU=300000,DU=32,OQ=new LQ(UU,DU);function Ij(f){if(typeof f==="function")return f();return f??"internal"}function xj(f){return{internal:{clientId:f?.internal?.clientId??j$.internal.clientId,idcsUrl:f?.internal?.idcsUrl??j$.internal.idcsUrl,scopes:f?.internal?.scopes??j$.internal.scopes,baseUrl:f?.internal?.baseUrl??j$.internal.baseUrl},external:{clientId:f?.external?.clientId??j$.external.clientId,idcsUrl:f?.external?.idcsUrl??j$.external.idcsUrl,scopes:f?.external?.scopes??j$.external.scopes,baseUrl:f?.external?.baseUrl??j$.external.baseUrl}}}function LU(f=Date.now()){let $=f-FU;for(let[J,Q]of M8.entries())if(Q.createdAt<$)M8.delete(J)}function OU(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let Z=z0($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=z0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function gj(f,$,J){let Q=f.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=f.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=z0(f.id_token),j=z0(Q),H=W?.sub??j?.sub,X=W?.email??j?.email;return{access:Q,refresh:Z,expires:OU(f,Q,f.id_token),accountId:H??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:H,idToken:f.id_token}}}async function mj(f,$){let J=j6(f),Q=OQ.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout($)});if(!W.ok){let X=`${J}/oauth2/v1/token`;return OQ.set(J,X,Date.now(),RU),X}let H=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return OQ.set(J,H),H}function vj(f){return{code:f.error,message:f.error_description}}async function _U(f){let $=M8.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");M8.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,Q=await mj(J.idcsUrl,f.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout(f.requestTimeoutMs)}),j=await W.json();if(!W.ok){let X=vj(j);throw new K6(`Token exchange failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let H=z0(j.id_token);if(!j.id_token||!H)throw Error("No ID token received from OCA");if(H.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return gj(j,f.mode)}function TU(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${j6($.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",$.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",$.scopes),J.searchParams.set("code_challenge",f.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",f.callbackUrl),J.searchParams.set("state",f.state),J.searchParams.set("nonce",f.nonce),J.toString()}async function N8(f){Nf(f.telemetry,"oca");let $=xj(f.config),J=Ij(f.mode),Q=f.callbackPorts?.length?f.callbackPorts:KU,Z=f.callbackPath??BU,W=f.requestTimeoutMs??kj,j=await ff({ports:Q,callbackPath:Z,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),H=j.callbackUrl;if(!H)throw Error("Unable to bind local OAuth callback server");let X=yj(16),A=yj(16),{verifier:Y,challenge:V}=await W6();LU(),M8.set(X,{verifier:Y,nonce:A,mode:J,redirectUri:H,createdAt:Date.now()});let B=TU({callbackUrl:H,mode:J,state:X,nonce:A,challenge:V,config:$});f.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await a1({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),P=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!P){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==X)throw Error("State mismatch");let G=await _U({code:P,state:R,mode:J,config:$,requestTimeoutMs:W});return qf(f.telemetry,"oca"),wf(f.telemetry,{id:G.accountId,email:G.email,provider:"oca"}),G}catch(K){throw yf(f.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function P6(f,$={}){let J=xj($.config),Q=$.requestTimeoutMs??kj,Z=f.metadata?.mode,W=Z==="internal"||Z==="external"?Z:Ij($.mode),j=W==="external"?J.external:J.internal,H=await mj(j.idcsUrl,Q),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:j.clientId}),A=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(Q)}),Y=await A.json();if(!A.ok){let V=vj(Y);throw new K6(`Token refresh failed: ${A.status}${V.message?` - ${V.message}`:""}`,{status:A.status,errorCode:V.code})}return gj(Y,W,f)}async function q8(f,$,J){if(!f)return null;let Q=$?.refreshBufferMs??J?.refreshBufferMs??PU,Z=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??GU;if($?.forceRefresh!==!0&&!n1(f,Q))return f;try{return await P6(f,J)}catch(j){if(j instanceof K6&&j.isLikelyInvalidGrant())return f$(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>Z)return f;return null}}var G6="workos:";function zU(f){let $=f.trim();return $.toLowerCase().startsWith(G6)?$:`${G6}${$}`}function MU(f){let $=f.trim();return $.toLowerCase().startsWith(G6)?$.slice(G6.length):$}function NU(f){let J=z0(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function qU(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=NU($);if(Q)return Q;return Date.now()-1}function yU(f,$){let J=f.auth?.accessToken?.trim(),Q=f.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=$?.normalizeAccessToken?.(J)??J;if(!Z)return null;return{access:Z,refresh:Q,expires:qU(f,Z),accountId:f.auth?.accountId}}function wU(f){let $=f.formatAccessToken?.(f.credentials.access)??f.credentials.access,J={...f.settings?.auth??{},accessToken:$,refreshToken:f.credentials.refresh,accountId:f.credentials.accountId,expiresAt:f.credentials.expires},Q={...f.settings??{provider:f.storageProviderId},provider:f.storageProviderId,auth:J};if(f.save!==!1)f.manager.saveProviderSettings(Q,{...f.setLastUsed===void 0?{}:{setLastUsed:f.setLastUsed},tokenSource:"oauth"});return Q}function _Q(f){let $=f.storageProviderId??f.providerId;return{providerId:f.providerId,storageProviderId:$,getApiKey(J){let Q=J?.auth?.accessToken?.trim();if(Q)return f.formatAccessToken?.(Q)??Q;return J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0},login:f.login,refresh:f.refresh,saveCredentials(J){return wU({...J,storageProviderId:$,formatAccessToken:f.formatAccessToken})},isConfigured(J){return!!J?.auth?.accessToken},normalizeStoredAccessToken:f.normalizeStoredAccessToken}}var CU=[_Q({providerId:"cline",formatAccessToken:zU,normalizeStoredAccessToken:MU,login:({settings:f,callbacks:$,telemetry:J})=>O8({apiBaseUrl:f?.baseUrl?.trim()||uj().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:$,telemetry:J}),refresh:({settings:f,credentials:$,forceRefresh:J,telemetry:Q})=>_8($,{apiBaseUrl:f.baseUrl?.trim()||uj().apiBaseUrl,telemetry:Q},{forceRefresh:J})}),_Q({providerId:"oca",login:({settings:f,callbacks:$,telemetry:J})=>N8({mode:f?.oca?.mode,callbacks:$,telemetry:J}),refresh:({settings:f,credentials:$,forceRefresh:J,telemetry:Q})=>q8($,{forceRefresh:J,telemetry:Q},{mode:f.oca?.mode,telemetry:Q})}),_Q({providerId:"openai-codex",login:({callbacks:f,telemetry:$})=>T8({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput,telemetry:$}),refresh:({credentials:f,forceRefresh:$,telemetry:J})=>z8(f,{forceRefresh:$,telemetry:J})})],SU=new Map(CU.map((f)=>[f.providerId,f]));function B0(f){return SU.get(f.trim().toLowerCase())}function d$(f){return B0(f)!==void 0}function TQ(f){return B0(f)?.storageProviderId}function zQ(f,$){let J=B0($),Q=J?.storageProviderId??$,Z=f.getProviderSettings(Q);return J?.getApiKey(Z)??F6($,Z)}async function y8(f,$,J){let Q=B0($);if(!Q)throw Error(`Provider "${$}" does not support OAuth login`);let Z=f.getProviderSettings(Q.storageProviderId),W=await Q.login({settings:Z,callbacks:J.callbacks,telemetry:J.telemetry});return Q.saveCredentials({manager:f,settings:Z,credentials:W})}function w8(f,$){let J=B0(f);if(!J)return null;return yU($,{normalizeAccessToken:J.normalizeStoredAccessToken})}function l$(f){let $=B0(f.providerId);if(!$)throw Error(`Provider "${f.providerId}" does not support OAuth credentials`);return $.saveCredentials({manager:f.manager,settings:f.settings,credentials:f.credentials,setLastUsed:f.setLastUsed,save:f.save})}function F6(f,$){let J=B0(f);if(J)return J.getApiKey($);return $?.auth?.accessToken?.trim()||$?.apiKey?.trim()||$?.auth?.apiKey?.trim()||void 0}function MQ(f,$){let J=B0(f);if(!J)return $.access;return J.getApiKey({provider:J.storageProviderId,auth:{accessToken:$.access}})??$.access}O0();var GH={};q(GH,{createContextCompactionPrepareTurn:()=>k8});import{createHandlerAsync as IU}from"@cline/llms";import{estimateTokens as NQ}from"@cline/shared";var rj=200000,qQ=0.9,ij=16384,yQ=20000,lj=1024,pj=2000,nj=2000,aj=8;function H$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
321
+ ...[truncated ${f.length-$} chars]`}function EU(f){let $=wQ(f);if(typeof $==="string")return $;return $.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
281
322
  ${J.content}
282
323
  </file>`;case"image":return`[image:${J.mediaType}]`;default:return""}}).join(`
283
- `)}function oW($){if(typeof $==="string")return e$($,o3);return $.map((f)=>{switch(f.type){case"text":return{...f,text:e$(f.text,o3)};case"file":return{...f,content:e$(f.content,fj)};case"image":return f;default:return f}})}function _U($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function Wj($){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]: ${e$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${_U(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${zU(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${e$(J.content,fj)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
284
- `)}function Zj($){return $.map(Wj).join(`
324
+ `)}function wQ(f){if(typeof f==="string")return H$(f,pj);return f.map(($)=>{switch($.type){case"text":return{...$,text:H$($.text,pj)};case"file":return{...$,content:H$($.content,nj)};case"image":return $;default:return $}})}function hU(f){return Object.entries(f).map(([$,J])=>`${$}=${JSON.stringify(J)}`).join(", ")}function tj(f){if(typeof f.content==="string")return`[${f.role==="user"?"User":"Bot"}]: ${f.content}`;let $=[];for(let J of f.content)switch(J.type){case"text":$.push(`[${f.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":$.push(`[Bot thinking]: ${H$(J.thinking,2000)}`);break;case"redacted_thinking":$.push("[Bot thinking]: [redacted]");break;case"tool_use":$.push(`[Bot tool calls]: ${J.name}(${hU(J.input)})`);break;case"tool_result":$.push(`[Tool result]: ${EU(J.content)}`);break;case"file":$.push(`[${f.role==="user"?"User":"Bot"} file ${J.path}]: ${H$(J.content,nj)}`);break;case"image":$.push(`[${f.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return $.join(`
325
+ `)}function sj(f){return f.map(tj).join(`
285
326
 
286
- `).trim()}function Qj(){let $=new WeakMap;return(f)=>{let J=f,W=$.get(J);if(typeof W==="number")return W;let Z;try{Z=JSON.stringify(f)}catch{Z=Wj(f)}let Q=aW(Z.length);return $.set(J,Q),Q}}function F8($){return $.metadata?.kind==="compaction_summary"}function eW($){if(!F8($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function TU($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function R8($){return $.role==="user"&&!TU($)&&!F8($)}function jj($){for(let f=0;f<$.length;f+=1)if(R8($[f]))return f;return-1}function i4($){for(let f=$.length-1;f>=0;f-=1)if(R8($[f]))return f;return 0}function Hj($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function Xj($){for(let f=$.length-1;f>=0;f-=1)if(F8($[f]))return f;return-1}function Aj($,f,J){let W=i4($);if(W<=0)return 0;let Z=0,Q=$.length;for(let H=$.length-1;H>=0;H-=1)if(Z+=J($[H]),Q=H,Z>=f)break;if(Q<=0)return 0;let j=Math.min(Q,W);while(j>0&&!R8($[j]))j-=1;return j}function U8($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>U8(f));if($&&typeof $==="object"){let f=$,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...U8(f[W]));if(Array.isArray(f.files)){for(let W of f.files)if(W&&typeof W==="object")J.push(...U8(W.path))}if(Array.isArray(f.file_paths))J.push(...U8(f.file_paths));return J}return[]}function P8($,f){let J=new Set($);for(let W of f){let Z=W.trim();if(!Z)continue;J.add(Z)}return[...J].sort((W,Z)=>W.localeCompare(Z))}function Yj($){let f=[],J=[];for(let W of $){let Z=eW(W);if(Z){f=P8(f,Z.details.readFiles),J=P8(J,Z.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){f=P8(f,[Q.path]);continue}if(Q.type!=="tool_use")continue;let j=U8(Q.input);if(Q.name==="read_files"){f=P8(f,j);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=P8(J,j)}}return{readFiles:f,modifiedFiles:J}}function NU($){let f=$.readFiles.length>0?$.readFiles.map((W)=>`- ${W}`).join(`
287
- `):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((W)=>`- ${W}`).join(`
327
+ `).trim()}function oj(){let f=new WeakMap;return($)=>{let J=$,Q=f.get(J);if(typeof Q==="number")return Q;let Z;try{Z=JSON.stringify($)}catch{Z=tj($)}let W=NQ(Z.length);return f.set(J,W),W}}function E8(f){return f.metadata?.kind==="compaction_summary"}function CQ(f){if(!E8(f))return;let $=f.metadata;if(!$)return;let J=$.details;return{kind:"compaction_summary",summary:String($.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number($.tokensBefore??0),generatedAt:Number($.generatedAt??0)}}function bU(f){if(f.role!=="user"||!Array.isArray(f.content))return!1;return f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}function h8(f){return f.role==="user"&&!bU(f)&&!E8(f)}function ej(f){for(let $=0;$<f.length;$+=1)if(h8(f[$]))return $;return-1}function U6(f){for(let $=f.length-1;$>=0;$-=1)if(h8(f[$]))return $;return 0}function fH(f){for(let $=f.length-1;$>=0;$-=1)if(f[$].role==="assistant")return $;return-1}function $H(f){for(let $=f.length-1;$>=0;$-=1)if(E8(f[$]))return $;return-1}function JH(f,$,J){let Q=U6(f);if(Q<=0)return 0;let Z=0,W=f.length;for(let H=f.length-1;H>=0;H-=1)if(Z+=J(f[H]),W=H,Z>=$)break;if(W<=0)return 0;let j=Math.min(W,Q);while(j>0&&!h8(f[j]))j-=1;return j}function S8(f){if(typeof f==="string"&&f.trim().length>0)return[f];if(Array.isArray(f))return f.flatMap(($)=>S8($));if(f&&typeof f==="object"){let $=f,J=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...S8($[Q]));if(Array.isArray($.files)){for(let Q of $.files)if(Q&&typeof Q==="object")J.push(...S8(Q.path))}if(Array.isArray($.file_paths))J.push(...S8($.file_paths));return J}return[]}function C8(f,$){let J=new Set(f);for(let Q of $){let Z=Q.trim();if(!Z)continue;J.add(Z)}return[...J].sort((Q,Z)=>Q.localeCompare(Z))}function QH(f){let $=[],J=[];for(let Q of f){let Z=CQ(Q);if(Z){$=C8($,Z.details.readFiles),J=C8(J,Z.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let W of Q.content){if(W.type==="file"){$=C8($,[W.path]);continue}if(W.type!=="tool_use")continue;let j=S8(W.input);if(W.name==="read_files"){$=C8($,j);continue}if(W.name==="editor"||W.name==="apply_patch")J=C8(J,j)}}return{readFiles:$,modifiedFiles:J}}function kU(f){let $=f.readFiles.length>0?f.readFiles.map((Q)=>`- ${Q}`).join(`
328
+ `):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((Q)=>`- ${Q}`).join(`
288
329
  `):"- none";return`## Files
289
330
  Read:
290
- ${f}
331
+ ${$}
291
332
  Modified:
292
- ${J}`}function Vj($,f){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
333
+ ${J}`}function ZH(f,$){if(/^## Files$/im.test(f))return f.trim();return`${f.trim()}
293
334
 
294
- ${NU(f)}`.trim()}function Bj($){let f=[`Summarize this session for continuation. Be concise and factual.
335
+ ${kU($)}`.trim()}function WH(f){let $=[`Summarize this session for continuation. Be concise and factual.
295
336
 
296
337
  ## Goal
297
338
  One sentence: what is being built or fixed.
@@ -308,16 +349,16 @@ Key technical choices or notable findings (omit if none).
308
349
  Immediate next steps.
309
350
 
310
351
  ## Files
311
- Read: ${$.fileOps.readFiles.join(", ")||"none"}
312
- Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.trim())f.push(`Previous summary:
313
- ${$.previousSummary.trim()}`);return f.push(`Conversation:
314
- ${$.conversationText||"(empty)"}`),f.join(`
352
+ Read: ${f.fileOps.readFiles.join(", ")||"none"}
353
+ Edited: ${f.fileOps.modifiedFiles.join(", ")||"none"}`];if(f.previousSummary?.trim())$.push(`Previous summary:
354
+ ${f.previousSummary.trim()}`);return $.push(`Conversation:
355
+ ${f.conversationText||"(empty)"}`),$.join(`
315
356
 
316
- `)}function Kj($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:Q,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??s3,thinking:!1}};if(!f)return J($.activeProviderConfig);let W=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...W??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.headers??W?.headers,knownModels:f.knownModels??W?.knownModels,maxOutputTokens:f.maxOutputTokens??s3})}function Gj($){return{role:"user",content:`Context summary:
357
+ `)}function jH(f){let $=f.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:W,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??lj,thinking:!1}};if(!$)return J(f.activeProviderConfig);let Q=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0;return J({...Q??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Q?.apiKey,baseUrl:$.baseUrl??Q?.baseUrl,headers:$.headers??Q?.headers,knownModels:$.knownModels??Q?.knownModels,maxOutputTokens:$.maxOutputTokens??lj})}function HH(f){return{role:"user",content:`Context summary:
317
358
 
318
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function yU($){let f=await MU($.providerConfig),J="";for await(let W of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function qU($){try{return JSON.stringify($).length}catch{return String($).length}}async function Pj($){let f=$.context.messages;if(f.length<2)return;let J=Aj(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let W=f.slice(0,J),Z=Xj(W),Q=Z>=0?eW(W[Z])?.summary:void 0,j=Z>=0?W.slice(Z+1):W;if(j.length===0)return;let H=Yj(W),X=Zj(j),A=Bj({previousSummary:Q,conversationText:X,fileOps:H});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:W.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:Q?.length??0,conversationTextChars:X.length,summaryRequestChars:A.length,summaryRequestEstimatedTokens:aW(A.length),newMessagesJsonChars:qU(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let Y=await yU({providerConfig:Kj({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:A,logger:$.logger});if(!Y.trim())return;let V=Vj(Y,H),B=f.reduce((R,P)=>R+$.estimateMessageTokens(P),0),K=[Gj({summary:V,fileOps:H,tokensBefore:B}),...f.slice(J)],G=K.reduce((R,P)=>R+$.estimateMessageTokens(P),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function Rj($){if(F8($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:oW(J.content)}:J)}}function D8($,f){return $.reduce((J,W)=>J+f(W),0)}function Uj($,f){let J=Math.max(1,f),W=Math.max(16,J*4);if(typeof $.content==="string"){let j=e$($.content,W).trim();return{...$,content:j||"..."}}let Z=W,Q=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let H=e$(j.text,Z).trim();return Z-=H.length,{...j,text:H||"..."}});return{...$,content:Q}}function wU($,f){let J=jj($),W=i4($),Z=Hj($),Q=[];for(let j=0;j<$.length;j+=1){let H=Rj($[j]);if(!H)continue;Q.push({index:j,message:H,estimatedTokens:f(H),isFirstUser:j===J,isLastUser:j===W,isLastAssistant:j===Z})}return Q}function Fj($,f,J,W){let Z=$[f];Z.message=J,Z.estimatedTokens=W(J)}function SU($){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 hU($){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 Dj($){return new Set([...SU($.message),...hU($.message)])}function CU($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let W of Dj($[J])){let Z=f.get(W);if(Z)Z.add(J);else f.set(W,new Set([J]))}return f}function EU($,f){let J=CU($),W=new Set,Z=[f];while(Z.length>0){let Q=Z.shift();if(Q===void 0||W.has(Q))continue;W.add(Q);for(let j of Dj($[Q]))for(let H of J.get(j)??[])if(!W.has(H))Z.push(H)}return W}function n4($,f,J,W){let Z=D8($.map((Q)=>Q.message),W);for(let Q=0;Q<$.length&&Z>J;){if(!f($[Q])){Q+=1;continue}let j=EU($,Q);Z-=Array.from(j).reduce((H,X)=>H+$[X].estimatedTokens,0);for(let H of Array.from(j).sort((X,A)=>A-X))$.splice(H,1)}}function bU($,f,J){let W=D8($.map((Q)=>Q.message),J);if(W<=f)return;for(let Q=$.length-1;Q>=0&&W>f;Q-=1){let j=$[Q];if(j.isFirstUser)continue;let H=Math.max(Jj,j.estimatedTokens-(W-f));if(H>=j.estimatedTokens)continue;Fj($,Q,Uj(j.message,H),J),W=D8($.map((X)=>X.message),J)}if(W<=f)return;let Z=$.findIndex((Q)=>Q.isFirstUser);if(Z>=0){let Q=Math.max(1,$[Z].estimatedTokens-(W-f));Fj($,Z,Uj($[Z].message,Q),J)}}function kU($,f){return JSON.stringify($)!==JSON.stringify(f)}function IU($){let f=i4($);if(f<0||f===0&&!R8($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function Lj($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:W}=IU($.context.messages);if(J.length===0)return;let Z=wU(J,$.estimateMessageTokens);if(Z.length===0)return;n4(Z,(X)=>X.message.role==="assistant"&&!X.isLastAssistant,f,$.estimateMessageTokens),n4(Z,(X)=>X.message.role==="user"&&!X.isFirstUser&&!X.isLastUser,f,$.estimateMessageTokens),n4(Z,(X)=>X.message.role==="assistant"&&X.isLastAssistant,f,$.estimateMessageTokens),n4(Z,(X)=>X.message.role==="user"&&X.isLastUser&&!X.isFirstUser,f,$.estimateMessageTokens),bU(Z,f,$.estimateMessageTokens);let Q=[...Z.map((X)=>X.message),...W];if(!kU($.context.messages,Q))return;let j=D8([...J.map((X)=>Rj(X)??X),...W],$.estimateMessageTokens),H=D8(Q,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:Q.length,messagesRemoved:$.context.messages.length-Q.length,tokensBefore:j,tokensAfter:H,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:Q}}function Oj($){try{return JSON.stringify($).length}catch{return String($).length}}function xU($){let f=0,J=0,W=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;let j=Oj(Q.content);f+=1,J+=j,W=Math.max(W,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:W}}var mU={basic:({context:$,estimateMessageTokens:f,logger:J})=>Lj({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:W,estimateMessageTokens:Z,logger:Q})=>Pj({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??sW,$.triggerTokens):J?.preserveRecentTokens??sW,estimateMessageTokens:Z,logger:Q})};function gU($){if(typeof $.config.reserveTokens==="number"){let W=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-W);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let W=Math.max(0,Math.min($.maxInputTokens-$j,$.maxInputTokens*tW));return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}let f=$.config.thresholdRatio??tW,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function vU($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),W=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}function L8($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let W=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=Qj(),Q=J?.strategy??"basic",j=mU[Q],H=f.mode??"auto",X=J?.compact?"custom":Q;return async(A)=>{let Y=A.apiMessages.reduce((O,N)=>O+Z(N),0),V=J?.maxInputTokens??A.model.info?.maxInputTokens??A.model.info?.contextWindow??e3;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=gU({inputTokens:Y,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:H,strategy:Q,iteration:A.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:Y,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:A.messages.length,apiMessageCount:A.apiMessages.length,apiMessagesJsonChars:Oj(A.apiMessages),...xU(A.apiMessages)}),H==="auto"&&!B.shouldCompact)return;let K=H==="manual"?vU({inputTokens:Y,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,G={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId,iteration:A.iteration,messages:A.messages,model:A.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?Y/V:0},R=H==="manual"?"manual_compaction":"auto_compaction";A.emitStatusNotice?.(H==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:A.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let P=A.messages.length,U=Date.now(),F=J?.compact?await J.compact(G):await j({context:G,providerConfig:{...W,abortSignal:A.abortSignal},compaction:J,mode:H,estimateMessageTokens:Z,logger:$.logger}),z=Date.now()-U,_=$.sessionId??A.conversationId,D={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId??void 0};if(F?.messages){let O=F.messages.reduce((N,q)=>N+Z(q),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:Q,maxInputTokens:V,inputTokens:Y,afterTokens:O,tokensSaved:Y-O,utilizationBefore:`${(Y/V*100).toFixed(1)}%`,utilizationAfter:`${(O/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length}),w4($.telemetry,{ulid:_,strategy:X,mode:H,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length,tokensBefore:Y,tokensAfter:O,tokensSaved:Y-O,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...D})}else S4($.telemetry,{ulid:_,strategy:X,mode:H,reason:"no_result",tokensBefore:Y,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...D});return F}}var xH={};w(xH,{zodToJsonSchema:()=>VD,validateWithZod:()=>YD,resolveToolRoutingConfig:()=>cf,resolveToolPresetName:()=>b$,resolveCoreSelectedToolIds:()=>j6,getCoreHeadlessToolNames:()=>m8,getCoreDefaultEnabledToolIds:()=>Q6,getCoreBuiltinToolCatalog:()=>l1,getCoreAcpToolNames:()=>H6,createWindowsShellTool:()=>HZ,createWebFetchTool:()=>XZ,createWebFetchExecutor:()=>I8,createToolPoliciesWithPreset:()=>e4,createSubmitAndExitTool:()=>BZ,createSkillsTool:()=>x1,createSearchTool:()=>QZ,createSearchExecutor:()=>k8,createReadFilesTool:()=>ZZ,createFileReadExecutor:()=>b8,createEditorTool:()=>YZ,createEditorExecutor:()=>C8,createDefaultToolsWithPreset:()=>$6,createDefaultTools:()=>J1,createDefaultExecutors:()=>vf,createBuiltinTools:()=>p1,createBashTool:()=>jZ,createBashExecutor:()=>h8,createAskQuestionTool:()=>VZ,createApplyPatchTool:()=>AZ,createApplyPatchExecutor:()=>S8,WebFetchRequestSchema:()=>JZ,ToolPresets:()=>m0,TEAM_TOOL_NAMES:()=>rf,SubmitInputSchema:()=>w8,SkillsInputSchema:()=>y8,SearchCodebaseInputSchema:()=>_8,RunCommandsInputSchema:()=>xf,ReadFilesInputSchema:()=>z8,ReadFileRequestSchema:()=>S$,FetchWebContentInputSchema:()=>T8,EditFileInputSchema:()=>N8,DefaultToolNames:()=>J0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>uf,AskQuestionInputSchema:()=>q8,ApplyPatchInputSchema:()=>M8,ALL_DEFAULT_TOOL_NAMES:()=>p$});import{validateWithZod as YD,zodToJsonSchema as VD}from"@cline/shared";L0();import{createTool as h$,validateWithZod as C$,zodToJsonSchema as A$}from"@cline/shared";var _j="__clineInternalTelemetry";function Tj($){let f=$?.__clineInternalTelemetry;return f&&typeof f==="object"&&"capture"in f&&typeof f.capture==="function"?f:void 0}import{validateWithZod as uU}from"@cline/shared";import{z as L}from"zod";var $1=6000,O8=L.string().describe("The absolute file path of a text file to read content from"),Nj=L.object({start_line:L.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:L.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),S$=L.object({path:O8,start_line:Nj.shape.start_line,end_line:Nj.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),z8=L.object({files:L.array(S$).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),Mj=L.union([z8,S$,L.array(S$),L.array(L.string()),L.string(),L.object({files:L.array(L.union([O8,S$]))}),L.object({files:S$}),L.object({files:O8}),L.object({file_paths:L.array(O8)}),L.object({file_paths:L.string()}),L.object({paths:L.array(L.union([O8,S$]))}),L.object({paths:S$}),L.object({paths:L.string()})]),_8=L.object({queries:L.array(L.string()).describe("Array of regex search queries to execute")}),yj=L.union([_8,L.array(L.string()),L.string(),L.object({queries:L.string()})]),k1=L.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${$1*2} characters) to avoid timeouts.`),xf=L.object({commands:L.array(k1).describe("Array of shell commands to execute")}),qj=L.union([xf,L.object({commands:k1}),L.object({command:k1}),L.object({cmd:k1}),L.array(L.string()),L.string()]),$Z=L.object({command:L.string().min(1).describe("The executable to run directly without shell parsing."),args:L.array(L.string()).optional().describe("Optional argv list passed directly to the executable.")}),wj=L.union([k1,$Z]),fZ=L.object({commands:L.array(wj).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.")}),Sj=L.union([xf,fZ,L.object({commands:wj}),L.array($Z),$Z,L.object({command:k1}),L.object({cmd:k1}),L.array(L.string()),L.string()]),JZ=L.object({url:L.string().describe("The URL to fetch"),prompt:L.string().min(2).describe("Analysis prompt for the fetched content")}),T8=L.object({requests:L.array(JZ).describe("Array of the URLs for the web fetch requests")}),N8=L.object({path:L.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:L.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${$1} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:L.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${$1} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:L.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),M8=L.object({input:L.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),hj=L.union([M8,L.string()]),y8=L.object({skill:L.string().min(1).describe("Name of the skill to execute."),args:L.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),q8=L.object({question:L.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:L.array(L.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),w8=L.object({summary:L.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:L.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
359
+ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function xU(f){let $=await IU(f.providerConfig),J="";for await(let Q of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}function gU(f){try{return JSON.stringify(f).length}catch{return String(f).length}}async function XH(f){let $=f.context.messages;if($.length<2)return;let J=JH($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let Q=$.slice(0,J),Z=$H(Q),W=Z>=0?CQ(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let H=QH(Q),X=sj(j),A=WH({previousSummary:W,conversationText:X,fileOps:H});f.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:$.length-J,previousSummaryChars:W?.length??0,conversationTextChars:X.length,summaryRequestChars:A.length,summaryRequestEstimatedTokens:NQ(A.length),newMessagesJsonChars:gU(j),maxInputTokens:f.context.maxInputTokens,triggerTokens:f.context.triggerTokens});let Y=await xU({providerConfig:jH({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:A,logger:f.logger});if(!Y.trim())return;let V=ZH(Y,H),B=$.reduce((R,G)=>R+f.estimateMessageTokens(G),0),K=[HH({summary:V,fileOps:H,tokensBefore:B}),...$.slice(J)],P=K.reduce((R,G)=>R+f.estimateMessageTokens(G),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:B,tokensAfter:P,maxInputTokens:f.context.maxInputTokens}),{messages:K}}function VH(f){if(E8(f))return;if(typeof f.content==="string"){let J=f.content.trim();return J?{...f,content:J}:void 0}let $=f.content.filter((J)=>J.type!=="text"||J.text.trim());if($.length===0)return;return{...f,content:$.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:wQ(J.content)}:J)}}function b8(f,$){return f.reduce((J,Q)=>J+$(Q),0)}function AH(f,$){let J=Math.max(1,$),Q=Math.max(16,J*4);if(typeof f.content==="string"){let j=H$(f.content,Q).trim();return{...f,content:j||"..."}}let Z=Q,W=f.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let H=H$(j.text,Z).trim();return Z-=H.length,{...j,text:H||"..."}});return{...f,content:W}}function mU(f,$){let J=ej(f),Q=U6(f),Z=fH(f),W=[];for(let j=0;j<f.length;j+=1){let H=VH(f[j]);if(!H)continue;W.push({index:j,message:H,estimatedTokens:$(H),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function YH(f,$,J,Q){let Z=f[$];Z.message=J,Z.estimatedTokens=Q(J)}function vU(f){let $=new Set;if(!Array.isArray(f.content))return $;for(let J of f.content)if(J.type==="tool_use")$.add(J.id);return $}function cU(f){let $=new Set;if(!Array.isArray(f.content))return $;for(let J of f.content)if(J.type==="tool_result")$.add(J.tool_use_id);return $}function BH(f){return new Set([...vU(f.message),...cU(f.message)])}function uU(f){let $=new Map;for(let J=0;J<f.length;J+=1)for(let Q of BH(f[J])){let Z=$.get(Q);if(Z)Z.add(J);else $.set(Q,new Set([J]))}return $}function dU(f,$){let J=uU(f),Q=new Set,Z=[$];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of BH(f[W]))for(let H of J.get(j)??[])if(!Q.has(H))Z.push(H)}return Q}function R6(f,$,J,Q){let Z=b8(f.map((W)=>W.message),Q);for(let W=0;W<f.length&&Z>J;){if(!$(f[W])){W+=1;continue}let j=dU(f,W);Z-=Array.from(j).reduce((H,X)=>H+f[X].estimatedTokens,0);for(let H of Array.from(j).sort((X,A)=>A-X))f.splice(H,1)}}function lU(f,$,J){let Q=b8(f.map((W)=>W.message),J);if(Q<=$)return;for(let W=f.length-1;W>=0&&Q>$;W-=1){let j=f[W];if(j.isFirstUser)continue;let H=Math.max(aj,j.estimatedTokens-(Q-$));if(H>=j.estimatedTokens)continue;YH(f,W,AH(j.message,H),J),Q=b8(f.map((X)=>X.message),J)}if(Q<=$)return;let Z=f.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,f[Z].estimatedTokens-(Q-$));YH(f,Z,AH(f[Z].message,W),J)}}function pU(f,$){return JSON.stringify(f)!==JSON.stringify($)}function rU(f){let $=U6(f);if($<0||$===0&&!h8(f[0]))return{compactable:f,protectedTail:[]};return{compactable:f.slice(0,$),protectedTail:f.slice($)}}function KH(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.maxInputTokens)),{compactable:J,protectedTail:Q}=rU(f.context.messages);if(J.length===0)return;let Z=mU(J,f.estimateMessageTokens);if(Z.length===0)return;R6(Z,(X)=>X.message.role==="assistant"&&!X.isLastAssistant,$,f.estimateMessageTokens),R6(Z,(X)=>X.message.role==="user"&&!X.isFirstUser&&!X.isLastUser,$,f.estimateMessageTokens),R6(Z,(X)=>X.message.role==="assistant"&&X.isLastAssistant,$,f.estimateMessageTokens),R6(Z,(X)=>X.message.role==="user"&&X.isLastUser&&!X.isFirstUser,$,f.estimateMessageTokens),lU(Z,$,f.estimateMessageTokens);let W=[...Z.map((X)=>X.message),...Q];if(!pU(f.context.messages,W))return;let j=b8([...J.map((X)=>VH(X)??X),...Q],f.estimateMessageTokens),H=b8(W,f.estimateMessageTokens);return f.logger?.debug("Performed basic compaction",{messagesBefore:f.context.messages.length,messagesAfter:W.length,messagesRemoved:f.context.messages.length-W.length,tokensBefore:j,tokensAfter:H,targetTokens:$,maxInputTokens:f.context.maxInputTokens}),{messages:W}}function PH(f){try{return JSON.stringify(f).length}catch{return String(f).length}}function iU(f){let $=0,J=0,Q=0;for(let Z of f){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=PH(W.content);$+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:$,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var nU={basic:({context:f,estimateMessageTokens:$,logger:J})=>KH({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>XH({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??yQ,f.triggerTokens):J?.preserveRecentTokens??yQ,estimateMessageTokens:Z,logger:W})};function aU(f){if(typeof f.config.reserveTokens==="number"){let Q=Math.max(0,f.config.reserveTokens),Z=Math.max(0,f.maxInputTokens-Q);return{shouldCompact:f.inputTokens>Z,triggerTokens:Z,thresholdRatio:f.maxInputTokens>0?Z/f.maxInputTokens:0}}if(typeof f.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min(f.maxInputTokens-ij,f.maxInputTokens*qQ));return{shouldCompact:f.inputTokens>Q,triggerTokens:Q,thresholdRatio:f.maxInputTokens>0?Q/f.maxInputTokens:0}}let $=f.config.thresholdRatio??qQ,J=f.maxInputTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function tU(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),Q=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:f.maxInputTokens>0?Q/f.maxInputTokens:0}}function k8(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let Q=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},Z=oj(),W=J?.strategy??"basic",j=nU[W],H=$.mode??"auto",X=J?.compact?"custom":W;return async(A)=>{let Y=A.apiMessages.reduce((D,y)=>D+Z(y),0),V=J?.maxInputTokens??A.model.info?.maxInputTokens??A.model.info?.contextWindow??rj;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=aU({inputTokens:Y,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(f.logger?.debug("Context compaction diagnostics",{mode:H,strategy:W,iteration:A.iteration,providerId:f.providerId,modelId:f.modelId,inputTokens:Y,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:A.messages.length,apiMessageCount:A.apiMessages.length,apiMessagesJsonChars:PH(A.apiMessages),...iU(A.apiMessages)}),H==="auto"&&!B.shouldCompact)return;let K=H==="manual"?tU({inputTokens:Y,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:$.manualTargetRatio}):B,P={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId,iteration:A.iteration,messages:A.messages,model:A.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?Y/V:0},R=H==="manual"?"manual_compaction":"auto_compaction";A.emitStatusNotice?.(H==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:A.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let G=A.messages.length,F=Date.now(),U=J?.compact?await J.compact(P):await j({context:P,providerConfig:{...Q,abortSignal:A.abortSignal},compaction:J,mode:H,estimateMessageTokens:Z,logger:f.logger}),_=Date.now()-F,M=f.sessionId??A.conversationId,L={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId??void 0};if(U?.messages){let D=U.messages.reduce((y,b)=>y+Z(b),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:V,inputTokens:Y,afterTokens:D,tokensSaved:Y-D,utilizationBefore:`${(Y/V*100).toFixed(1)}%`,utilizationAfter:`${(D/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:G,messagesAfter:U.messages.length,messagesRemoved:G-U.messages.length}),c4(f.telemetry,{ulid:M,strategy:X,mode:H,messagesBefore:G,messagesAfter:U.messages.length,messagesRemoved:G-U.messages.length,tokensBefore:Y,tokensAfter:D,tokensSaved:Y-D,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:_,provider:f.providerId,modelId:f.modelId,...L})}else u4(f.telemetry,{ulid:M,strategy:X,mode:H,reason:"no_result",tokensBefore:Y,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:_,provider:f.providerId,modelId:f.modelId,...L});return U}}var CX={};q(CX,{zodToJsonSchema:()=>_L,validateWithZod:()=>OL,resolveToolRoutingConfig:()=>J2,resolveToolPresetName:()=>mf,resolveCoreSelectedToolIds:()=>C6,getCoreHeadlessToolNames:()=>e8,getCoreDefaultEnabledToolIds:()=>w6,getCoreBuiltinToolCatalog:()=>f1,getCoreAcpToolNames:()=>S6,createWindowsShellTool:()=>gQ,createWebFetchTool:()=>mQ,createWebFetchExecutor:()=>s8,createToolPoliciesWithPreset:()=>T6,createSubmitAndExitTool:()=>dQ,createSkillsTool:()=>i$,createSearchTool:()=>IQ,createSearchExecutor:()=>t8,createReadFilesTool:()=>kQ,createFileReadExecutor:()=>a8,createEditorTool:()=>cQ,createEditorExecutor:()=>i8,createDefaultToolsWithPreset:()=>z6,createDefaultTools:()=>Y$,createDefaultExecutors:()=>f2,createBuiltinTools:()=>$1,createBashTool:()=>xQ,createBashExecutor:()=>r8,createAskQuestionTool:()=>uQ,createApplyPatchTool:()=>vQ,createApplyPatchExecutor:()=>p8,WebFetchRequestSchema:()=>hQ,ToolPresets:()=>c0,TEAM_TOOL_NAMES:()=>Z2,SubmitInputSchema:()=>l8,SkillsInputSchema:()=>u8,SearchCodebaseInputSchema:()=>g8,RunCommandsInputSchema:()=>s1,ReadFilesInputSchema:()=>x8,ReadFileRequestSchema:()=>kf,FetchWebContentInputSchema:()=>m8,EditFileInputSchema:()=>v8,DefaultToolNames:()=>Y0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>$2,AskQuestionInputSchema:()=>d8,ApplyPatchInputSchema:()=>c8,ALL_DEFAULT_TOOL_NAMES:()=>sf});import{validateWithZod as OL,zodToJsonSchema as _L}from"@cline/shared";O0();import{createTool as If,validateWithZod as xf,zodToJsonSchema as Vf}from"@cline/shared";var FH="__clineInternalTelemetry";function UH(f){let $=f?.__clineInternalTelemetry;return $&&typeof $==="object"&&"capture"in $&&typeof $.capture==="function"?$:void 0}import{validateWithZod as sU}from"@cline/shared";import{z as O}from"zod";var X$=6000,I8=O.string().describe("The absolute file path of a text file to read content from"),RH=O.object({start_line:O.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:O.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),kf=O.object({path:I8,start_line:RH.shape.start_line,end_line:RH.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),x8=O.object({files:O.array(kf).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.")}),DH=O.union([x8,kf,O.array(kf),O.array(O.string()),O.string(),O.object({files:O.array(O.union([I8,kf]))}),O.object({files:kf}),O.object({files:I8}),O.object({file_paths:O.array(I8)}),O.object({file_paths:O.string()}),O.object({paths:O.array(O.union([I8,kf]))}),O.object({paths:kf}),O.object({paths:O.string()})]),g8=O.object({queries:O.array(O.string()).describe("Array of regex search queries to execute")}),LH=O.union([g8,O.array(O.string()),O.string(),O.object({queries:O.string()})]),p$=O.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${X$*2} characters) to avoid timeouts.`),s1=O.object({commands:O.array(p$).describe("Array of shell commands to execute")}),OH=O.union([s1,O.object({commands:p$}),O.object({command:p$}),O.object({cmd:p$}),O.array(O.string()),O.string()]),SQ=O.object({command:O.string().min(1).describe("The executable to run directly without shell parsing."),args:O.array(O.string()).optional().describe("Optional argv list passed directly to the executable.")}),_H=O.union([p$,SQ]),EQ=O.object({commands:O.array(_H).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.")}),TH=O.union([s1,EQ,O.object({commands:_H}),O.array(SQ),SQ,O.object({command:p$}),O.object({cmd:p$}),O.array(O.string()),O.string()]),hQ=O.object({url:O.string().describe("The URL to fetch"),prompt:O.string().min(2).describe("Analysis prompt for the fetched content")}),m8=O.object({requests:O.array(hQ).describe("Array of the URLs for the web fetch requests")}),v8=O.object({path:O.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:O.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${X$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:O.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${X$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:O.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),c8=O.object({input:O.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),zH=O.union([c8,O.string()]),u8=O.object({skill:O.string().min(1).describe("Name of the skill to execute."),args:O.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),d8=O.object({question:O.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:O.array(O.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),l8=O.object({summary:O.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:O.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
319
360
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
320
- 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 f1($){if($ instanceof Error)return $.message;return String($)}function Cj($){if(typeof $.old_text==="string"&&$.old_text.length>$1)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${$1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>$1)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${$1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class I1 extends Error{timeoutMs;constructor($,f){super($);this.name="TimeoutError",this.timeoutMs=f}}function X$($,f,J){return Promise.race([$,new Promise((W,Z)=>{setTimeout(()=>Z(new I1(J,f)),f)})])}function a4($){let{path:f,start_line:J,end_line:W}=$;if(J==null&&W==null)return f;return`${f}:${J??1}-${W??"EOF"}`}function Ej($){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 bj($){let f=uU(Sj,$);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 WZ($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${$.command} ${J.join(" ")}`}function kj($,f){let J=$.metadata?.[f];return typeof J==="string"?J:void 0}function Ij($,f){B3(Tj($.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:kj($,"mode"),source:kj($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function ZZ($,f={}){let J=f.fileReadTimeoutMs??1e4;return h$({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. ",inputSchema:A$(z8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,Z)=>{let Q=C$(Mj,W),j;if(typeof Q==="string")j=[{path:Q}];else if(Array.isArray(Q))j=Q.map((H)=>typeof H==="string"?{path:H}:H);else if("files"in Q)j=(Array.isArray(Q.files)?Q.files:[Q.files]).map((X)=>typeof X==="string"?{path:X}:X);else if("file_paths"in Q)j=(Array.isArray(Q.file_paths)?Q.file_paths:[Q.file_paths]).map((X)=>({path:X}));else if("paths"in Q)j=(Array.isArray(Q.paths)?Q.paths:[Q.paths]).map((X)=>typeof X==="string"?{path:X}:X);else j=[Q];return Promise.all(j.map(async(H)=>{let X=Ej(H);if(X)return{query:a4(H),result:"",error:`Invalid file range: ${X}`,success:!1};try{let A=await X$($(H,Z),J,`File read timed out after ${J}ms`);return{query:a4(H),result:A,success:!0}}catch(A){let Y=f1(A);return{query:a4(H),result:"",error:`Error reading file: ${Y}`,success:!1}}}))}})}function QZ($,f={}){let J=f.searchTimeoutMs??30000,W=f.cwd??process.cwd();return h$({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:A$(_8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,Q)=>{let j=C$(yj,Z),H=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(H.map(async(X)=>{try{let A=await X$($(X,W,Q),J,`Search timed out after ${J}ms`),Y=A.length>0&&!A.includes("No results found");return{query:X,result:A,success:Y}}catch(A){let Y=f1(A);return{query:X,result:"",error:`Search failed: ${Y}`,success:!1}}}))}})}function jZ($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return h$({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.",inputSchema:A$(xf),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=C$(qj,Q),X;if(typeof H==="string")X=[H];else if(Array.isArray(H))X=H;else if("commands"in H)X=Array.isArray(H.commands)?H.commands:[H.commands];else if("command"in H)X=[H.command];else X=[H.cmd];return Promise.all(X.map(async(A)=>{let Y=Date.now();try{let V=await X$($(A,Z,j),J,`Command timed out after ${J}ms`);return{query:A,result:V,success:!0}}catch(V){if(V instanceof I1)Ij(j,{effectiveTimeoutMs:V.timeoutMs,timeoutSource:W,commandCount:X.length,durationMs:Date.now()-Y});let B=f1(V);return{query:A,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function HZ($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return h$({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:A$(fZ),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=bj(Q);return Promise.all(H.map(async(X)=>{let A=Date.now();try{let Y=await X$($(X,Z,j),J,`Command timed out after ${J}ms`);return{query:WZ(X),result:Y,success:!0}}catch(Y){if(Y instanceof I1)Ij(j,{effectiveTimeoutMs:Y.timeoutMs,timeoutSource:W,commandCount:H.length,durationMs:Date.now()-A});let V=f1(Y);return{query:WZ(X),result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function XZ($,f={}){let J=f.webFetchTimeoutMs??30000;return h$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:A$(T8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,Z)=>{let Q=C$(T8,W);return Promise.all(Q.requests.map(async(j)=>{try{let H=await X$($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:H,success:!0}}catch(H){let X=f1(H);return{query:j.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var cU=`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 A$(f){if(f instanceof Error)return f.message;return String(f)}function MH(f){if(typeof f.old_text==="string"&&f.old_text.length>X$)return`Editor input too large: old_text was ${f.old_text.length} characters, exceeding the recommended limit of ${X$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(f.new_text.length>X$)return`Editor input too large: new_text was ${f.new_text.length} characters, exceeding the recommended limit of ${X$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class r$ extends Error{timeoutMs;constructor(f,$){super(f);this.name="TimeoutError",this.timeoutMs=$}}function Yf(f,$,J){return Promise.race([f,new Promise((Q,Z)=>{setTimeout(()=>Z(new r$(J,$)),$)})])}function D6(f){let{path:$,start_line:J,end_line:Q}=f;if(J==null&&Q==null)return $;return`${$}:${J??1}-${Q??"EOF"}`}function NH(f){let{start_line:$,end_line:J}=f;if($==null||J==null||$<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${$}, end_line: ${J})`}function qH(f){let $=sU(TH,f);if(typeof $==="string")return[$];if(Array.isArray($))return $;if("commands"in $)return Array.isArray($.commands)?$.commands:[$.commands];if("command"in $)return"args"in $?[$]:[$.command];if("cmd"in $)return[$.cmd];return[$]}function bQ(f){if(typeof f==="string")return f;let $=f.args??[];if($.length===0)return f.command;let J=$.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${f.command} ${J.join(" ")}`}function yH(f,$){let J=f.metadata?.[$];return typeof J==="string"?J:void 0}function wH(f,$){S3(UH(f.metadata),{tool_name:"run_commands",effective_timeout_ms:$.effectiveTimeoutMs,timeout_source:$.timeoutSource,command_count:$.commandCount,duration_ms:$.durationMs,ulid:f.sessionId,mode:yH(f,"mode"),source:yH(f,"source"),session_id:f.sessionId,agent_id:f.agentId,conversation_id:f.conversationId,run_id:f.runId,iteration:f.iteration,tool_call_id:f.toolCallId})}function kQ(f,$={}){let J=$.fileReadTimeoutMs??1e4;return If({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:Vf(x8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Q,Z)=>{let W=xf(DH,Q),j;if(typeof W==="string")j=[{path:W}];else if(Array.isArray(W))j=W.map((H)=>typeof H==="string"?{path:H}:H);else if("files"in W)j=(Array.isArray(W.files)?W.files:[W.files]).map((X)=>typeof X==="string"?{path:X}:X);else if("file_paths"in W)j=(Array.isArray(W.file_paths)?W.file_paths:[W.file_paths]).map((X)=>({path:X}));else if("paths"in W)j=(Array.isArray(W.paths)?W.paths:[W.paths]).map((X)=>typeof X==="string"?{path:X}:X);else j=[W];return Promise.all(j.map(async(H)=>{let X=NH(H);if(X)return{query:D6(H),result:"",error:`Invalid file range: ${X}`,success:!1};try{let A=await Yf(f(H,Z),J,`File read timed out after ${J}ms`);return{query:D6(H),result:A,success:!0}}catch(A){let Y=A$(A);return{query:D6(H),result:"",error:`Error reading file: ${Y}`,success:!1}}}))}})}function IQ(f,$={}){let J=$.searchTimeoutMs??30000,Q=$.cwd??process.cwd();return If({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:Vf(g8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=xf(LH,Z),H=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(H.map(async(X)=>{try{let A=await Yf(f(X,Q,W),J,`Search timed out after ${J}ms`),Y=A.length>0&&!A.includes("No results found");return{query:X,result:A,success:Y}}catch(A){let Y=A$(A);return{query:X,result:"",error:`Search failed: ${Y}`,success:!1}}}))}})}function xQ(f,$={}){let J=$.bashTimeoutMs??30000,Q=$.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=$.cwd??process.cwd();return If({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:Vf(s1),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let H=xf(OH,W),X;if(typeof H==="string")X=[H];else if(Array.isArray(H))X=H;else if("commands"in H)X=Array.isArray(H.commands)?H.commands:[H.commands];else if("command"in H)X=[H.command];else X=[H.cmd];return Promise.all(X.map(async(A)=>{let Y=Date.now();try{let V=await Yf(f(A,Z,j),J,`Command timed out after ${J}ms`);return{query:A,result:V,success:!0}}catch(V){if(V instanceof r$)wH(j,{effectiveTimeoutMs:V.timeoutMs,timeoutSource:Q,commandCount:X.length,durationMs:Date.now()-Y});let B=A$(V);return{query:A,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function gQ(f,$={}){let J=$.bashTimeoutMs??30000,Q=$.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=$.cwd??process.cwd();return If({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:Vf(EQ),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let H=qH(W);return Promise.all(H.map(async(X)=>{let A=Date.now();try{let Y=await Yf(f(X,Z,j),J,`Command timed out after ${J}ms`);return{query:bQ(X),result:Y,success:!0}}catch(Y){if(Y instanceof r$)wH(j,{effectiveTimeoutMs:Y.timeoutMs,timeoutSource:Q,commandCount:H.length,durationMs:Date.now()-A});let V=A$(Y);return{query:bQ(X),result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function mQ(f,$={}){let J=$.webFetchTimeoutMs??30000;return If({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:Vf(m8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(Q,Z)=>{let W=xf(m8,Q);return Promise.all(W.requests.map(async(j)=>{try{let H=await Yf(f(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:H,success:!0}}catch(H){let X=A$(H);return{query:j.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var oU=`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:
321
362
 
322
363
  *** Begin Patch
323
364
  *** Update File: path/to/file.ts
@@ -353,162 +394,121 @@ Example:
353
394
  </div>
354
395
  );
355
396
  }
356
- *** End Patch`;function AZ($,f={}){let J=f.applyPatchTimeoutMs??30000,W=f.cwd??process.cwd();return h$({name:"apply_patch",description:cU,inputSchema:A$(M8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=C$(hj,Z),H=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await X$($({input:H},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(X){return{query:"apply_patch",result:"",error:`apply_patch failed: ${f1(X)}`,success:!1}}}})}function YZ($,f={}){let J=f.editorTimeoutMs??30000,W=f.cwd??process.cwd();return h$({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:A$(N8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=C$(N8,Z),H=j.insert_line==null?"edit":"insert",X=Cj(j);if(X)return{query:`${H}:${j.path}`,result:"",error:X,success:!1};try{let A=await X$($(j,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${H}:${j.path}`,result:A,success:!0}}catch(A){let Y=f1(A);return{query:`${H}:${j.path}`,result:"",error:`Editor operation failed: ${Y}`,success:!1}}}})}function x1($,f={}){let J=f.skillsTimeoutMs??15000,W='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=h$({name:"skills",description:W,inputSchema:A$(y8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=C$(y8,Q);return X$($(H.skill,H.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let Q=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),Z}function VZ($){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:A$(q8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let W=C$(q8,f);return $(W.question,W.options,J)}}}function BZ($,f={}){let J=f.submitTimeoutMs??15000;return h$({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:A$(w8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=C$(w8,W);return X$($(Q.summary,Q.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function J1($){let{executors:f,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:Z=!0,enableWebFetch:Q=!0,enableApplyPatch:j=!1,enableEditor:H=!0,enableSkills:X=!0,enableAskQuestion:A=!0,enableSubmitAndExit:Y=!1,...V}=$,B=[];if(J&&f.readFile)B.push(ZZ(f.readFile,V));if(W&&f.search)B.push(QZ(f.search,V));if(Z&&f.bash)if(process.platform==="win32")B.push(HZ(f.bash,V));else B.push(jZ(f.bash,V));if(Q&&f.webFetch)B.push(XZ(f.webFetch,V));if(H&&f.editor)B.push(YZ(f.editor,V));else if(j&&f.applyPatch)B.push(AZ(f.applyPatch,V));if(X&&f.skills)B.push(x1(f.skills,V));let K=Y?f.submit:void 0;if(A&&f.askQuestion&&!K)B.push(VZ(f.askQuestion));if(K)B.push(BZ(K,V));return B}import*as I0 from"node:fs/promises";import*as x0 from"node:path";var v={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},mj=["%%bash","apply_patch","EOF","```"];class Z0 extends Error{constructor($){super($);this.name="DiffError"}}function k0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class KZ{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(v.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(v.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(v.UPDATE)){this.parseUpdate($.substring(v.UPDATE.length).trim());return}if($?.startsWith(v.DELETE)){this.parseDelete($.substring(v.DELETE.length).trim());return}if($?.startsWith(v.ADD)){this.parseAdd($.substring(v.ADD.length).trim());return}throw new Z0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new Z0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new Z0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",W=this.parseUpdateFile(J,$);W.movePath=f,this.patch.actions[$]=W,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},W=$.split(`
357
- `),Z=0,Q=[v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(!Q.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],H=j?.startsWith("@@ ")?j.substring(3):void 0;if(H!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new Z0(`Invalid Line:
358
- ${this.lines[this.index]}`);if(H?.trim()){let P=k0(H.trim());for(let U=Z;U<W.length;U++){let F=W[U];if(F&&(k0(F)===P||k0(F.trim())===P)){if(Z=U+1,k0(F.trim())===P&&k0(F)!==P)this.fuzz++;break}}}let[A,Y,V,B]=pU(this.lines,this.index),[K,G,R]=lU(W,A,Z,B);if(K===-1){let P=A.join(`
359
- `);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:P.length>200?`${P.substring(0,200)}...`:P}),this.index=V}else{this.fuzz+=G;for(let P of Y)P.origIndex+=K,J.chunks.push(P);Z=K+A.length,this.index=V}}return J}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new Z0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new Z0(`Add File Error: File already exists: ${$}`);this.index++;let f=[],J=[v.END,v.UPDATE,v.DELETE,v.ADD];while(this.hasMoreLines()&&!J.some((W)=>this.lines[this.index]?.startsWith(W.trim()))){let W=this.lines[this.index++];if(W===void 0)break;if(!W.startsWith("+"))throw new Z0(`Invalid Add File line (missing '+'): ${W}`);f.push(W.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
360
- `),chunks:[]}}}function xj($,f){let J=$.length>f.length?$:f,W=$.length>f.length?f:$;if(J.length===0)return 1;let Z=dU(W,J);return(J.length-Z)/J.length}function dU($,f){let J=f.length+1,W=$.length+1,Z=Array(J*W).fill(0),Q=(H,X)=>Z[H*W+X]??0,j=(H,X,A)=>{Z[H*W+X]=A};for(let H=0;H<=f.length;H++)j(H,0,H);for(let H=0;H<=$.length;H++)j(0,H,H);for(let H=1;H<=f.length;H++)for(let X=1;X<=$.length;X++)if(f[H-1]===$[X-1])j(H,X,Q(H-1,X-1));else j(H,X,1+Math.min(Q(H-1,X-1),Q(H,X-1),Q(H-1,X)));return Q(f.length,$.length)}function lU($,f,J,W){if(f.length===0)return[J,0,1];let Z=0,Q=(j)=>{let H=k0(f.join(`
361
- `));for(let A=j;A<$.length;A++){let Y=k0($.slice(A,A+f.length).join(`
362
- `));if(Y===H)return[A,0,1];let V=xj(Y,H);if(V>Z)Z=V}for(let A=j;A<$.length;A++){let Y=k0($.slice(A,A+f.length).map((B)=>B.trimEnd()).join(`
363
- `)),V=k0(f.map((B)=>B.trimEnd()).join(`
364
- `));if(Y===V)return[A,1,1]}for(let A=j;A<$.length;A++){let Y=k0($.slice(A,A+f.length).map((B)=>B.trim()).join(`
365
- `)),V=k0(f.map((B)=>B.trim()).join(`
366
- `));if(Y===V)return[A,100,1]}let X=0.66;for(let A=j;A<$.length;A++){let Y=k0($.slice(A,A+f.length).join(`
367
- `)),V=xj(Y,H);if(V>=X)return[A,1000,V];if(V>Z)Z=V}return[-1,0,Z]};if(W){let[j,H,X]=Q($.length-f.length);if(j!==-1)return[j,H,X];return[j,H,X]=Q(J),[j,H+1e4,X]}return Q(J)}function pU($,f){let J=f,W=[],Z=[],Q=[],j=[],H="keep",X=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(J<$.length){let A=$[J];if(!A||X.some((B)=>A.startsWith(B.trim())))break;if(A==="***")break;if(A.startsWith("***"))throw new Z0(`Invalid line: ${A}`);J++;let Y=H,V=A;if(V[0]==="+")H="add";else if(V[0]==="-")H="delete";else if(V[0]===" ")H="keep";else H="keep",V=` ${V}`;if(V=V.slice(1),H==="keep"&&Y!==H){if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});Z=[],Q=[]}if(H==="delete")Z.push(V),W.push(V);else if(H==="add")Q.push(V);else W.push(V)}if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});if(J<$.length&&$[J]===v.END_FILE)return J++,[W,j,J,!0];return[W,j,J,!1]}function GZ($,f,J){let W=x0.isAbsolute(f),Z=W?x0.normalize(f):x0.resolve($,f);if(!J||W)return Z;let Q=x0.relative($,Z);if(Q.startsWith("..")||x0.isAbsolute(Q))throw new Z0(`Path must stay within cwd: ${f}`);return Z}function rU($){return $.split(`
368
- `).map((f)=>f.replace(/\r$/,""))}function gj($){if($.trim()==="")return!1;return mj.some((f)=>$.startsWith(f))}function iU($){let f=0,J=$.length;while(f<J&&gj($[f]??""))f++;while(J>f&&gj($[J-1]??""))J--;return $.slice(f,J)}function nU($){let f=rU($),J=f.findIndex((j)=>j.startsWith(v.BEGIN)),W=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(v.END)){W=j;break}if(J!==-1||W!==-1){if(J===-1||W===-1||W<J)throw new Z0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,W+1)}}let Z=iU(f);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[v.BEGIN,...Z,v.END]}}function aU($,f){let J=new Set;for(let W of $)for(let Z of f)if(W.startsWith(Z)){J.add(W.substring(Z.length).trim());break}return[...J]}function tU($,f,J){if(f.length===0)return $;let W=$.split(`
369
- `),Z=[],Q=0;for(let j of f){if(j.origIndex>W.length)throw new Z0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${W.length}`);if(Q>j.origIndex)throw new Z0(`${J}: currentIndex ${Q} > chunk.origIndex ${j.origIndex}`);Z.push(...W.slice(Q,j.origIndex)),Z.push(...j.insLines),Q=j.origIndex+j.delLines.length}return Z.push(...W.slice(Q)),Z.join(`
370
- `)}async function sU($,f,J,W){let Z=aU($,[v.UPDATE,v.DELETE]),Q={};for(let j of Z){let H=GZ(f,j,W),X;try{X=await I0.readFile(H,J)}catch{throw new Z0(`File not found: ${j}`)}Q[j]=X.replace(/\r\n/g,`
371
- `)}return Q}function oU($,f){let J={};for(let[W,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[W]={type:"delete",oldContent:f[W]};break;case"add":if(Z.newFile===void 0)throw new Z0("ADD action without file content");J[W]={type:"add",newContent:Z.newFile};break;case"update":J[W]={type:"update",oldContent:f[W],newContent:tU(f[W]??"",Z.chunks,W),movePath:Z.movePath};break}return J}async function eU($,f,J,W){let Z=[];for(let[Q,j]of Object.entries($)){let H=GZ(f,Q,W);switch(j.type){case"delete":await I0.rm(H,{force:!0}),Z.push(`${Q}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new Z0(`Cannot create ${Q} with no content`);await I0.mkdir(x0.dirname(H),{recursive:!0}),await I0.writeFile(H,j.newContent,{encoding:J}),Z.push(Q);break;case"update":{if(j.newContent===void 0)throw new Z0(`UPDATE change for ${Q} has no new content`);if(j.movePath){let X=GZ(f,j.movePath,W);await I0.mkdir(x0.dirname(X),{recursive:!0}),await I0.writeFile(X,j.newContent,{encoding:J}),await I0.rm(H,{force:!0}),Z.push(`${Q} -> ${j.movePath}`)}else await I0.writeFile(H,j.newContent,{encoding:J}),Z.push(Q);break}}}return Z}function S8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(W,Z,Q)=>{let j=nU(W.input),H=await sU(j.lines,Z,f,J),X=new KZ(j.lines,H),{patch:A,fuzz:Y}=X.parse(),V=oU(A,H),B=await eU(V,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of B)K.push(G);if(Y>0)K.push(`Note: Patch applied with fuzz factor ${Y}`);if(A.warnings&&A.warnings.length>0)for(let G of A.warnings)K.push(`Warning (${G.path}): ${G.message}`);return K.join(`
372
- `)}}import{spawn as vj}from"node:child_process";import{getDefaultShell as $F,getShellArgs as fF}from"@cline/shared";function JF($,f,J,W,Z){return new Promise((Q,j)=>{let H=process.platform==="win32",X=vj($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!H}),A=X.pid,Y="",V="",B=0,K=!1,G=!1,R=(D)=>{if(G)return;G=!0,D()},P=()=>{if(!A)return;if(H){vj("taskkill",["/pid",String(A),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-A,"SIGKILL")}catch{X.kill("SIGKILL")}},U=(D)=>{K=!0,P(),R(()=>j(D))},F=setTimeout(()=>U(new I1(`Command timed out after ${J}ms`,J)),J),z=()=>U(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",z);let _=()=>{clearTimeout(F),f.signal?.removeEventListener("abort",z)};X.stdout?.on("data",(D)=>{if(B+=D.length,B<=W)Y+=D.toString()}),X.stderr?.on("data",(D)=>{if(B+=D.length,B<=W)V+=D.toString()}),X.on("close",(D)=>{if(_(),K)return;let O=Z?Y+(V?`
397
+ *** End Patch`;function vQ(f,$={}){let J=$.applyPatchTimeoutMs??30000,Q=$.cwd??process.cwd();return If({name:"apply_patch",description:oU,inputSchema:Vf(c8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=xf(zH,Z),H=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await Yf(f({input:H},Q,W),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(X){return{query:"apply_patch",result:"",error:`apply_patch failed: ${A$(X)}`,success:!1}}}})}function cQ(f,$={}){let J=$.editorTimeoutMs??30000,Q=$.cwd??process.cwd();return If({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:Vf(v8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=xf(v8,Z),H=j.insert_line==null?"edit":"insert",X=MH(j);if(X)return{query:`${H}:${j.path}`,result:"",error:X,success:!1};try{let A=await Yf(f(j,Q,W),J,`Editor operation timed out after ${J}ms`);return{query:`${H}:${j.path}`,result:A,success:!0}}catch(A){let Y=A$(A);return{query:`${H}:${j.path}`,result:"",error:`Editor operation failed: ${Y}`,success:!1}}}})}function i$(f,$={}){let J=$.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=If({name:"skills",description:Q,inputSchema:Vf(u8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,j)=>{let H=xf(u8,W);return Yf(f(H.skill,H.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let W=f.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(W&&W.length>0)return`${Q} Available skills: ${W.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),Z}function uQ(f){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:Vf(d8),retryable:!1,maxRetries:0,execute:async($,J)=>{let Q=xf(d8,$);return f(Q.question,Q.options,J)}}}function dQ(f,$={}){let J=$.submitTimeoutMs??15000;return If({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:Vf(l8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let W=xf(l8,Q);return Yf(f(W.summary,W.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function Y$(f){let{executors:$,enableReadFiles:J=!0,enableSearch:Q=!0,enableBash:Z=!0,enableWebFetch:W=!0,enableApplyPatch:j=!1,enableEditor:H=!0,enableSkills:X=!0,enableAskQuestion:A=!0,enableSubmitAndExit:Y=!1,...V}=f,B=[];if(J&&$.readFile)B.push(kQ($.readFile,V));if(Q&&$.search)B.push(IQ($.search,V));if(Z&&$.bash)if(process.platform==="win32")B.push(gQ($.bash,V));else B.push(xQ($.bash,V));if(W&&$.webFetch)B.push(mQ($.webFetch,V));if(H&&$.editor)B.push(cQ($.editor,V));else if(j&&$.applyPatch)B.push(vQ($.applyPatch,V));if(X&&$.skills)B.push(i$($.skills,V));let K=Y?$.submit:void 0;if(A&&$.askQuestion&&!K)B.push(uQ($.askQuestion));if(K)B.push(dQ(K,V));return B}import*as m0 from"node:fs/promises";import*as v0 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"},SH=["%%bash","apply_patch","EOF","```"];class Z0 extends Error{constructor(f){super(f);this.name="DiffError"}}function g0(f){let $={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return f.normalize("NFC").replace(/./gu,(J)=>$[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class lQ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(f,$){this.lines=f;this.currentFiles=$}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning(f){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(f)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(u.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(u.END)??!1}parseNextAction(){let f=this.lines[this.index];if(f?.startsWith(u.UPDATE)){this.parseUpdate(f.substring(u.UPDATE.length).trim());return}if(f?.startsWith(u.DELETE)){this.parseDelete(f.substring(u.DELETE.length).trim());return}if(f?.startsWith(u.ADD)){this.parseAdd(f.substring(u.ADD.length).trim());return}throw new Z0(`Unknown line while parsing: ${f}`)}checkDuplicate(f,$){if(f in this.patch.actions)throw new Z0(`Duplicate ${$} for file: ${f}`)}parseUpdate(f){this.checkDuplicate(f,"update"),this.currentPath=f,this.index++;let $=this.lines[this.index]?.startsWith(u.MOVE)?(this.lines[this.index++]??"").substring(u.MOVE.length).trim():void 0;if(!(f in this.currentFiles))throw new Z0(`Update File Error: Missing File: ${f}`);let J=this.currentFiles[f]??"",Q=this.parseUpdateFile(J,f);Q.movePath=$,this.patch.actions[f]=Q,this.currentPath=void 0}parseUpdateFile(f,$){let J={type:"update",chunks:[]},Q=f.split(`
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],H=j?.startsWith("@@ ")?j.substring(3):void 0;if(H!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new Z0(`Invalid Line:
399
+ ${this.lines[this.index]}`);if(H?.trim()){let G=g0(H.trim());for(let F=Z;F<Q.length;F++){let U=Q[F];if(U&&(g0(U)===G||g0(U.trim())===G)){if(Z=F+1,g0(U.trim())===G&&g0(U)!==G)this.fuzz++;break}}}let[A,Y,V,B]=$R(this.lines,this.index),[K,P,R]=fR(Q,A,Z,B);if(K===-1){let G=A.join(`
400
+ `);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:G.length>200?`${G.substring(0,200)}...`:G}),this.index=V}else{this.fuzz+=P;for(let G of Y)G.origIndex+=K,J.chunks.push(G);Z=K+A.length,this.index=V}}return J}parseDelete(f){if(this.checkDuplicate(f,"delete"),!(f in this.currentFiles))throw new Z0(`Delete File Error: Missing File: ${f}`);this.patch.actions[f]={type:"delete",chunks:[]},this.index++}parseAdd(f){if(this.checkDuplicate(f,"add"),f in this.currentFiles)throw new Z0(`Add File Error: File already exists: ${f}`);this.index++;let $=[],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 Z0(`Invalid Add File line (missing '+'): ${Q}`);$.push(Q.substring(1))}this.patch.actions[f]={type:"add",newFile:$.join(`
401
+ `),chunks:[]}}}function CH(f,$){let J=f.length>$.length?f:$,Q=f.length>$.length?$:f;if(J.length===0)return 1;let Z=eU(Q,J);return(J.length-Z)/J.length}function eU(f,$){let J=$.length+1,Q=f.length+1,Z=Array(J*Q).fill(0),W=(H,X)=>Z[H*Q+X]??0,j=(H,X,A)=>{Z[H*Q+X]=A};for(let H=0;H<=$.length;H++)j(H,0,H);for(let H=0;H<=f.length;H++)j(0,H,H);for(let H=1;H<=$.length;H++)for(let X=1;X<=f.length;X++)if($[H-1]===f[X-1])j(H,X,W(H-1,X-1));else j(H,X,1+Math.min(W(H-1,X-1),W(H,X-1),W(H-1,X)));return W($.length,f.length)}function fR(f,$,J,Q){if($.length===0)return[J,0,1];let Z=0,W=(j)=>{let H=g0($.join(`
402
+ `));for(let A=j;A<f.length;A++){let Y=g0(f.slice(A,A+$.length).join(`
403
+ `));if(Y===H)return[A,0,1];let V=CH(Y,H);if(V>Z)Z=V}for(let A=j;A<f.length;A++){let Y=g0(f.slice(A,A+$.length).map((B)=>B.trimEnd()).join(`
404
+ `)),V=g0($.map((B)=>B.trimEnd()).join(`
405
+ `));if(Y===V)return[A,1,1]}for(let A=j;A<f.length;A++){let Y=g0(f.slice(A,A+$.length).map((B)=>B.trim()).join(`
406
+ `)),V=g0($.map((B)=>B.trim()).join(`
407
+ `));if(Y===V)return[A,100,1]}let X=0.66;for(let A=j;A<f.length;A++){let Y=g0(f.slice(A,A+$.length).join(`
408
+ `)),V=CH(Y,H);if(V>=X)return[A,1000,V];if(V>Z)Z=V}return[-1,0,Z]};if(Q){let[j,H,X]=W(f.length-$.length);if(j!==-1)return[j,H,X];return[j,H,X]=W(J),[j,H+1e4,X]}return W(J)}function $R(f,$){let J=$,Q=[],Z=[],W=[],j=[],H="keep",X=["@@",u.END,u.UPDATE,u.DELETE,u.ADD,u.END_FILE];while(J<f.length){let A=f[J];if(!A||X.some((B)=>A.startsWith(B.trim())))break;if(A==="***")break;if(A.startsWith("***"))throw new Z0(`Invalid line: ${A}`);J++;let Y=H,V=A;if(V[0]==="+")H="add";else if(V[0]==="-")H="delete";else if(V[0]===" ")H="keep";else H="keep",V=` ${V}`;if(V=V.slice(1),H==="keep"&&Y!==H){if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});Z=[],W=[]}if(H==="delete")Z.push(V),Q.push(V);else if(H==="add")W.push(V);else Q.push(V)}if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});if(J<f.length&&f[J]===u.END_FILE)return J++,[Q,j,J,!0];return[Q,j,J,!1]}function pQ(f,$,J){let Q=v0.isAbsolute($),Z=Q?v0.normalize($):v0.resolve(f,$);if(!J||Q)return Z;let W=v0.relative(f,Z);if(W.startsWith("..")||v0.isAbsolute(W))throw new Z0(`Path must stay within cwd: ${$}`);return Z}function JR(f){return f.split(`
409
+ `).map(($)=>$.replace(/\r$/,""))}function EH(f){if(f.trim()==="")return!1;return SH.some(($)=>f.startsWith($))}function QR(f){let $=0,J=f.length;while($<J&&EH(f[$]??""))$++;while(J>$&&EH(f[J-1]??""))J--;return f.slice($,J)}function ZR(f){let $=JR(f),J=$.findIndex((j)=>j.startsWith(u.BEGIN)),Q=-1;for(let j=$.length-1;j>=0;j--)if($[j]?.startsWith(u.END)){Q=j;break}if(J!==-1||Q!==-1){if(J===-1||Q===-1||Q<J)throw new Z0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:$.slice(J,Q+1)}}let Z=QR($);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 WR(f,$){let J=new Set;for(let Q of f)for(let Z of $)if(Q.startsWith(Z)){J.add(Q.substring(Z.length).trim());break}return[...J]}function jR(f,$,J){if($.length===0)return f;let Q=f.split(`
410
+ `),Z=[],W=0;for(let j of $){if(j.origIndex>Q.length)throw new Z0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${Q.length}`);if(W>j.origIndex)throw new Z0(`${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 HR(f,$,J,Q){let Z=WR(f,[u.UPDATE,u.DELETE]),W={};for(let j of Z){let H=pQ($,j,Q),X;try{X=await m0.readFile(H,J)}catch{throw new Z0(`File not found: ${j}`)}W[j]=X.replace(/\r\n/g,`
412
+ `)}return W}function XR(f,$){let J={};for(let[Q,Z]of Object.entries(f.actions))switch(Z.type){case"delete":J[Q]={type:"delete",oldContent:$[Q]};break;case"add":if(Z.newFile===void 0)throw new Z0("ADD action without file content");J[Q]={type:"add",newContent:Z.newFile};break;case"update":J[Q]={type:"update",oldContent:$[Q],newContent:jR($[Q]??"",Z.chunks,Q),movePath:Z.movePath};break}return J}async function AR(f,$,J,Q){let Z=[];for(let[W,j]of Object.entries(f)){let H=pQ($,W,Q);switch(j.type){case"delete":await m0.rm(H,{force:!0}),Z.push(`${W}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new Z0(`Cannot create ${W} with no content`);await m0.mkdir(v0.dirname(H),{recursive:!0}),await m0.writeFile(H,j.newContent,{encoding:J}),Z.push(W);break;case"update":{if(j.newContent===void 0)throw new Z0(`UPDATE change for ${W} has no new content`);if(j.movePath){let X=pQ($,j.movePath,Q);await m0.mkdir(v0.dirname(X),{recursive:!0}),await m0.writeFile(X,j.newContent,{encoding:J}),await m0.rm(H,{force:!0}),Z.push(`${W} -> ${j.movePath}`)}else await m0.writeFile(H,j.newContent,{encoding:J}),Z.push(W);break}}}return Z}function p8(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0}=f;return async(Q,Z,W)=>{let j=ZR(Q.input),H=await HR(j.lines,Z,$,J),X=new lQ(j.lines,H),{patch:A,fuzz:Y}=X.parse(),V=XR(A,H),B=await AR(V,Z,$,J),K=["Successfully applied patch to the following files:"];for(let P of B)K.push(P);if(Y>0)K.push(`Note: Patch applied with fuzz factor ${Y}`);if(A.warnings&&A.warnings.length>0)for(let P of A.warnings)K.push(`Warning (${P.path}): ${P.message}`);return K.join(`
413
+ `)}}import{spawn as hH}from"node:child_process";import{getDefaultShell as YR,getShellArgs as VR}from"@cline/shared";function BR(f,$,J,Q,Z){return new Promise((W,j)=>{let H=process.platform==="win32",X=hH(f.executable,f.args,{cwd:f.cwd,env:{...process.env,...f.env},stdio:["pipe","pipe","pipe"],detached:!H}),A=X.pid,Y="",V="",B=0,K=!1,P=!1,R=(L)=>{if(P)return;P=!0,L()},G=()=>{if(!A)return;if(H){hH("taskkill",["/pid",String(A),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-A,"SIGKILL")}catch{X.kill("SIGKILL")}},F=(L)=>{K=!0,G(),R(()=>j(L))},U=setTimeout(()=>F(new r$(`Command timed out after ${J}ms`,J)),J),_=()=>F(Error("Command was aborted"));if($.signal)$.signal.addEventListener("abort",_);let M=()=>{clearTimeout(U),$.signal?.removeEventListener("abort",_)};X.stdout?.on("data",(L)=>{if(B+=L.length,B<=Q)Y+=L.toString()}),X.stderr?.on("data",(L)=>{if(B+=L.length,B<=Q)V+=L.toString()}),X.on("close",(L)=>{if(M(),K)return;let D=Z?Y+(V?`
373
414
  [stderr]
374
- ${V}`:""):Y;if(B>W)O+=`
375
-
376
- [Output truncated: ${B} bytes total, showing first ${W} bytes]`;if(D!==0)R(()=>j(Error(V||`Command exited with code ${D}`)));else R(()=>Q(O))}),X.on("error",(D)=>{_(),R(()=>j(Error(`Failed to execute command: ${D.message}`)))})})}function h8($={}){let{shell:f=$F(process.platform),timeoutMs:J=30000,maxOutputBytes:W=1e6,env:Z={},combineOutput:Q=!0}=$;return(j,H,X)=>{let A=typeof j!=="string";return JF({executable:A?j.command:f,args:A?j.args??[]:fF(f,j),cwd:H,env:Z},X,J,W,Q)}}import*as e0 from"node:fs/promises";import*as o0 from"node:path";function WF($,f,J){let W=o0.isAbsolute(f),Z=W?o0.normalize(f):o0.resolve($,f);if(!J)return Z;if(W)return Z;let Q=o0.relative($,Z);if(Q.startsWith("..")||o0.isAbsolute(Q))throw Error(`Path must stay within cwd: ${f}`);return Z}function ZF($,f){if(f.length===0)return 0;return $.split(f).length-1}function QF($,f,J){let W=$.split(`
377
- `),Z=f.split(`
378
- `),Q=Math.max(W.length,Z.length),j=["```diff"],H=0;for(let X=0;X<Q;X++){if(H>=J){j.push("... diff truncated ...");break}let A=W[X],Y=Z[X];if(A===Y)continue;let V=X+1;if(A!==void 0)j.push(`-${V}: ${A}`),H++;if(Y!==void 0&&H<J)j.push(`+${V}: ${Y}`),H++}return j.push("```"),j.join(`
379
- `)}async function jF($,f,J){return await e0.mkdir(o0.dirname($),{recursive:!0}),await e0.writeFile($,f,{encoding:J}),`File created successfully at: ${$}`}async function HF($){try{return await e0.access($),!0}catch{return!1}}async function XF($,f,J,W,Z){let Q=await e0.readFile($,W),j=ZF(Q,f);if(j===0)throw Error(`No replacement performed: text not found in ${$}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let H=Q.replace(f,J??"");await e0.writeFile($,H,{encoding:W});let X=QF(Q,H,Z);return`Edited ${$}
380
- ${X}`}async function AF($,f,J,W){let Q=(await e0.readFile($,W)).split(`
381
- `),j=Q.length+1;if(f<1||f>j)throw Error(`Invalid insert_line: ${f}. insert_line must be a positive one-based boundary line in the range 1-${j}. Use ${j} to append at EOF.`);let H=f-1;return Q.splice(H,0,...J.split(`
382
- `)),await e0.writeFile($,Q.join(`
383
- `),{encoding:W}),`Inserted content at line ${f} in ${$}.`}function C8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=$;return async(Z,Q,j)=>{let H=WF(Q,Z.path,J);if(Z.insert_line!=null)return AF(H,Z.insert_line,Z.new_text,f);if(!await HF(H))return jF(H,Z.new_text,f);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return XF(H,Z.old_text,Z.new_text,f,W)}}import*as E8 from"node:fs/promises";import*as W1 from"node:path";import{resolveExistingFilePath as YF}from"@cline/shared/storage";var VF=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),BF={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function b8($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:W}={...BF,...$};return async(Z,Q)=>{let{path:j,start_line:H,end_line:X}=Z,A=W1.isAbsolute(j)?W1.normalize(j):W1.resolve(process.cwd(),j),Y=YF(A)??A,V=W1.extname(Y).toLowerCase(),B=VF.get(V),K=await E8.stat(Y);if(!K.isFile())throw Error(`Path is not a file: ${Y}`);if(K.size>f)throw Error(`File too large: ${K.size} bytes (max: ${f} bytes). Consider reading specific sections or using a different approach.`);if(B){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let z=await E8.readFile(Y);return[{type:"text",text:"Successfully read image"},{type:"image",data:z.toString("base64"),mediaType:B}]}let R=(await E8.readFile(Y,J)).split(`
384
- `),P=Math.max((H??1)-1,0),U=Math.min(X??R.length,R.length),F=R.slice(P,U);if(W){let z=String(R.length).length;return F.map((_,D)=>`${String(P+D+1).padStart(z," ")} | ${_}`).join(`
385
- `)}return F.join(`
386
- `)}}import{spawn as ij}from"node:child_process";import*as nj from"node:fs/promises";import*as o4 from"node:path";var rj={};w(rj,{prewarmFileIndex:()=>s4,getFileIndex:()=>E$,enrichPromptWithMentions:()=>gf});import{spawn as KF}from"node:child_process";import{readdir as GF}from"node:fs/promises";import UZ from"node:path";import{isMainThread as dj,parentPort as uj,Worker as PF}from"node:worker_threads";var UF=15000,FF=600000,RF=1000,DF=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function cj($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var mf=new Map;function LF(){if(!dj)return!1;return!0}function OF($){if(mf.size<=1)return;for(let[f,J]of mf.entries()){if(J.pending)continue;if($-J.lastAccessedAt>FF)mf.delete(f)}}function zF($,f){return UZ.relative($,f).split(UZ.sep).join("/")}async function _F($){let J=(await new Promise((W,Z)=>{let Q=KF("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),j="",H="";Q.stdout.on("data",(X)=>{j+=X.toString()}),Q.stderr.on("data",(X)=>{H+=X.toString()}),Q.on("error",Z),Q.on("close",(X)=>{if(X===0){W(j);return}Z(Error(H||`rg exited with code ${X}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function lj($,f,J){let W;try{W=await GF(f,{withFileTypes:!0})}catch(Z){if(cj(Z))return;throw Z}for(let Z of W){let Q=UZ.join(f,Z.name);if(Z.isDirectory()){if(DF.has(Z.name))continue;try{await lj($,Q,J)}catch(j){if(cj(j))continue;throw j}continue}if(Z.isFile())J.add(zF($,Q))}}async function TF($){let f=new Set;return await lj($,$,f),f}async function t4($){try{return await _F($)}catch{return TF($)}}function NF(){if(dj||!uj)return;let $=uj;$.on("message",(f)=>{if(f.type!=="index")return;t4(f.cwd).then((J)=>{let W={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(W)})})}class pj{worker=new PF(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let f=++this.nextRequestId,J=new Promise((Z,Q)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},RF);j.unref(),this.pending.set(f,{resolve:(H)=>{clearTimeout(j),Z(H)},reject:(H)=>{clearTimeout(j),Q(H)}})}),W={type:"index",requestId:f,cwd:$};return this.worker.postMessage(W),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}NF();var PZ;function MF(){if(!LF())return null;if(PZ===void 0)PZ=new pj;return PZ}async function yF($){let f=MF();if(!f)return t4($);try{let J=await f.requestIndex($);if(J===null)return t4($);return new Set(J)}catch{return t4($)}}async function E$($,f={}){let J=f.ttlMs??UF,W=Date.now();OF(W);let Z=mf.get($);if(Z&&J>0&&W-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=W,Z.files;if(Z?.pending)return Z.lastAccessedAt=W,Z.pending;let Q=yF($).then((j)=>{return mf.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return mf.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function s4($,f={}){await E$($,{...f,ttlMs:0})}import{stat as qF}from"node:fs/promises";import m1 from"node:path";var wF=/[),.:;!?`'"]+$/,SF=/^[(`'"]+/;function hF($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of f){let Z=(W[2]??"").trim();if(Z.length===0)continue;let Q=Z.replace(SF,"").replace(wF,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function CF($,f){let J=$.replace(/\\/g,"/"),W=m1.isAbsolute(J)?m1.resolve(J):m1.resolve(f,J),Z=m1.relative(f,W);if(Z.startsWith("..")||m1.isAbsolute(Z))return;return Z.split(m1.sep).join("/")}async function gf($,f,J={}){let W=hF($);if(W.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:Q,maxTotalBytes:j}=J,H=await E$(f,{ttlMs:J.ttlMs}),X=[],A=[],Y=[],V=0;for(let B of W){if(Z&&Y.length>=Z){A.push(B);continue}let K=CF(B,f);if(!K||!H.has(K)){A.push(B);continue}if(!Q||!j){X.push(K);continue}let G=m1.join(f,K);try{if(!(await qF(G)).isFile()){A.push(B);continue}let P=V+Q;if(P>j){A.push(B);continue}V=P,X.push(K)}catch{A.push(B)}}return{prompt:$,mentions:W,matchedFiles:X,ignoredMentions:A}}var EF=["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"],bF=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],g1=null;function kF(){if(g1!==null)return Promise.resolve(g1);return new Promise(($)=>{let f=ij("rg",["--version"],{stdio:["ignore","pipe","pipe"]});f.on("close",(J)=>{g1=J===0,$(g1)}),f.on("error",()=>{g1=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(g1===null)g1=!1,$(!1)},1000)})}function IF($,f,J,W,Z=5000,Q){return new Promise((j)=>{let H=ij("rg",["--json",`--context=${W}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"]}),X="",A=!1,Y=()=>{if(!H.killed)H.kill("SIGTERM")},V=setTimeout(()=>{if(!A)A=!0,Y(),j(null)},Z),B=(K)=>{if(!A)A=!0,clearTimeout(V),Y(),j(K)};if(Q?.aborted){Y(),j(null);return}Q?.addEventListener("abort",()=>{B(null)}),H.stdout.on("data",(K)=>{X+=K.toString()}),H.stderr.on("data",()=>{}),H.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=X.split(`
387
- `).filter((P)=>P.trim());for(let P of R){if(G.length>=J)break;let U=JSON.parse(P);if(U.type==="match"){let F=U.data,z=[];if(U.data.submatches&&U.data.submatches.length>0){let _=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(_?.start??0)+1,match:_?.match?.text??"",context:z})}}else if(U.type==="context"&&G.length>0){let F=G[G.length-1],z=U.data.line_number===F.line?">":" ";F.context.push(`${z} ${U.data.line_number}: ${U.data.lines?.text??U.data.line?.text??""}`)}}B(G.length>0?G:null)}catch{B(null)}return}B(null)}),H.on("error",()=>{B(null)})})}function xF($,f,J,W){let Z=$.split("/"),Q=Z[Z.length-1]??"";if(Z.length-1>W)return!1;for(let X=0;X<Z.length-1;X++)if(f.has(Z[X]??""))return!1;let H=o4.posix.extname(Q).slice(1).toLowerCase();return J.has(H)||!H&&!Q.startsWith(".")}function k8($={}){let{includeExtensions:f=EF,excludeDirs:J=bF,maxResults:W=100,contextLines:Z=2,maxDepth:Q=20}=$,j=new Set(J),H=new Set(f.map((X)=>X.toLowerCase()));return async(X,A,Y)=>{if(Y.signal?.aborted)throw Error("Search operation aborted");let V=await kF(),B=null;if(V)B=await IF(X,A,W,Z,5000,Y.signal);if(B){let F=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${X}`,""];for(let z of B)F.push(`${z.file}:${z.line}:${z.column}`),F.push(...z.context),F.push("");if(B.length>=W)F.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return F.join(`
388
- `)}let K;try{K=new RegExp(X,"gim")}catch(F){throw Error(`Invalid regex pattern: ${X}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,P=await E$(A);for(let F of P){if(Y.signal?.aborted)throw Error("Search operation aborted");if(!xF(F,j,H,Q))continue;if(G.length>=W)break;R++;let z=o4.join(A,F);try{let D=(await nj.readFile(z,"utf-8")).split(`
389
- `);for(let O=0;O<D.length;O++){let N=D[O];K.lastIndex=0;let q=K.exec(N);while(q!==null){if(G.length>=W)break;let $0=Math.max(0,O-Z),A0=Math.min(D.length-1,O+Z),o=[];for(let Y0=$0;Y0<=A0;Y0++){let i=Y0===O?">":" ";o.push(`${i} ${Y0+1}: ${D[Y0]}`)}if(G.push({file:F,line:O+1,column:q.index+1,match:q[0],context:o}),q.index===K.lastIndex)K.lastIndex++;q=K.exec(N)}}}catch{}}if(G.length===0)return`No results found for pattern: ${X}
390
- Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${X}`,`Searched ${R} files.`,""];for(let F of G)U.push(`${F.file}:${F.line}:${F.column}`),U.push(...F.context),U.push("");if(G.length>=W)U.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return U.join(`
391
- `)}}function mF($){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,`
392
- `).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,`
415
+ ${V}`:""):Y;if(B>Q)D+=`
416
+
417
+ [Output truncated: ${B} bytes total, showing first ${Q} bytes]`;if(L!==0)R(()=>j(Error(V||`Command exited with code ${L}`)));else R(()=>W(D))}),X.on("error",(L)=>{M(),R(()=>j(Error(`Failed to execute command: ${L.message}`)))})})}function r8(f={}){let{shell:$=YR(process.platform),timeoutMs:J=30000,maxOutputBytes:Q=1e6,env:Z={},combineOutput:W=!0}=f;return(j,H,X)=>{let A=typeof j!=="string";return BR({executable:A?j.command:$,args:A?j.args??[]:VR($,j),cwd:H,env:Z},X,J,Q,W)}}import*as Jf from"node:fs/promises";import*as $f from"node:path";function KR(f,$,J){let Q=$f.isAbsolute($),Z=Q?$f.normalize($):$f.resolve(f,$);if(!J)return Z;if(Q)return Z;let W=$f.relative(f,Z);if(W.startsWith("..")||$f.isAbsolute(W))throw Error(`Path must stay within cwd: ${$}`);return Z}function PR(f,$){if($.length===0)return 0;return f.split($).length-1}function GR(f,$,J){let Q=f.split(`
418
+ `),Z=$.split(`
419
+ `),W=Math.max(Q.length,Z.length),j=["```diff"],H=0;for(let X=0;X<W;X++){if(H>=J){j.push("... diff truncated ...");break}let A=Q[X],Y=Z[X];if(A===Y)continue;let V=X+1;if(A!==void 0)j.push(`-${V}: ${A}`),H++;if(Y!==void 0&&H<J)j.push(`+${V}: ${Y}`),H++}return j.push("```"),j.join(`
420
+ `)}async function FR(f,$,J){return await Jf.mkdir($f.dirname(f),{recursive:!0}),await Jf.writeFile(f,$,{encoding:J}),`File created successfully at: ${f}`}async function UR(f){try{return await Jf.access(f),!0}catch{return!1}}async function RR(f,$,J,Q,Z){let W=await Jf.readFile(f,Q),j=PR(W,$);if(j===0)throw Error(`No replacement performed: text not found in ${f}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${f}.`);let H=W.replace($,J??"");await Jf.writeFile(f,H,{encoding:Q});let X=GR(W,H,Z);return`Edited ${f}
421
+ ${X}`}async function DR(f,$,J,Q){let W=(await Jf.readFile(f,Q)).split(`
422
+ `),j=W.length+1;if($<1||$>j)throw Error(`Invalid insert_line: ${$}. insert_line must be a positive one-based boundary line in the range 1-${j}. Use ${j} to append at EOF.`);let H=$-1;return W.splice(H,0,...J.split(`
423
+ `)),await Jf.writeFile(f,W.join(`
424
+ `),{encoding:Q}),`Inserted content at line ${$} in ${f}.`}function i8(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0,maxDiffLines:Q=200}=f;return async(Z,W,j)=>{let H=KR(W,Z.path,J);if(Z.insert_line!=null)return DR(H,Z.insert_line,Z.new_text,$);if(!await UR(H))return FR(H,Z.new_text,$);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return RR(H,Z.old_text,Z.new_text,$,Q)}}import*as n8 from"node:fs/promises";import*as V$ from"node:path";import{resolveExistingFilePath as LR}from"@cline/shared/storage";var OR=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),_R={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function a8(f={}){let{maxFileSizeBytes:$,encoding:J,includeLineNumbers:Q}={..._R,...f};return async(Z,W)=>{let{path:j,start_line:H,end_line:X}=Z,A=V$.isAbsolute(j)?V$.normalize(j):V$.resolve(process.cwd(),j),Y=LR(A)??A,V=V$.extname(Y).toLowerCase(),B=OR.get(V),K=await n8.stat(Y);if(!K.isFile())throw Error(`Path is not a file: ${Y}`);if(K.size>$)throw Error(`File too large: ${K.size} bytes (max: ${$} bytes). Consider reading specific sections or using a different approach.`);if(B){if(W.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let _=await n8.readFile(Y);return[{type:"text",text:"Successfully read image"},{type:"image",data:_.toString("base64"),mediaType:B}]}let R=(await n8.readFile(Y,J)).split(`
425
+ `),G=Math.max((H??1)-1,0),F=Math.min(X??R.length,R.length),U=R.slice(G,F);if(Q){let _=String(R.length).length;return U.map((M,L)=>`${String(G+L+1).padStart(_," ")} | ${M}`).join(`
426
+ `)}return U.join(`
427
+ `)}}import{spawn as vH}from"node:child_process";import*as cH from"node:fs/promises";import*as _6 from"node:path";var mH={};q(mH,{prewarmFileIndex:()=>O6,getFileIndex:()=>gf,enrichPromptWithMentions:()=>e1});import{spawn as TR}from"node:child_process";import{readdir as zR}from"node:fs/promises";import iQ from"node:path";import{isMainThread as IH,parentPort as bH,Worker as MR}from"node:worker_threads";var NR=15000,qR=600000,yR=1000,wR=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function kH(f){let $=f&&typeof f==="object"&&"code"in f?String(f.code??""):"";return $==="EACCES"||$==="EPERM"||$==="ENOENT"}var o1=new Map;function CR(){if(!IH)return!1;return!0}function SR(f){if(o1.size<=1)return;for(let[$,J]of o1.entries()){if(J.pending)continue;if(f-J.lastAccessedAt>qR)o1.delete($)}}function ER(f,$){return iQ.relative(f,$).split(iQ.sep).join("/")}async function hR(f){let J=(await new Promise((Q,Z)=>{let W=TR("rg",["--files","--hidden","-g","!.git"],{cwd:f,stdio:["ignore","pipe","pipe"]}),j="",H="";W.stdout.on("data",(X)=>{j+=X.toString()}),W.stderr.on("data",(X)=>{H+=X.toString()}),W.on("error",Z),W.on("close",(X)=>{if(X===0){Q(j);return}Z(Error(H||`rg exited with code ${X}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(J)}async function xH(f,$,J){let Q;try{Q=await zR($,{withFileTypes:!0})}catch(Z){if(kH(Z))return;throw Z}for(let Z of Q){let W=iQ.join($,Z.name);if(Z.isDirectory()){if(wR.has(Z.name))continue;try{await xH(f,W,J)}catch(j){if(kH(j))continue;throw j}continue}if(Z.isFile())J.add(ER(f,W))}}async function bR(f){let $=new Set;return await xH(f,f,$),$}async function L6(f){try{return await hR(f)}catch{return bR(f)}}function kR(){if(IH||!bH)return;let f=bH;f.on("message",($)=>{if($.type!=="index")return;L6($.cwd).then((J)=>{let Q={type:"indexResult",requestId:$.requestId,files:Array.from(J)};f.postMessage(Q)}).catch((J)=>{let Q={type:"indexResult",requestId:$.requestId,error:J instanceof Error?J.message:"Failed to build file index"};f.postMessage(Q)})})}class gH{worker=new MR(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(f)=>{if(f.type!=="indexResult")return;let $=this.pending.get(f.requestId);if(!$)return;if(this.pending.delete(f.requestId),f.error){$.reject(Error(f.error));return}$.resolve(f.files??[])}),this.worker.on("error",(f)=>{this.flushPending(f)}),this.worker.on("exit",(f)=>{if(f!==0)this.flushPending(Error(`File index worker exited with code ${f}`))})}requestIndex(f){let $=++this.nextRequestId,J=new Promise((Z,W)=>{let j=setTimeout(()=>{this.pending.delete($),Z(null)},yR);j.unref(),this.pending.set($,{resolve:(H)=>{clearTimeout(j),Z(H)},reject:(H)=>{clearTimeout(j),W(H)}})}),Q={type:"index",requestId:$,cwd:f};return this.worker.postMessage(Q),J}flushPending(f){for(let[$,J]of this.pending.entries())J.reject(f),this.pending.delete($)}}kR();var rQ;function IR(){if(!CR())return null;if(rQ===void 0)rQ=new gH;return rQ}async function xR(f){let $=IR();if(!$)return L6(f);try{let J=await $.requestIndex(f);if(J===null)return L6(f);return new Set(J)}catch{return L6(f)}}async function gf(f,$={}){let J=$.ttlMs??NR,Q=Date.now();SR(Q);let Z=o1.get(f);if(Z&&J>0&&Q-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=Q,Z.files;if(Z?.pending)return Z.lastAccessedAt=Q,Z.pending;let W=xR(f).then((j)=>{return o1.set(f,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return o1.set(f,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:Q,pending:W}),W}async function O6(f,$={}){await gf(f,{...$,ttlMs:0})}import{stat as gR}from"node:fs/promises";import n$ from"node:path";var mR=/[),.:;!?`'"]+$/,vR=/^[(`'"]+/;function cR(f){let $=f.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let Q of $){let Z=(Q[2]??"").trim();if(Z.length===0)continue;let W=Z.replace(vR,"").replace(mR,"");if(W.length===0||W.includes("@"))continue;J.push(W)}return Array.from(new Set(J))}function uR(f,$){let J=f.replace(/\\/g,"/"),Q=n$.isAbsolute(J)?n$.resolve(J):n$.resolve($,J),Z=n$.relative($,Q);if(Z.startsWith("..")||n$.isAbsolute(Z))return;return Z.split(n$.sep).join("/")}async function e1(f,$,J={}){let Q=cR(f);if(Q.length===0)return{prompt:f,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:W,maxTotalBytes:j}=J,H=await gf($,{ttlMs:J.ttlMs}),X=[],A=[],Y=[],V=0;for(let B of Q){if(Z&&Y.length>=Z){A.push(B);continue}let K=uR(B,$);if(!K||!H.has(K)){A.push(B);continue}if(!W||!j){X.push(K);continue}let P=n$.join($,K);try{if(!(await gR(P)).isFile()){A.push(B);continue}let G=V+W;if(G>j){A.push(B);continue}V=G,X.push(K)}catch{A.push(B)}}return{prompt:f,mentions:Q,matchedFiles:X,ignoredMentions:A}}var dR=["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"],lR=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],a$=null;function pR(){if(a$!==null)return Promise.resolve(a$);return new Promise((f)=>{let $=vH("rg",["--version"],{stdio:["ignore","pipe","pipe"]});$.on("close",(J)=>{a$=J===0,f(a$)}),$.on("error",()=>{a$=!1,f(!1)}),setTimeout(()=>{if(!$.killed)$.kill("SIGTERM");if(a$===null)a$=!1,f(!1)},1000)})}function rR(f,$,J,Q,Z=5000,W){return new Promise((j)=>{let H=vH("rg",["--json",`--context=${Q}`,"--max-count=1","-i",f],{cwd:$,stdio:["ignore","pipe","pipe"]}),X="",A=!1,Y=()=>{if(!H.killed)H.kill("SIGTERM")},V=setTimeout(()=>{if(!A)A=!0,Y(),j(null)},Z),B=(K)=>{if(!A)A=!0,clearTimeout(V),Y(),j(K)};if(W?.aborted){Y(),j(null);return}W?.addEventListener("abort",()=>{B(null)}),H.stdout.on("data",(K)=>{X+=K.toString()}),H.stderr.on("data",()=>{}),H.on("close",(K)=>{if(K===0||K===1){try{let P=[],R=X.split(`
428
+ `).filter((G)=>G.trim());for(let G of R){if(P.length>=J)break;let F=JSON.parse(G);if(F.type==="match"){let U=F.data,_=[];if(F.data.submatches&&F.data.submatches.length>0){let M=F.data.submatches[0];P.push({file:U.path.text,line:U.line_number,column:(M?.start??0)+1,match:M?.match?.text??"",context:_})}}else if(F.type==="context"&&P.length>0){let U=P[P.length-1],_=F.data.line_number===U.line?">":" ";U.context.push(`${_} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}B(P.length>0?P:null)}catch{B(null)}return}B(null)}),H.on("error",()=>{B(null)})})}function iR(f,$,J,Q){let Z=f.split("/"),W=Z[Z.length-1]??"";if(Z.length-1>Q)return!1;for(let X=0;X<Z.length-1;X++)if($.has(Z[X]??""))return!1;let H=_6.posix.extname(W).slice(1).toLowerCase();return J.has(H)||!H&&!W.startsWith(".")}function t8(f={}){let{includeExtensions:$=dR,excludeDirs:J=lR,maxResults:Q=100,contextLines:Z=2,maxDepth:W=20}=f,j=new Set(J),H=new Set($.map((X)=>X.toLowerCase()));return async(X,A,Y)=>{if(Y.signal?.aborted)throw Error("Search operation aborted");let V=await pR(),B=null;if(V)B=await rR(X,A,Q,Z,5000,Y.signal);if(B){let U=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${X}`,""];for(let _ of B)U.push(`${_.file}:${_.line}:${_.column}`),U.push(..._.context),U.push("");if(B.length>=Q)U.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return U.join(`
429
+ `)}let K;try{K=new RegExp(X,"gim")}catch(U){throw Error(`Invalid regex pattern: ${X}. ${U instanceof Error?U.message:""}`)}let P=[],R=0,G=await gf(A);for(let U of G){if(Y.signal?.aborted)throw Error("Search operation aborted");if(!iR(U,j,H,W))continue;if(P.length>=Q)break;R++;let _=_6.join(A,U);try{let L=(await cH.readFile(_,"utf-8")).split(`
430
+ `);for(let D=0;D<L.length;D++){let y=L[D];K.lastIndex=0;let b=K.exec(y);while(b!==null){if(P.length>=Q)break;let I=Math.max(0,D-Z),o=Math.min(L.length-1,D+Z),A0=[];for(let f0=I;f0<=o;f0++){let t=f0===D?">":" ";A0.push(`${t} ${f0+1}: ${L[f0]}`)}if(P.push({file:U,line:D+1,column:b.index+1,match:b[0],context:A0}),b.index===K.lastIndex)K.lastIndex++;b=K.exec(y)}}}catch{}}if(P.length===0)return`No results found for pattern: ${X}
431
+ Searched ${R} files.`;let F=[`Found ${P.length} result${P.length===1?"":"s"} for pattern: ${X}`,`Searched ${R} files.`,""];for(let U of P)F.push(`${U.file}:${U.line}:${U.column}`),F.push(...U.context),F.push("");if(P.length>=Q)F.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return F.join(`
432
+ `)}}function nR(f){return f.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
433
+ `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,($,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
393
434
  `).replace(/\n{3,}/g,`
394
435
 
395
- `).trim()}function I8($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:Q=!0}=$;return async(j,H,X)=>{let A;try{A=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(A.protocol))throw Error(`Invalid protocol: ${A.protocol}. Only http and https are supported.`);let Y=new AbortController,V=setTimeout(()=>Y.abort(),f),B;if(X.signal)B=()=>Y.abort(),X.signal.addEventListener("abort",B);try{let K=await fetch(j,{method:"GET",headers:{"User-Agent":W,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:Q?"follow":"manual",signal:Y.signal});if(clearTimeout(V),!Q&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let P=[],U=0;while(!0){let{done:N,value:q}=await R.read();if(N)break;if(U+=q.length,U>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);P.push(q)}let F=new Uint8Array(U),z=0;for(let N of P)F.set(N,z),z+=N.length;let _=new TextDecoder("utf-8").decode(F),D;if(G.includes("text/html")||G.includes("application/xhtml"))D=mF(_);else if(G.includes("application/json"))try{let N=JSON.parse(_);D=JSON.stringify(N,null,2)}catch{D=_}else D=_;let O=[`URL: ${j}`,`Content-Type: ${G}`,`Size: ${U} bytes`,"","--- Content ---",D.slice(0,50000)];if(D.length>50000)O.push(`
396
- [Content truncated: showing first 50000 of ${D.length} characters]`);return O.push("","--- Analysis Request ---",`Prompt: ${H}`),O.join(`
397
- `)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(X.signal&&B)X.signal.removeEventListener("abort",B)}}}function vf($={}){return{readFile:b8($.fileRead),search:k8($.search),bash:h8($.bash),webFetch:I8($.webFetch),applyPatch:S8($.applyPatch),editor:C8($.editor)}}var gF={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"},uf=[{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 aj($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((W)=>J.includes(W.toLowerCase()))}function vF($,f,J,W){if($.mode&&$.mode!=="any"&&$.mode!==W)return!1;return aj(f,$.providerIdIncludes)&&aj(J,$.modelIdIncludes)}function cf($,f,J,W){if(!W||W.length===0)return{};let Z=new Map;for(let j of W){if(!vF(j,$,f,J))continue;for(let H of j.disableTools??[])Z.set(H,!1);for(let H of j.enableTools??[])Z.set(H,!0)}let Q={};for(let[j,H]of Z.entries())Q[gF[j]]=H;return Q}var m0={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 b$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function e4($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let W of p$)J[W]=f;return J}function $6($,f){let J=m0[$],{enableSpawnAgent:W,enableAgentTeams:Z,...Q}=J;return J1({...Q,...f})}import{createTool as uR,zodToJsonSchema as cR}from"@cline/shared";import{z as MZ}from"zod";import{createAgentRuntime as CR}from"@cline/agents";import{createContributionRegistry as ER}from"@cline/shared";import{createGateway as tF,createHandlerAsync as sF,hasRegisteredHandler as oF,MODEL_COLLECTIONS_BY_PROVIDER_ID as eF,normalizeProviderId as $R}from"@cline/llms";import{EMPTY_CONTENT_TEXT as uF}from"@cline/shared";function cF($){let f=lF($.content),J=[],W=$.id??iF(),Z=0,Q=[],j=()=>{if(Q.length===0)return;let H=Z===0?W:`${W}_part_${Z}`;Z+=1,J.push({id:H,role:$.role,content:Q.map(pF),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:tj($.metrics)}),Q=[]};if(f.length===0)return J.push({id:W,role:$.role,content:[{type:"text",text:uF}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:tj($.metrics)}),J;for(let H of f){if(H.type!=="tool_result"){Q.push(H);continue}j(),J.push({id:`${W}_tool_${H.tool_use_id}`,role:"tool",content:[oj(H)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function f6($){return $.flatMap(cF)}function dF($){let f=$.content.map(ej).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:rF($.metrics)}}function df($){return $.map(dF)}function J6($){let f=[];for(let J of $){let W=J.content.map(ej).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,Q=f[f.length-1];if(Z==="user"&&W.length>0&&W.every((j)=>j.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((j)=>j.type==="tool_result")){Q.content.push(...W);continue}f.push({role:Z,content:W})}return f}function lF($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function pF($){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 oj($)}}function oj($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function ej($){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 tj($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function rF($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var sj=0;function iF(){return sj+=1,`msg_${Date.now().toString(36)}_${sj.toString(36)}`}function nF($){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:aF($),error:$.error}];default:return[]}}function aF($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function $H($){return{async*stream(f){let J=!1,W=!1;try{let Z=typeof $==="function"?await $():$;Z.setAbortSignal?.(f.signal);let Q=J6(f.messages),j=f.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema}));for await(let H of Z.createMessage(f.systemPrompt??"",Q,j))for(let X of nF(H)){if(X.type==="finish")J=!0;else if(X.type==="tool-call-delta")W=!0;yield X}if(!J)yield{type:"finish",reason:W?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:f.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function fR($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function JR($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if($.providerId==="bedrock")Object.assign(f,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return fR(f)}function FZ($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return eF[$.providerId]?.models??void 0}function WR($){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 ZR($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:WR(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function fH($,f,J){let W=$.providerConfig,Z=W?.providerId===$.providerId?W:void 0,Q={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:FZ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};if(oF($R(Q.providerId)))return $H(()=>sF(Q));return tF({providerConfigs:[{providerId:Q.providerId,apiKey:Q.apiKey,baseUrl:Q.baseUrl,headers:Q.headers,options:JR(Q),models:Q.knownModels?Object.entries(Q.knownModels).map(([j,H])=>ZR(j,H)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:Q.providerId,modelId:Q.modelId},{maxTokens:Q.maxOutputTokens})}import{normalizeUserInput as JH}from"@cline/shared";var QR=50000,jR=6000000,WH=8000,HR=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),XR=new Set(["read","read_files"]),v1="[outdated - see the latest file content]",ZH="Tool execution was interrupted before a result was produced.",AR=($)=>`
436
+ `).trim()}function s8(f={}){let{timeoutMs:$=30000,maxResponseBytes:J=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:W=!0}=f;return async(j,H,X)=>{let A;try{A=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(A.protocol))throw Error(`Invalid protocol: ${A.protocol}. Only http and https are supported.`);let Y=new AbortController,V=setTimeout(()=>Y.abort(),$),B;if(X.signal)B=()=>Y.abort(),X.signal.addEventListener("abort",B);try{let K=await fetch(j,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:W?"follow":"manual",signal:Y.signal});if(clearTimeout(V),!W&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let P=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let G=[],F=0;while(!0){let{done:y,value:b}=await R.read();if(y)break;if(F+=b.length,F>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);G.push(b)}let U=new Uint8Array(F),_=0;for(let y of G)U.set(y,_),_+=y.length;let M=new TextDecoder("utf-8").decode(U),L;if(P.includes("text/html")||P.includes("application/xhtml"))L=nR(M);else if(P.includes("application/json"))try{let y=JSON.parse(M);L=JSON.stringify(y,null,2)}catch{L=M}else L=M;let D=[`URL: ${j}`,`Content-Type: ${P}`,`Size: ${F} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)D.push(`
437
+ [Content truncated: showing first 50000 of ${L.length} characters]`);return D.push("","--- Analysis Request ---",`Prompt: ${H}`),D.join(`
438
+ `)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${$}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(X.signal&&B)X.signal.removeEventListener("abort",B)}}}function f2(f={}){return{readFile:a8(f.fileRead),search:t8(f.search),bash:r8(f.bash),webFetch:s8(f.webFetch),applyPatch:p8(f.applyPatch),editor:i8(f.editor)}}var aR={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"},$2=[{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 uH(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((Q)=>J.includes(Q.toLowerCase()))}function tR(f,$,J,Q){if(f.mode&&f.mode!=="any"&&f.mode!==Q)return!1;return uH($,f.providerIdIncludes)&&uH(J,f.modelIdIncludes)}function J2(f,$,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!tR(j,f,$,J))continue;for(let H of j.disableTools??[])Z.set(H,!1);for(let H of j.enableTools??[])Z.set(H,!0)}let W={};for(let[j,H]of Z.entries())W[aR[j]]=H;return W}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 mf(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function T6(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let Q of sf)J[Q]=$;return J}function z6(f,$){let J=c0[f],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return Y$({...W,...$})}import{createTool as oD,zodToJsonSchema as eD}from"@cline/shared";import{z as QZ}from"zod";import{createAgentRuntime as dD}from"@cline/agents";import{createContributionRegistry as lD}from"@cline/shared";import{createGateway as jD,createHandlerAsync as HD,hasRegisteredHandler as XD,MODEL_COLLECTIONS_BY_PROVIDER_ID as AD,normalizeProviderId as YD}from"@cline/llms";import{EMPTY_CONTENT_TEXT as sR}from"@cline/shared";function oR(f){let $=fD(f.content),J=[],Q=f.id??QD(),Z=0,W=[],j=()=>{if(W.length===0)return;let H=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:H,role:f.role,content:W.map($D),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:dH(f.metrics)}),W=[]};if($.length===0)return J.push({id:Q,role:f.role,content:[{type:"text",text:sR}],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:dH(f.metrics)}),J;for(let H of $){if(H.type!=="tool_result"){W.push(H);continue}j(),J.push({id:`${Q}_tool_${H.tool_use_id}`,role:"tool",content:[pH(H)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return j(),J}function M6(f){return f.flatMap(oR)}function eR(f){let $=f.content.map(rH).filter((J)=>J!==void 0);return{id:f.id,role:f.role==="tool"?"user":f.role,content:$,ts:f.createdAt,metadata:f.metadata,modelInfo:f.modelInfo,metrics:JD(f.metrics)}}function Q2(f){return f.map(eR)}function N6(f){let $=[];for(let J of f){let Q=J.content.map(rH).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=$[$.length-1];if(Z==="user"&&Q.length>0&&Q.every((j)=>j.type==="tool_result")&&W?.role==="user"&&Array.isArray(W.content)&&W.content.every((j)=>j.type==="tool_result")){W.content.push(...Q);continue}$.push({role:Z,content:Q})}return $}function fD(f){if(typeof f==="string")return f.trim().length>0?[{type:"text",text:f}]:[];return[...f]}function $D(f){switch(f.type){case"text":return{type:"text",text:f.text};case"thinking":return{type:"reasoning",text:f.thinking,metadata:f.signature?{signature:f.signature,details:f.details}:f.details?{details:f.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:f.data}};case"image":return{type:"image",image:f.data,mediaType:f.mediaType};case"file":return{type:"file",path:f.path,content:f.content};case"tool_use":return{type:"tool-call",toolCallId:f.id,toolName:f.name,input:f.input,metadata:f.signature?{signature:f.signature}:void 0};case"tool_result":return pH(f)}}function pH(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:f.name,output:f.content,isError:f.is_error}}function rH(f){switch(f.type){case"text":return{type:"text",text:f.text};case"reasoning":{if(f.redacted===!0)return{type:"redacted_thinking",data:f.metadata?.data??""};let $=f.metadata;return{type:"thinking",thinking:f.text,signature:$?.signature,details:$?.details}}case"image":return typeof f.image==="string"?{type:"image",data:f.image,mediaType:f.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:f.path,content:f.content};case"tool-call":{let $=f.metadata;return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:$?.thoughtSignature??$?.signature}}case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,name:f.toolName,content:J,is_error:f.isError}}}}function dH(f){if(!f)return;return{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,cacheReadTokens:f.cacheReadTokens??0,cacheWriteTokens:f.cacheWriteTokens??0,cost:f.cost}}function JD(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var lH=0;function QD(){return lH+=1,`msg_${Date.now().toString(36)}_${lH.toString(36)}`}function ZD(f){switch(f.type){case"text":return[{type:"text-delta",text:f.text}];case"reasoning":return[{type:"reasoning-delta",text:f.reasoning,metadata:f.signature?{thoughtSignature:f.signature,details:f.details}:{details:f.details}}];case"tool_calls":{let $=f.tool_call.function,J=$.arguments;return[{type:"tool-call-delta",toolCallId:f.tool_call.call_id??$.id,toolName:$.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...f.signature?{metadata:{thoughtSignature:f.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost}}];case"done":return[{type:"finish",reason:WD(f),error:f.error}];default:return[]}}function WD(f){if(f.success===!1)return"error";if(f.incompleteReason==="max_output_tokens"||f.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function iH(f){return{async*stream($){let J=!1,Q=!1;try{let Z=typeof f==="function"?await f():f;Z.setAbortSignal?.($.signal);let W=N6($.messages),j=$.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema}));for await(let H of Z.createMessage($.systemPrompt??"",W,j))for(let X of ZD(H)){if(X.type==="finish")J=!0;else if(X.type==="tool-call-delta")Q=!0;yield X}if(!J)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:$.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function VD(f){let $=Object.fromEntries(Object.entries(f).filter(([,J])=>J!==void 0));return Object.keys($).length>0?$:void 0}function BD(f){return f.providerId==="openai-compatible"||f.clientType==="openai-compatible"}function KD(f){let $={region:f.region,apiLine:f.apiLine,openRouterProviderSorting:f.openRouterProviderSorting,modelCatalog:f.modelCatalog};if(BD(f))Object.assign($,{apiVersion:f.azure?.apiVersion,useIdentity:f.azure?.useIdentity});if(f.providerId==="bedrock")Object.assign($,{authentication:f.aws?.authentication,profile:f.aws?.profile,accessKeyId:f.aws?.accessKey,secretAccessKey:f.aws?.secretKey,sessionToken:f.aws?.sessionToken,usePromptCache:f.aws?.usePromptCache,useCrossRegionInference:f.useCrossRegionInference,useGlobalInference:f.useGlobalInference,endpoint:f.aws?.endpoint,customModelBaseId:f.aws?.customModelBaseId});if(f.providerId==="vertex"){let J=f.gcp?.region??f.region;Object.assign($,{project:f.gcp?.projectId,projectId:f.gcp?.projectId,location:J,region:J})}return VD($)}function nQ(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return AD[f.providerId]?.models??void 0}function PD(f){if(!f?.length)return;let $=new Set;for(let J of f)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":$.add(J);break;case"structured_output":$.add("structured-output");break;default:$.add("text")}return $.add("text"),[...$]}function GD(f,$){return{id:f,name:$.name??f,description:$.description,contextWindow:$.contextWindow,maxInputTokens:$.maxInputTokens,maxOutputTokens:$.maxTokens,capabilities:PD($.capabilities),metadata:{family:$.family,pricing:$.pricing,status:$.status,releaseDate:$.releaseDate}}}function nH(f,$,J){let Q=f.providerConfig,Z=Q?.providerId===f.providerId?Q:void 0,W={...Z??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??Z?.apiKey,baseUrl:f.baseUrl??Z?.baseUrl,headers:f.headers??Z?.headers,knownModels:nQ(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};if(XD(YD(W.providerId)))return iH(()=>HD(W));return jD({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,options:KD(W),models:W.knownModels?Object.entries(W.knownModels).map(([j,H])=>GD(j,H)):void 0}],logger:$,telemetry:J??f.telemetry??f.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as aH}from"@cline/shared";var FD=50000,UD=6000000,tH=8000,RD=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),DD=new Set(["read","read_files"]),t$="[outdated - see the latest file content]",sH="Tool execution was interrupted before a result was produced.",LD=(f)=>`
398
439
 
399
- ...[truncated ${$} chars]...
440
+ ...[truncated ${f} chars]...
400
441
 
401
- `,YR=($)=>`
442
+ `,OD=(f)=>`
402
443
 
403
- ...[truncated ${$} chars to fit provider request budget]...
444
+ ...[truncated ${f} chars to fit provider request budget]...
404
445
 
405
- `;class DZ{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=QR,f=HR,J=jR){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let j=JH(W.content);if(j!==W.content)return{...W,content:j}}return W}let Z=!1,Q=W.content.map((j)=>{let H=this.transformBlock(j,W.role);if(H!==j)Z=!0;return H});return Z?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=JH($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),W=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let Q=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===$.content?$:{...$,content:W}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let W=$[J];if(!Array.isArray(W.content))continue;for(let Z=0;Z<W.content.length;Z++){let Q=W.content[Z];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${Z}`);else if(Q.type==="tool_use"){let j=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,j),this.isReadTool(j)){let H=this.extractLocatorsFromReadToolInput(Q.input);if(H.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,H)}}else if(Q.type==="tool_result"){let j=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(j)||Q.is_error===!0)continue;let H=this.getReadLocators(Q);for(let X of H)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),Q.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,Q.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],W=new Map,Z=!1,Q=()=>{if(W.size===0)return;j(this.createMissingToolResultMessage(W)),W.clear(),Z=!0},j=(H)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,H)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(H.content)]},Z=!0;return}J.push(H)};for(let H of $){if(this.isToolResultOnlyMessage(H)){if(j(this.appendMissingToolResults(H,W)),W.size>0)W.clear(),Z=!0;continue}if(Array.isArray(H.content)){let X=H.content.filter((Y)=>Y.type==="tool_result"),A=H.content.filter((Y)=>Y.type!=="tool_result");if(X.length>0){let Y=this.appendMissingToolResults({...H,role:"user",content:X},W);if(j(Y),W.size>0)W.clear();Z=!0}if(A.length>0||X.length===0){if(X.length===0)Q();let Y=X.length>0?{...H,content:A}:H;if(j(Y),Y.role==="assistant")this.trackMissingToolCalls(Y,f,W)}continue}Q(),j(H)}return Q(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")f.add(W.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let W of $.content){if(W.type!=="tool_use"||f.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${ZH} Tool: ${$}.`:ZH}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],W=this.extractLocatorFromReadRequest(f);if(W)J.push(W);if(Array.isArray(f.files))for(let Z of f.files){let Q=this.extractLocatorFromReadRequest(Z);if(Q)J.push(Q)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let W of $){let Z=this.extractLocatorFromResultEntry(W);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((Q)=>this.toReadLocatorKey(Q))),W=new Set(f.map((Q)=>Q.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??v1;let Z=0;for(let Q of $)if(Q.type==="text")Z+=this.countOutdatedImageEntries(Q.text,J);return $.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:v1}}if(Q.type==="image"){if(Z===0)return Q;return Z-=1,{type:"text",text:v1}}if(Q.type!=="text")return Q;let j=this.replaceOutdatedInString(Q.text,J);if(j===null)return{...Q,text:v1};return j===Q.text?Q:{...Q,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let W=Array.isArray(J)?J:[J],Z=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let j=Q,H=this.extractLocatorFromResultEntry(j);if(!H)continue;if(!f.has(this.toReadLocatorKey(H)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let W=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(W)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let W={...$};if(typeof W.result==="string")W.result=v1;else if(typeof W.content==="string")W.content=v1;else W.result=v1;return W}isReadTool($){return!!$&&XR.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let W=this.truncateMiddle(f.content);return W===f.content?f:{...f,content:W}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return RZ($,this.maxToolResultChars,AR)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((Q)=>BR(Q))}}),W=this.collectTruncationCandidates(J);for(let Z of W){if(f<=this.maxTotalTextBytes)break;let Q=Z.byteLength;if(Q<=WH)continue;let j=f-this.maxTotalTextBytes,H=Math.max(WH,Q-j),X=VR(Z.get(),H,YR);Z.set(X),f-=Q-M0(X)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=M0(J.content);continue}for(let W of J.content)if(W.type==="text")f+=M0(W.text);else if(W.type==="thinking")f+=M0(W.thinking);else if(W.type==="file")f+=M0(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")f+=M0(W.content);else for(let Z of W.content)if(Z.type==="text")f+=M0(Z.text);else if(Z.type==="file")f+=M0(Z.content)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content){if(W.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof W.content==="string"){f.push({byteLength:M0(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")f.push({byteLength:M0(Q.text),get:()=>Q.text,set:(j)=>{Q.text=j}});else if(Q.type==="file")f.push({byteLength:M0(Q.content),get:()=>Q.content,set:(j)=>{Q.content=j}})}}return f.sort((J,W)=>W.byteLength-J.byteLength)}}function M0($){return Buffer.byteLength($,"utf8")}function RZ($,f,J){if($.length<=f)return $;let W=J($.length-f),Z=Math.max(0,Math.floor((f-W.length)/2)),Q=Math.max(0,$.length-Z*2),j=J(Q),H=Math.max(0,Math.floor((f-j.length)/2)),X=$.slice(0,H),A=H>0?$.slice(-H):"";return`${X}${j}${A}`}function VR($,f,J){if(M0($)<=f)return $;let W=0,Z=$.length,Q=RZ($,0,J);while(W<=Z){let j=W+Z>>>1,H=RZ($,j,J);if(M0(H)<=f)Q=H,W=j+1;else Z=j-1}return Q}function BR($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function LZ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class OZ{messages=[];conversationId=LZ();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=LZ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=LZ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function QH($){let{agentConfig:f}=$,J=KR(f),W=GR(f),Z=$.hooks,Q=PR(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:W,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:Q,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function KR($){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 GR($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function PR($){if($===void 0)return;return $>=2?"parallel":"sequential"}function UR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function FR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function zZ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(zZ);let f={};for(let J of Object.keys($).sort())f[J]=zZ($[J]);return f}function RR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(zZ($))}catch{return String($)}}function DR($,f,J,W){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===W.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=W.hardThreshold}}var jH={softThreshold:3,hardThreshold:5};class _Z{config;state=UR();constructor($){this.config={softThreshold:$?.softThreshold??jH.softThreshold,hardThreshold:$?.hardThreshold??jH.hardThreshold}}inspect($){let f=RR($.input),J=DR(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(){FR(this.state)}}class TZ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let W=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(W),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await OR({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let Q=Z.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:LR({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function LR($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let W=$.stopReason?.trim();if(W)f.push(`Decision: ${W}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function OR($,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 zR($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function _R($){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 TR($){return $.content.find((f)=>f.type==="tool-result")}function NR($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function MR($){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 NZ{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=zR($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let W=_R($);if(W!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let W=TR($.message),Z=W?.output,Q=MR(W);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:Q,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,W=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,H=($.totalCost??0)-Q;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:H===0?void 0:H,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:NR($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function bR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function kR($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function IR($,f){let J=$.trim(),W=f.map((Z)=>Z.trim()).filter(Boolean).join(`
446
+ `;class tQ{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=FD,$=RD,J=UD){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((Q)=>{if(!Array.isArray(Q.content)){if(Q.role==="user"&&typeof Q.content==="string"){let j=aH(Q.content);if(j!==Q.content)return{...Q,content:j}}return Q}let Z=!1,W=Q.content.map((j)=>{let H=this.transformBlock(j,Q.role);if(H!==j)Z=!0;return H});return Z?{...Q,content:W}:Q});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let Z=aH(f.text);if(Z!==f.text)return{...f,text:Z};return f}if(f.type==="file"){let Z=this.truncateMiddle(f.content);return Z===f.content?f:{...f,content:Z}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),Q=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let Z=this.getReadLocators(f);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,f.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===f.content?f:{...f,content:Q}}reindex(f){let $=this.indexedMessageCount===0||f.length>=this.indexedMessageCount&&f[this.indexedMessageCount-1]===this.indexedTailRef;if(f.length<this.indexedMessageCount||!$)this.resetIndexes();for(let J=this.indexedMessageCount;J<f.length;J++){let Q=f[J];if(!Array.isArray(Q.content))continue;for(let Z=0;Z<Q.content.length;Z++){let W=Q.content[Z];if(W.type==="file")this.latestFullContentOwnerByPathCache.set(W.path,`file:${J}:${Z}`);else if(W.type==="tool_use"){let j=W.name.toLowerCase();if(this.toolNameByIdCache.set(W.id,j),this.isReadTool(j)){let H=this.extractLocatorsFromReadToolInput(W.input);if(H.length>0)this.readLocatorsByToolUseIdCache.set(W.id,H)}}else if(W.type==="tool_result"){let j=this.toolNameByIdCache.get(W.tool_use_id);if(!this.isReadTool(j)||W.is_error===!0)continue;let H=this.getReadLocators(W);for(let X of H)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),W.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,W.tool_use_id)}}}this.indexedMessageCount=f.length,this.indexedTailRef=f.length>0?f[f.length-1]:void 0}addMissingToolResults(f){let $=this.collectToolResultIds(f),J=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(H)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,H)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(H.content)]},Z=!0;return}J.push(H)};for(let H of f){if(this.isToolResultOnlyMessage(H)){if(j(this.appendMissingToolResults(H,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(H.content)){let X=H.content.filter((Y)=>Y.type==="tool_result"),A=H.content.filter((Y)=>Y.type!=="tool_result");if(X.length>0){let Y=this.appendMissingToolResults({...H,role:"user",content:X},Q);if(j(Y),Q.size>0)Q.clear();Z=!0}if(A.length>0||X.length===0){if(X.length===0)W();let Y=X.length>0?{...H,content:A}:H;if(j(Y),Y.role==="assistant")this.trackMissingToolCalls(Y,$,Q)}continue}W(),j(H)}return W(),Z?J:f}appendMissingToolResults(f,$){if($.size===0||!Array.isArray(f.content))return f;return{...f,role:"user",content:[...f.content,...this.createMissingToolResultBlocks($)]}}shouldMergeUserAfterToolResults(f,$){return f?.role==="user"&&$.role==="user"&&this.isToolResultOnlyMessage(f)&&this.contentBlocksForUserMerge($.content).length>0}contentBlocksForUserMerge(f){return typeof f==="string"?f.length>0?[{type:"text",text:f}]:[]:f}collectToolResultIds(f){let $=new Set;for(let J of f){if(!Array.isArray(J.content))continue;for(let Q of J.content)if(Q.type==="tool_result")$.add(Q.tool_use_id)}return $}isToolResultOnlyMessage(f){return f.role==="user"&&Array.isArray(f.content)&&f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}trackMissingToolCalls(f,$,J){if(!Array.isArray(f.content))return;for(let Q of f.content){if(Q.type!=="tool_use"||$.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${sH} Tool: ${f}.`:sH}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(f){let $=f,J=this.readResultLocatorCache.get($);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent(f.content),this.readResultLocatorCache.set($,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get(f.tool_use_id)??[]}extractLocatorsFromReadToolInput(f){if(!f||typeof f!=="object")return[];let $=f,J=[],Q=this.extractLocatorFromReadRequest($);if(Q)J.push(Q);if(Array.isArray($.files))for(let Z of $.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray($.file_paths)){for(let Z of $.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent(f){if(typeof f==="string")return this.tryParseReadLocators(f);for(let $ of f){if($.type!=="text")continue;let J=this.tryParseReadLocators($.text);if(J.length>0)return J}return[]}tryParseReadLocators(f){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(f))}catch{return[]}}extractLocatorsFromParsedReadResult(f){if(Array.isArray(f)){let J=[];for(let Q of f){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let $=this.extractLocatorFromResultEntry(f);return $?[$]:[]}extractLocatorFromReadRequest(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(!J)return;return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)}}extractLocatorFromResultEntry(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(J)return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)};if(typeof $.query==="string"&&$.query.length>0)return this.parseReadQuery($.query);return}extractPath(f){let $=[f.path,f.file_path,f.filePath];for(let J of $)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber(f){return typeof f==="number"&&Number.isInteger(f)?f:null}parseReadQuery(f){let $=/^(.*):(\d+)-(EOF|\d+)$/.exec(f);if(!$)return{path:f,startLine:null,endLine:null};return{path:$[1],startLine:Number($[2]),endLine:$[3]==="EOF"?null:Number($[3])}}dedupeReadLocators(f){let $=new Map;for(let J of f)$.set(this.toReadLocatorKey(J),J);return Array.from($.values())}toReadLocatorKey(f){if(this.isFullFileRead(f))return f.path;return`${f.path}:${f.startLine??1}-${f.endLine??"EOF"}`}isFullFileRead(f){return f.startLine==null&&f.endLine==null}isOutdatedReadLocator(f,$){let J=this.latestFullContentOwnerByPathCache.get(f.path);if(J&&J!==$)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(f))!==$}replaceOutdatedReadContent(f,$){let J=new Set($.map((W)=>this.toReadLocatorKey(W))),Q=new Set($.map((W)=>W.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??t$;let Z=0;for(let W of f)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return f.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:t$}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:t$}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:t$};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}catch{return 0}let Q=Array.isArray(J)?J:[J],Z=0;for(let W of Q){if(!W||typeof W!=="object")continue;let j=W,H=this.extractLocatorFromResultEntry(j);if(!H)continue;if(!$.has(this.toReadLocatorKey(H)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(Q)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let Q={...f};if(typeof Q.result==="string")Q.result=t$;else if(typeof Q.content==="string")Q.content=t$;else Q.result=t$;return Q}isReadTool(f){return!!f&&DD.has(f)}shouldTruncateTool(f){return!!f&&this.targetToolNames.has(f)}truncateToolResultContent(f){if(typeof f==="string")return this.truncateMiddle(f);return f.map(($)=>{if($.type==="file"){let Q=this.truncateMiddle($.content);return Q===$.content?$:{...$,content:Q}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return aQ(f,this.maxToolResultChars,LD)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>TD(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if($<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=tH)continue;let j=$-this.maxTotalTextBytes,H=Math.max(tH,W-j),X=_D(Z.get(),H,OD);Z.set(X),$-=W-w0(X)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=w0(J.content);continue}for(let Q of J.content)if(Q.type==="text")$+=w0(Q.text);else if(Q.type==="thinking")$+=w0(Q.thinking);else if(Q.type==="file")$+=w0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")$+=w0(Q.content);else for(let Z of Q.content)if(Z.type==="text")$+=w0(Z.text);else if(Z.type==="file")$+=w0(Z.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){if(!Array.isArray(J.content))continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof Q.content==="string"){$.push({byteLength:w0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")$.push({byteLength:w0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")$.push({byteLength:w0(W.content),get:()=>W.content,set:(j)=>{W.content=j}})}}return $.sort((J,Q)=>Q.byteLength-J.byteLength)}}function w0(f){return Buffer.byteLength(f,"utf8")}function aQ(f,$,J){if(f.length<=$)return f;let Q=J(f.length-$),Z=Math.max(0,Math.floor(($-Q.length)/2)),W=Math.max(0,f.length-Z*2),j=J(W),H=Math.max(0,Math.floor(($-j.length)/2)),X=f.slice(0,H),A=H>0?f.slice(-H):"";return`${X}${j}${A}`}function _D(f,$,J){if(w0(f)<=$)return f;let Q=0,Z=f.length,W=aQ(f,0,J);while(Q<=Z){let j=Q+Z>>>1,H=aQ(f,j,J);if(w0(H)<=$)W=H,Q=j+1;else Z=j-1}return W}function TD(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function sQ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class oQ{messages=[];conversationId=sQ();sessionStarted=!1;constructor(f){if((f?.length??0)>0)this.restore(f??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(f){this.messages.push(f)}appendMessages(f){if(f.length===0)return;this.messages.push(...f)}replaceMessages(f){this.messages=[...f]}resetForRun(){this.messages=[],this.conversationId=sQ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=sQ(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function oH(f){let{agentConfig:$}=f,J=zD($),Q=MD($),Z=f.hooks,W=ND($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:Q,model:f.model,modelOptions:J,tools:f.tools,hooks:Z,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??$.telemetry,initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:W,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function zD(f){let $={};if(f.thinking!==void 0)$.thinking=f.thinking;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;if(f.maxTokensPerTurn!==void 0)$.maxTokensPerTurn=f.maxTokensPerTurn;if(f.apiTimeoutMs!==void 0)$.apiTimeoutMs=f.apiTimeoutMs;return Object.keys($).length>0?$:void 0}function MD(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function ND(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function qD(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function yD(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function eQ(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(eQ);let $={};for(let J of Object.keys(f).sort())$[J]=eQ(f[J]);return $}function wD(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(eQ(f))}catch{return String(f)}}function CD(f,$,J,Q){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=Q.hardThreshold}}var eH={softThreshold:3,hardThreshold:5};class fZ{config;state=qD();constructor(f){this.config={softThreshold:f?.softThreshold??eH.softThreshold,hardThreshold:f?.hardThreshold??eH.hardThreshold}}inspect(f){let $=wD(f.input),J=CD(this.state,f.name,$,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){yD(this.state)}}class $Z{consecutiveMistakes=0;options;constructor(f){this.options=f}async record(f){let $=this.options.maxConsecutiveMistakes,J=f.forceAtLimit&&$?$:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let Q=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:f.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:f.iteration,reason:f.reason,details:f.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!$||J<$)return{action:"continue"};let Z=await ED({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:SD({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function SD(f){let $=[`Stopped after ${f.consecutiveMistakes}/${f.maxConsecutiveMistakes} consecutive mistakes (${f.reason}) at iteration ${f.iteration}.`],J=f.details?.trim();if(J)$.push(`Error: ${J}`);let Q=f.stopReason?.trim();if(Q)$.push(`Decision: ${Q}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function ED(f,$){if(!$)return{action:"stop",reason:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`};try{return await $(f)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`}}}function hD(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function bD(f){let $=f.content.filter((J)=>J.type==="reasoning");if($.length===0)return;return{reasoning:$.map((J)=>J.text).join(""),redacted:$.some((J)=>J.redacted===!0)}}function kD(f){return f.content.find(($)=>$.type==="tool-result")}function ID(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function xD(f){if(!f||f.isError!==!0)return;if(typeof f.output==="string")return f.output;if(f.output instanceof Error)return f.output.message;try{return JSON.stringify(f.output)}catch{return String(f.output)}}class JZ{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate(f){switch(f.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:f.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:f.iteration,hadToolCalls:f.toolCallCount>0,toolCallCount:f.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:f.text,accumulated:f.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:f.text,redacted:f.redacted===!0}];case"assistant-message":return this.translateAssistantMessage(f.message);case"tool-started":return this.translateToolStarted(f);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,update:f.update}];case"tool-finished":return this.translateToolFinished(f);case"usage-updated":return this.translateUsage(f.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:f.message,reason:f.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:f.metadata}];case"run-finished":return this.translateRunFinished(f.result);case"run-failed":return[{type:"error",error:f.error,recoverable:!1,iteration:f.snapshot.iteration}];default:return f}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage(f){let $=[],J=hD(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let Q=bD(f);if(Q!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return $}translateToolStarted(f){return this.toolStartedAt.set(f.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,input:f.toolCall.input}]}translateToolFinished(f){let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=$===void 0?void 0:Date.now()-$;this.toolStartedAt.delete(f.toolCall.toolCallId);let Q=kD(f.message),Z=Q?.output,W=xD(Q);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,Q=f.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,H=(f.totalCost??0)-W;return this.lastUsage={inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost},[{type:"usage",inputTokens:Math.max(0,$),outputTokens:Math.max(0,J),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:H===0?void 0:H,totalInputTokens:f.inputTokens,totalOutputTokens:f.outputTokens,totalCacheReadTokens:f.cacheReadTokens===0?void 0:f.cacheReadTokens,totalCacheWriteTokens:f.cacheWriteTokens===0?void 0:f.cacheWriteTokens,totalCost:f.totalCost}]}translateRunFinished(f){let $={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens===0?void 0:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens===0?void 0:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost};return[{type:"done",reason:ID(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function pD(f){if(typeof f==="string")return f;if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}}async function rD(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function iD(f,$){let J=f.trim(),Q=$.map((Z)=>Z.trim()).filter(Boolean).join(`
406
447
 
407
- `);if(J&&W)return`${J}
448
+ `);if(J&&Q)return`${J}
408
449
 
409
- ${W}`;return J||W}function xR($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let W of f){let Z=await W.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let W of f)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,Z;for(let Q of f){let j=await Q.beforeModel?.({...J,request:W});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},W={...W,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...W.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let W of f){let Z=await W.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let W=J.input,Z;for(let Q of f){let j=await Q.beforeTool?.({...J,input:W});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))W=j.input}return Z},afterTool:async(J)=>{let W=J.result,Z;for(let Q of f){let j=await Q.afterTool?.({...J,result:W});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)W=j.result}return Z},onEvent:async(J)=>{for(let W of f)await W.onEvent?.(J)}}}class Z1{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 NZ;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??CR,this.conversation=new OZ($.initialMessages),this.messageBuilder=new DZ,this.contributionRegistry=ER({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 TZ({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,j,H)=>mR(this.logger,Q,j,H),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=$.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let Z=W===!1||W===void 0?void 0:W;this.loopTracker=new _Z(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of $)if(!f.has(W.name))J.push(W),f.add(W.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await kR(f);if(J)$.push(J)}return IR(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let U=await vR(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:U})}let W=await this.composeSystemPrompt(),Z=fH(this.config,this.logger,this.telemetry),Q=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let U of Q)j.set(U.name,U);for(let U of this.config.tools)j.set(U.name,U);let H=this.conversation.getConversationId(),X=XH(this.config),A=Array.from(j.values()),Y=f6(this.conversation.getMessages()),V=QH({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:H,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:A,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[_j]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,A),initialMessages:Y,systemPrompt:W}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((U)=>{this.handleRuntimeEvent(U)}),G,R;try{if($.isContinue)G=await B.continue(void 0);else G=await B.run("")}catch(U){R=U instanceof Error?U:Error(String(U))}finally{K();try{await this.activeTrackerWork}catch(U){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:U})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(G&&G.messages.length>0){let U=df(G.messages);this.conversation.replaceMessages(U)}let P=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:P})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=xR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let W=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(W);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let Z=df(W.messages),Q=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:Z,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:W.emitStatusNotice});if(!j)return;return{...j.messages?{messages:f6(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(J6($));return f6(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)f=await W.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,W=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((X)=>X.type==="tool-result"),Q=Z?.type==="tool-result"&&Z.isError===!0,j=Q?bR(Z?.type==="tool-result"?Z.output:void 0):void 0,H={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:W,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(H),Q){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(df($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),W=df(f).filter((Z)=>!Z.id||!J.has(Z.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:$,input:f});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:W.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:W,endedAt:Z}=$,Q=Z.getTime()-W.getTime(),j=J?"error":gR(f),H=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",X=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,A=f?df(f.messages):this.conversation.getMessages(),Y=XH(this.config);if(J)throw J;return{text:H,usage:X,messages:A,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:Y},startedAt:W,endedAt:Z,durationMs:Q}}}function mR($,f,J,W){if(!$)return;if(f==="debug"){$.debug(J,W);return}if(f==="error"&&$.error){$.error(J,W);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...W,severity:Z})}function gR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function vR($,f,J,W){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => HH);return Z($,f,J,W)}function XH($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=FZ($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as AH}from"@cline/shared";function YH($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return AH({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
410
- ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function VH($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return AH({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function lf($){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 u1($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?YH($.prompt,f):VH($.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 pf($){let f=u1($),J=new Z1(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var dR=MZ.object({systemPrompt:MZ.string().describe("System prompt defining the sub-agent's behavior"),task:MZ.string().describe("Task for the sub-agent to complete")});function Q1($){return uR({name:"spawn_agent",description:"Spawn a sub-agent with a custom system prompt for specialized tasks. Use when delegating work that benefits from focused expertise.",inputSchema:cR(dR),execute:async(f,J)=>{let W=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=pf({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:W,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),Q=Z.getAgentId(),j=Z.getConversationId(),H=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:Q,conversationId:j,parentAgentId:H,input:f})}catch{}try{let X=await Z.run(f.task),A={text:X.text,iterations:X.iterations,finishReason:X.finishReason,usage:{inputTokens:X.usage.inputTokens,outputTokens:X.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:H,input:f,result:A,agentResult:X})}catch{}return A}catch(X){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:H,input:f,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as Q0,TEAM_AWAIT_TIMEOUT_MS as lR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as pR,TEAM_RUN_TEXT_PREVIEW_LIMIT as rR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as iR,TeamAttachOutcomeFragmentInputSchema as BH,TeamAwaitRunsInputSchema as KH,TeamBroadcastInputSchema as GH,TeamBroadcastToolResultSchema as nR,TeamCancelRunInputSchema as PH,TeamCancelRunToolResultSchema as aR,TeamCleanupInputSchema as UH,TeamCleanupToolResultSchema as tR,TeamCreateOutcomeInputSchema as FH,TeamCreateOutcomeToolResultSchema as sR,TeamFinalizeOutcomeInputSchema as RH,TeamFinalizeOutcomeToolResultSchema as oR,TeamListOutcomesInputSchema as DH,TeamListRunsInputSchema as LH,TeamMailboxMessageToolResultSchema as eR,TeamMissionLogInputSchema as OH,TeamMissionLogToolResultSchema as $D,TeamOutcomeFragmentToolResultSchema as zH,TeamOutcomeToolResultSchema as fD,TeamReadMailboxInputSchema as _H,TeamReviewOutcomeFragmentInputSchema as TH,TeamRunTaskInputSchema as NH,TeamRunTaskToolResultSchema as yZ,TeamRunToolSummarySchema as qZ,TeamSendMessageInputSchema as MH,TeamSendMessageToolResultSchema as JD,TeamShutdownTeammateInputSchema as yH,TeamSimpleAgentStatusToolResultSchema as qH,TeamSpawnTeammateInputSchema as wH,TeamStatusInputSchema as SH,TeamStatusToolResultSchema as WD,TeamTaskInputSchema as hH,TeamTaskToolResultSchema as x8,validateWithZod as E,zodToJsonSchema as j0}from"@cline/shared";function CH($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function c1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function ZD($){let f=$.result;if(!f)return;return{textPreview:CH(f.text,rR),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 W6($){return $?.toISOString()}function wZ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:CH($.message,pR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:W6($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:W6($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:W6($.heartbeatAt),lastProgressAt:W6($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:ZD($)}}function QD($){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 rf=["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 EH($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...d1({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:u1({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function nf($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,W=d1({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let Q of $.restoredTeammates??[]){if($.runtime.isTeammateActive(Q.agentId))continue;EH({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Q}),Z.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:Z}}function d1($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,W=$.includeManagementTools??!0,Z=[];if(J)Z.push(Q0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(wH),execute:async(j)=>{let H=E(wH,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let X={agentId:H.agentId,rolePrompt:H.rolePrompt};if(EH({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:X}),!W)$.onLeadToolsUnlocked?.(d1({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return E(qH,{agentId:H.agentId,status:"spawned"})}}));if(!W)return Z;Z.push(Q0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(yH),execute:async(j)=>{let H=E(yH,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(H.agentId,H.reason),E(qH,{agentId:H.agentId,status:"stopped"})}})),Z.push(Q0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(SH),execute:async(j)=>{return E(SH,j),E(WD,$.runtime.getSnapshot())}})),Z.push(Q0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:j0(hH),execute:async(j)=>{let H=E(hH,j);switch(H.action){case"create":{let X=new Set(iR.create??[]),A=Object.entries(j).filter(([V,B])=>X.has(V)&&B!=null).map(([V])=>V),Y=$.runtime.createTask({title:c1(H.title,"title"),description:c1(H.description,"description"),dependsOn:H.dependsOn,assignee:H.assignee,createdBy:$.requesterId});return E(x8,{action:"create",taskId:Y.id,status:Y.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return E(x8,{action:"list",tasks:$.runtime.listTaskItems({status:H.status,assignee:H.assignee})});case"claim":{let X=$.runtime.claimTask(c1(H.taskId,"taskId"),$.requesterId);return E(x8,{action:"claim",taskId:X.id,status:X.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let X=$.runtime.completeTask(c1(H.taskId,"taskId"),$.requesterId,c1(H.summary,"summary"));return E(x8,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=$.runtime.blockTask(c1(H.taskId,"taskId"),$.requesterId,c1(H.reason,"reason"));return E(x8,{action:"block",taskId:X.id,status:X.status})}}}}));let Q=new Map;return Z.push(Q0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(NH),execute:async(j)=>{let H=E(NH,j);if(H.runMode==="async"){let Y=$.runtime.startTeammateRun(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:$.requesterId,continueConversation:H.continueConversation||void 0});return E(yZ,{agentId:H.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${H.agentId} and queued as ${Y.id}.`,runId:Y.id})}let X=Q.get(H.agentId);if(X){let Y=await X;return E(yZ,{...Y,status:"joined",deduped:!0,message:`Task for ${H.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=$.runtime.routeToTeammate(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:$.requesterId,continueConversation:H.continueConversation||void 0}).then((Y)=>E(yZ,{agentId:H.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${H.agentId} and completed in sync mode.`,text:Y.text,iterations:Y.iterations})).finally(()=>{Q.delete(H.agentId)});return Q.set(H.agentId,A),await A}})),Z.push(Q0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(PH),execute:async(j)=>{let H=E(PH,j),X=$.runtime.cancelRun(H.runId,H.reason);return E(aR,{runId:X.id,status:X.status})}})),Z.push(Q0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(LH),execute:async(j)=>E(qZ.array(),$.runtime.listRuns(E(LH,j)).map(wZ))})),Z.push(Q0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:j0(KH),timeoutMs:lR,execute:async(j)=>{let H=E(KH,j);if(H.runId){let Y=await $.runtime.awaitRun(H.runId);return QD(Y),E(qZ,wZ(Y))}let X=await $.runtime.awaitAllRuns(),A=X.filter((Y)=>["failed","cancelled","interrupted"].includes(Y.status));if(A.length>0){let Y=A.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${Y}`)}return E(qZ.array(),X.map(wZ))}})),Z.push(Q0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(MH),execute:async(j)=>{let H=E(MH,j),X=$.runtime.sendMessage($.requesterId,H.toAgentId,H.subject,H.body,H.taskId??void 0);return E(JD,{id:X.id,toAgentId:X.toAgentId})}})),Z.push(Q0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(GH),execute:async(j)=>{let H=E(GH,j),X=$.runtime.broadcast($.requesterId,H.subject,H.body,{taskId:H.taskId??void 0});return E(nR,{delivered:X.length})}})),Z.push(Q0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(_H),execute:async(j)=>{let H=E(_H,j);return E(eR.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:H.unreadOnly,markRead:!0}))}})),Z.push(Q0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(OH),execute:async(j)=>{let H=E(OH,j),X=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:H.taskId||void 0,kind:H.kind,summary:H.summary,evidence:H.evidence?.length?H.evidence:void 0,nextAction:H.nextAction||void 0});return E($D,{id:X.id})}})),Z.push(Q0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(UH),execute:async(j)=>{if(E(UH,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),E(tR,{status:"cleaned"})}})),Z.push(Q0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(FH),execute:async(j)=>{let H=E(FH,j),X=$.runtime.createOutcome({title:H.title,requiredSections:H.requiredSections,createdBy:$.requesterId});return E(sR,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),Z.push(Q0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(BH),execute:async(j)=>{let H=E(BH,j),X=$.runtime.attachOutcomeFragment({outcomeId:H.outcomeId,section:H.section,sourceAgentId:$.requesterId,sourceRunId:H.sourceRunId||void 0,content:H.content});return E(zH,{fragmentId:X.id,status:X.status})}})),Z.push(Q0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(TH),execute:async(j)=>{let H=E(TH,j),X=$.runtime.reviewOutcomeFragment({fragmentId:H.fragmentId,reviewedBy:$.requesterId,approved:H.approved});return E(zH,{fragmentId:X.id,status:X.status})}})),Z.push(Q0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(RH),execute:async(j)=>{let H=E(RH,j),X=$.runtime.finalizeOutcome(H.outcomeId);return E(oR,{outcomeId:X.id,status:X.status})}})),Z.push(Q0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(DH),execute:async(j)=>{return E(DH,j),E(fD.array(),$.runtime.listOutcomes())}})),Z}function Z6($){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 bH($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var jD=[{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:Q1({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...rf]}],HD={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function XD($){return $==="plan"||$==="yolo"?$:"act"}function IH($){let f=XD($.mode),J=m0[b$({mode:f})],W=cf($.providerId??"",$.modelId??"",f,uf);return{mode:f,flags:{...J,...W,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function kH($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=IH(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=HD[$];return W?J[W]===!0:!1}function AD($,f){if($.id==="editor"){let{flags:J}=IH(f),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:kH($.id,f),headlessToolNames:[W?"apply_patch":"editor"]}}return{...$,defaultEnabled:kH($.id,f)}}function l1($={}){return jD.map((f)=>AD(f,$))}function Q6($={}){return l1($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function j6($){if(!$.enabled)return new Set;let f=l1($.availabilityContext),J=new Set(f.map((W)=>W.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of $.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function m8($,f={}){return l1(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function H6($,f={}){return m8($,f)}function p1($={}){let{executorOptions:f={},executors:J,...W}=$,Z={...vf(f),...J??{}};return J1({...W,executors:Z})}import{mkdirSync as PD,writeFileSync as UD}from"node:fs";import{dirname as FD}from"node:path";import{normalizeUserInput as RD}from"@cline/shared";import{nanoid as DD}from"nanoid";var mH={};w(mH,{sanitizeSessionToken:()=>r1,parseTeamTaskSubSessionId:()=>tf,parseSubSessionId:()=>v8,makeTeamTaskSubSessionId:()=>g8,makeSubSessionId:()=>af,deriveSubsessionStatus:()=>u8});import{nanoid as BD}from"nanoid";function r1($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function af($,f){let J=r1($),W=r1(f),Z=`${J}__${W}`;return Z.length>180?Z.slice(0,180):Z}function g8($,f){let J=r1($),W=r1(f);return`${J}__teamtask__${W}__${BD(6)}`}function tf($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+12),Q=Z.lastIndexOf("__");if(Q<=0)return null;let j=Z.slice(0,Q),H=Z.slice(Q+2);if(!W||!j||!H)return null;return{rootSessionId:W,agentId:j,teamTaskId:H}}function v8($){if(tf($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+f.length);if(!W||!Z)return null;return{rootSessionId:W,agentId:Z}}function u8($){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 t}from"zod";var uH={};w(uH,{isTerminalSessionStatus:()=>vH,isNonTerminalSessionStatus:()=>W0,SessionSource:()=>P0,SESSION_STATUSES:()=>c8,NON_TERMINAL_SESSION_STATUSES:()=>gH});import{SESSION_STATUS_VALUES as KD}from"@cline/shared";var c8=KD,gH=["idle","running","pending"];function vH($){return!gH.includes($)}function W0($){return!vH($)}var P0={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 GD=t.enum(c8),y0=t.object({version:t.literal(1),session_id:t.string().min(1),source:t.string().min(1),pid:t.number().int(),started_at:t.string().min(1),ended_at:t.string().min(1).optional(),exit_code:t.number().int().nullable().optional(),status:GD,interactive:t.boolean(),provider:t.string().min(1),model:t.string().min(1),cwd:t.string().min(1),workspace_root:t.string().min(1),team_name:t.string().min(1).optional(),enable_tools:t.boolean(),enable_spawn:t.boolean(),enable_teams:t.boolean(),prompt:t.string().optional(),metadata:t.record(t.string(),t.unknown()).optional(),messages_path:t.string().min(1).optional()});function cH($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function hZ($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let W=[],Z=new Set;for(let Q of J){if(Z.has(Q.name))continue;Z.add(Q.name),W.push(Q)}return W}function dH($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function k$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function SZ($,f){let J={...$};J.id=k$(J.id)??DD();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:k$(W?.id)??k$(J.modelId)??k$(f?.id),provider:k$(W?.provider)??k$(J.providerId)??k$(f?.provider),family:k$(W?.family)??k$(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 X6($){return $.map((f)=>SZ(f))}function A6($,f,J=[]){let W=$.map((X,A)=>{let Y=J[A],B=Y?.role===X.role&&JSON.stringify(Y.content)===JSON.stringify(X.content)?{...Y,...X}:{...X};return SZ(B)}),Z=J.length,Q=[];for(let X=Z;X<W.length;X+=1)if(W[X]?.role==="assistant")Q.push(X);if(Q.length===0){let X=[...W].reverse().findIndex((A)=>A.role==="assistant");if(X===-1)return W;Q.push(W.length-1-X)}let j=Q[Q.length-1],H=Q.some((X)=>W[X]?.metrics);for(let X of Q){let A=W[X],Y=A.metrics;if(!Y&&X===j&&!H){let V=f.usage;Y={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}W[X]={...SZ(A,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...Y?{metrics:Y}:{},ts:A.ts??f.endedAt.getTime()}}return W}function d8($){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 LD=120;function i1($){let f=$?.trim();return f?f.slice(0,LD):void 0}function CZ($){let f=RD($??"").trim();if(!f)return;return i1(f.split(`
411
- `)[0]?.trim())}function j1($){if(!$)return;let f={...$},J=i1(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 l8($){let f=j1($.metadata)??{},J=$.title!==void 0?i1($.title):CZ($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function EZ($){let f=tf($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=v8($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function bZ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:X6($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function lH($,f,J){PD(FD($),{recursive:!0}),UD($,`${JSON.stringify(bZ({updatedAt:f,context:J,messages:[]}),null,2)}
412
- `,"utf8")}function pH($,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 rH($,f,J){let W=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let Q=await f(Z);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}L0();var iH={};w(iH,{summarizeUsageFromMessages:()=>of,sumUsageTotals:()=>p8,getCurrentContextSize:()=>kZ,createInitialAccumulatedUsage:()=>B0,accumulateUsageTotals:()=>H0});function B0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function p8($){let f=B0();for(let J of $)f=H0(f,J);return f}function sf($){return typeof $==="number"&&Number.isFinite($)?$:0}function of($){let f=B0();for(let J of $){let W=J.metrics;if(!W)continue;f=H0(f,{inputTokens:sf(W.inputTokens),outputTokens:sf(W.outputTokens),cacheReadTokens:sf(W.cacheReadTokens),cacheWriteTokens:sf(W.cacheWriteTokens),totalCost:sf(W.cost)})}return f}function kZ($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let W=sf(J.metrics?.inputTokens);return W>0?W:void 0}return}function OD($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function IZ($){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 I$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,W=$.teamRole,Z="root";if(W==="teammate")Z="team_teammate";else if(W==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:W,teamAgentId:$.teamAgentId?.trim()||void 0}}function zD($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function _D($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let W=J?.trim();if(W)return W}return $.isPrimaryAgentEvent?"root":"unknown"}function xZ($,f,J){let{sessionId:W,config:Z,liveSession:Q,emit:j}=$,H=Z.telemetry,X=Q?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,Y=IZ(f),V=I$({agentId:J?.agentId??Y.agentId,conversationId:J?.conversationId??Y.conversationId,parentAgentId:J?.parentAgentId??Y.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??X?.getTeamId(),teamName:J?.teamName??X?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=OD(f.input);if(B)z4(H,{ulid:W,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",K=!f.error;if(O4(H,{ulid:W,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))_4(H,{ulid:W,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...V})}if(f.type==="notice"&&f.reason==="api_error")$8(H,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...V});if(f.type==="error")$8(H,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...V});if(f.type==="usage"&&Q?.turnUsageBaseline){let B=zD(f);if(A){Q.turnPrimaryUsage=H0(Q.turnPrimaryUsage??B0(),B);let G=H0(Q.turnUsageBaseline,Q.turnPrimaryUsage);$.usageBySession.set(W,G),wf(H,{ulid:W,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),D4(H,{ulid:W,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...V})}else{let G=_D({isPrimaryAgentEvent:A,overrides:J,eventMetadata:Y}),R=Q.turnUsageByAgent??new Map;Q.turnUsageByAgent=R,R.set(G,H0(R.get(G)??B0(),B))}let K=H0(Q.turnPrimaryUsage??B0(),p8(Q.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(W,H0(Q.turnAggregateUsageBaseline??Q.turnUsageBaseline,K))}if(f.type==="iteration_end"&&A)$.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:W,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:dH(f),ts:Date.now()}})}function H1($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as rO}from"@cline/shared";function nH($){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 TD($){let J=new TextEncoder().encode($),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function ND($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),nH(f)}async function Y6(){let $=ND(),f=nH(await TD($));return{verifier:$,challenge:f}}function V6($){return $.endsWith("/")?$.slice(0,-1):$}function n1($,f){return new URL(f,`${V6($)}/`).toString()}function ef($,f={}){let J=$.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:f.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[W,Z]=J.split("#",2);return{code:W||void 0,state:Z||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:f.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function MD($){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 _0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),Z=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=MD(Z);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function $2($){try{let f=JSON.parse($),J=f.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:Z}}catch{return{}}}function a1($,f){return Date.now()>=$.expires-f}async function f2($){if(!$.onManualCodeInput){let Q=await $.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let f,J,W=$.onManualCodeInput().then((Q)=>{f=Q,$.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return ef(f,$.parseOptions);if(await W,J)throw J;if(f)return ef(f,$.parseOptions);return{}}Z$();import{existsSync as R6,readFileSync as KL,statSync as GL}from"node:fs";import{basename as PL,dirname as U6,join as D6,resolve as F6}from"node:path";import{discoverPluginModulePaths as UL,resolveConfiguredPluginModulePaths as PX,resolvePluginConfigSearchPaths as FL,SKILLS_CONFIG_DIRECTORY_NAME as RL}from"@cline/shared/storage";import{resolve as rD}from"node:path";import{normalizePluginManifest as iD}from"@cline/shared";import{existsSync as U0,readFileSync as W2}from"node:fs";import{builtinModules as yD,createRequire as uZ}from"node:module";import{dirname as X1,extname as i8,isAbsolute as qD,resolve as c}from"node:path";import{fileURLToPath as tH}from"node:url";import{PLUGIN_FILE_EXTENSIONS as wD}from"@cline/shared";var sH=X1(tH(import.meta.url)),SD=uZ(import.meta.url),hD=c(sH,"..","..","..","..",".."),mZ=bD(hD),CD=["@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"],cZ=new Set(yD.flatMap(($)=>[$,$.replace(/^node:/,"")])),r8=new Set(wD),ED=["development","node","import","require","default"];function bD($){let f={},J={"@cline/sdk":c($,"packages/sdk/src/index.ts"),"@cline/agents":c($,"packages/agents/src/index.ts"),"@cline/core":c($,"packages/core/src/index.ts"),"@cline/llms":c($,"packages/llms/src/index.ts"),"@cline/shared":c($,"packages/shared/src/index.ts"),"@cline/shared/storage":c($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":c($,"packages/shared/src/db/index.ts")};for(let[W,Z]of Object.entries(J))if(U0(Z))f[W]=Z;for(let W of["agents","core","llms","shared"]){let Z=c($,"packages",W),Q=c(Z,"package.json");if(!U0(Q))continue;try{let j=JSON.parse(W2(Q,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let H=c(Z,j.exports);if(U0(H))f[j.name]=H;continue}if(typeof j.exports!=="object")continue;for(let[H,X]of Object.entries(j.exports)){let A=kD(Z,X);if(!A)continue;let Y=H==="."?j.name:`${j.name}/${H.replace(/^\.\//,"")}`;f[Y]=A}}catch{}}return f}function kD($,f){let J=dZ(f);if(!J)return null;let W=oH($,J);for(let Z of W)if(U0(Z))return Z;return null}function dZ($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let W of ED){let Z=dZ(J[W],f);if(Z)return Z}return null}function oH($,f){let J=f.replace(/^\.\//,""),W=[c($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[c($,`${Z}.ts`),c($,`${Z}.tsx`),c($,`${Z}.mts`),c($,`${Z}.cts`),...W]}return W}function ID($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function B6($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function J2($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function xD($){let f=J2($);if($===f)return".";return`.${$.slice(f.length)}`}function eH($){return J2($).startsWith("@cline/")}function gZ($,f){let J=J2(f),W=X1($);while(!0){let Z=c(W,"node_modules",J);if(U0(Z)||U0(c(Z,"package.json")))return!0;let Q=c(W,"..");if(Q===W)return!1;W=Q}}function aH($){return vZ($)!==null}function vZ($){try{return SD.resolve($)}catch{}return mD($)}function mD($){let f=J2($),J=$X(f);if(!J)return null;let W=c(J,"package.json");try{let Z=JSON.parse(W2(W,"utf8")),Q=xD($),j=Q==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,Q)?Z.exports[Q]:void 0,H=dZ(j)??(Q==="."&&typeof Z.main==="string"?Z.main:null);if(!H)return null;let X=c(J,H),A=[X,...oH(J,H).filter((Y)=>Y!==X)];for(let Y of A)if(U0(Y))return Y;return null}catch{return null}}function gD(){let $=[sH],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(X1(X1(f)));let J=process.execPath?.trim();if(J)$.push(X1(J));return[...new Set($.map((W)=>c(W)))]}function vD($,f){let J=$;while(!0){let W=c(J,"package.json");if(U0(W))try{if(JSON.parse(W2(W,"utf8")).name===f)return J}catch{}let Z=c(J,"node_modules",f,"package.json");if(U0(Z))return X1(Z);let Q=c(J,"..");if(Q===J)return null;J=Q}}function $X($){for(let f of gD()){let J=vD(f,$);if(J)return J}return null}function uD($){let J=X1($);for(let W=0;W<4;W++){let Z=c(J,"package.json");if(U0(Z))try{let j=JSON.parse(W2(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let Q=c(J,"..");if(Q===J)return!1;J=Q}return!1}function fX($,f){let J=f.startsWith("file:")?tH(f):qD(f)?f:c(X1($),f);if(U0(J)&&r8.has(i8(J)))return J;for(let W of r8){let Z=`${J}${W}`;if(U0(Z))return Z}for(let W of r8){let Z=c(J,`index${W}`);if(U0(Z))return Z}return null}function JX($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of J)for(let Z of $.matchAll(W)){let Q=Z[1];if(Q)f.add(Q)}return[...f]}function cD($){return i8($)!==".ts"}function WX($,f,J=new Set){if(J.has($)||!U0($))return;if(J.add($),!r8.has(i8($)))return;let W=W2($,"utf8"),Z=cD($);for(let Q of JX(W)){if(Q.startsWith("node:")||cZ.has(Q))continue;if(B6(Q)){if(!Z)continue;if(Object.hasOwn(mZ,Q)||Object.hasOwn(mZ,J2(Q))||gZ($,Q)||eH(Q)&&aH(Q)||f&&aH(Q))continue;throw Error(`Cannot find module '${J2(Q)}'`)}let j=fX($,Q);if(j)WX(j,f,J)}}function ZX($,f=new Set,J=new Set){if(f.has($)||!U0($))return J;if(f.add($),!r8.has(i8($)))return J;let W=W2($,"utf8");for(let Z of JX(W)){if(J.add(Z),B6(Z))continue;let Q=fX($,Z);if(Q)ZX(Q,f,J)}return J}function dD($,f){let J=uZ($),W={},Z=ZX($),Q=new Set(CD);for(let[j,H]of Object.entries(mZ)){try{J.resolve(j);continue}catch{}W[j]=H}for(let j of Z)if(B6(j)&&(eH(j)||f))Q.add(j);for(let j of Q){if(Object.hasOwn(W,j)||gZ($,j))continue;let H=vZ(j);if(H)W[j]=H}if(!f)return W;for(let j of Z){if(!B6(j)||Object.hasOwn(W,j)||gZ($,j)||j.startsWith("node:")||cZ.has(j))continue;let H=vZ(j);if(H)W[j]=H}return W}function lD($){let f=i8($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var t1;function pD(){if(t1!==void 0)return t1;let $=$X("jiti");if(!$)return t1=null,null;let f=c($,"dist","babel.cjs");if(!U0(f))return t1=null,null;try{let W=uZ(f)(f);t1=typeof W==="function"?W:null}catch{t1=null}return t1}async function QX($,f={}){let J=!uD($);WX($,J);let W=dD($,J),Z=ID(W),Q=await import("jiti"),j=typeof Q==="function"?Q:typeof Q.default==="function"?Q.default:void 0;if(!j)throw Error("Unable to load jiti");let H=Object.entries(Z).filter(([,V])=>lD(V)).map(([V])=>V),X=pD(),A=X?(V)=>X({...V,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...cZ],transformModules:H,tryNative:!1,...A?{transform:A}:{}}).import($,{})}function jX($,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 HX($){return typeof $==="object"&&$!==null}function lZ($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function nD($,f){if(!HX($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!lZ($.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")&&!lZ($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!lZ($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function aD($,f){if(!HX($))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"`);nD($,f)}async function n8($,f={}){let J=rD(f.cwd??process.cwd(),$),W=await QX(J,{useCache:f.useCache}),Z=f.exportName??"plugin",Q=W.default??W[Z];aD(Q,J);let j=Q,H=j.setup,X=H?(A,Y)=>{let V={...f.session,...Y.session},B={...Y,session:Object.keys(V).length>0?V:void 0,client:f.client??Y.client,user:f.user??Y.user,workspaceInfo:f.workspaceInfo??Y.workspaceInfo,automation:f.automation??Y.automation,logger:f.logger??Y.logger,telemetry:f.telemetry??Y.telemetry};return H(A,B)}:void 0;return{...j,manifest:iD(j.manifest),setup:X}}async function K6($,f={}){return(await s1($,f)).plugins}async function s1($,f={}){let J=[],W=[],Z=new Map,Q=0;for(let H of $)try{let X=await n8(H,f);if(!jX(X.manifest,f))continue;let A=Z.get(X.name);if(A)W.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:H,overriddenPluginPath:A.pluginPath,message:`Plugin "${X.name}" from ${H} overrides ${A.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:H,order:Q++})}catch(X){let A=X instanceof Error?X.message:String(X);J.push({pluginPath:H,phase:"load",message:A,stack:X instanceof Error?X.stack:void 0})}let j=[...Z.values()].sort((H,X)=>H.order-X.order);return{plugins:j.map((H)=>H.plugin),pluginPaths:j.map((H)=>H.pluginPath),failures:J,warnings:W}}import{existsSync as nZ}from"node:fs";import{createRequire as GX}from"node:module";import{dirname as G6,join as Q2}from"node:path";import{fileURLToPath as $L}from"node:url";var BX={};w(BX,{resolveSubprocessRuntimeExecutable:()=>pZ,buildSubprocessSandboxCommand:()=>VX,SubprocessSandbox:()=>Z2,CLINE_JS_RUNTIME_PATH_ENV:()=>YX});import{spawn as tD}from"node:child_process";import{basename as sD}from"node:path";import{augmentNodeCommandForDebug as oD,withResolvedClineBuildEnv as eD}from"@cline/shared";function XX($){if($ instanceof Error)return $;return Error(String($))}var YX="CLINE_JS_RUNTIME_PATH";function AX($){let f=$?.trim();if(!f)return!1;let J=sD(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function pZ($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[YX]?.trim();if(J)return J;let W=$.execPath?.trim()||process.execPath;if(AX(W))return W;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let Q=Z?.trim();if(Q&&AX(Q))return Q}return"node"}function VX($,f={}){let J=pZ({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return oD([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class Z2{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=VX($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=tD(f[0]??pZ(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:eD(process.env)});this.process=J;let W="",Z=(Q)=>{let j=W+Q;W=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{Z(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${XX(Q).message}`))}),J.on("exit",(Q,j)=>{this.process=null;let H=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(j)})${H?`: ${H}`:""}`))})}async call($,f,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,Q={type:"call",id:Z,method:$,args:f};return await new Promise((j,H)=>{let X={resolve:(A)=>j(A),reject:H};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),H(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,X),W.send(Q,(A)=>{if(!A)return;let Y=this.clearPendingRequest(Z);if(!Y)return;Y.reject(Error(`${this.processLabel} failed to send call "${$}": ${XX(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 fL($){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 a8($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function JL(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function WL(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=GX($).resolve(`${JL()}/package.json`),W=Q2(G6(J),"extensions","plugin-sandbox-bootstrap.js");return nZ(W)?W:void 0}catch{return}}function ZL(){let $=process.execPath?.trim();if(!$)return;let f=Q2(G6(G6($)),"extensions","plugin-sandbox-bootstrap.js");return nZ(f)?f:void 0}function QL(){let $=G6($L(import.meta.url)),f=GX(import.meta.url),J=[Q2($,"plugin-sandbox-bootstrap.js"),Q2($,"extensions","plugin-sandbox-bootstrap.js"),Q2($,"agents","plugin-sandbox-bootstrap.js"),WL(),ZL()];for(let Q of J.filter((j)=>typeof j==="string"))if(nZ(Q))return{file:Q};let W=Q2($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
413
- `)}}var rZ=QL();function iZ($,f,J){if(typeof $==="number"&&$>0)return $;if(J){let W=process.env[J];if(W){let Z=Number(W);if(Number.isInteger(Z)&&Z>0)return Z}}return f}async function P6($){let f=new Z2({name:"plugin-sandbox",..."file"in rZ?{bootstrapFile:rZ.file}:{bootstrapScript:rZ.script},onEvent:$.onEvent}),J=iZ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),W=iZ($.hookTimeoutMs,3000),Z=iZ($.contributionTimeoutMs,60000),Q={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,H=()=>{return j??=f.call("initialize",Q,{timeoutMs:J}).finally(()=>{j=void 0}),j},X;try{X=await f.call("initialize",Q,{timeoutMs:J})}catch(V){throw await f.shutdown().catch(()=>{}),V}let A=X.plugins.map(fL);return{extensions:A.map((V)=>{let B={name:V.name,__clinePluginPath:V.pluginPath,manifest:V.manifest,setup:(K)=>{jL(K,f,V,Z,H),HL(K,f,V,Z,H),XL(K,f,V,Z,H),YL(K,f,V,Z,H),AL(K,V)}};return B.hooks=BL(f,V,W,H),B}),failures:X.failures,pluginPaths:A.map((V)=>V.pluginPath),shutdown:async()=>{await f.shutdown()},warnings:X.warnings}}function jL($,f,J,W,Z){for(let Q of J.contributions?.tools??[]){let j={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(H,X)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:H,context:X},{timeoutMs:W})}catch(A){if(!a8(A))throw A;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:H,context:X},{timeoutMs:W})}}};$.registerTool(j)}}function HL($,f,J,W,Z){for(let Q of J.contributions?.commands??[])$.registerCommand({name:Q.name,description:Q.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}catch(H){if(!a8(H))throw H;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}}})}function XL($,f,J,W,Z){for(let Q of J.contributions?.rules??[])$.registerRule({id:Q.ruleId,source:Q.source,content:Q.hasContentHandler===!0?async()=>{try{return await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}catch(j){if(!a8(j))throw j;return await Z(),await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}}:Q.content??""})}function AL($,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 YL($,f,J,W,Z){for(let Q of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:Q.name,async build(j){try{let H=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return KX(H)?H:j}catch(H){if(!a8(H))throw H;await Z();let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return KX(X)?X:j}}})}function KX($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function VL($,f,J,W,Z){return async(Q)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}catch(j){if(!a8(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}}}function BL($,f,J,W){let Z={};for(let Q of f.hooks??[])Z[Q]=VL($,f.pluginId,Q,J,W);return Object.keys(Z).length>0?Z:void 0}var tZ="package.json",DL="package";function t8($){return FL($)}function s8($){return UL($)}function LL($){try{return R6($)&&GL($).isDirectory()}catch{return!1}}function sZ($){let f=[],J=new Set;for(let W of $){let Z=F6(W);if(J.has(Z))continue;J.add(Z),f.push(Z)}return f}function UX($){let f=sZ($);return k4(f)}function FX($){return t8($).flatMap((f)=>s8(f)).filter((f)=>R6(f))}function OL($,f){let J=[];for(let W of $)try{J.push(...PX([W],f))}catch{}return J}function aZ($){return typeof $==="object"&&$!==null}function zL($){try{let f=JSON.parse(KL(D6($,tZ),"utf8"));if(!aZ(f)||!aZ(f.cline))return[];let J=f.cline.plugins;if(!Array.isArray(J))return[];let W=[];for(let Z of J){if(typeof Z==="string"){W.push(Z);continue}if(!aZ(Z)||!Array.isArray(Z.paths))continue;for(let Q of Z.paths)if(typeof Q==="string")W.push(Q)}return W}catch{return[]}}function RX($,f){let J=F6(f);return zL($).some((W)=>F6($,W)===J)}function _L($,f){return PL($)===DL&&R6(D6(U6($),tZ))&&RX(U6($),f)}function TL($){let f=F6($),J=[],W=U6(f);while(!0){if(_L(W,f)){J.push(W);break}if(R6(D6(W,tZ))){if(RX(W,f))J.push(W);break}let Z=U6(W);if(Z===W)break;W=Z}return sZ(J)}function o1($={}){let f=$.cwd??process.cwd(),J=FX($.workspacePath),W=PX($.pluginPaths??[],f);return UX([...W,...J])}function NL($={}){let f=$.cwd??process.cwd(),J=FX($.workspacePath),W=OL($.pluginPaths??[],f);return UX([...W,...J])}function e1($){let f=[];for(let J of $)for(let W of TL(J)){let Z=D6(W,RL);if(LL(Z))f.push(Z)}return sZ(f)}function DX($={}){return e1(NL($))}async function j2($={}){let f=o1($);if(f.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let W=await s1(f,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:W.plugins,failures:W.failures,pluginPaths:W.pluginPaths,warnings:W.warnings}}let J=await P6({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 ML}from"node:child_process";import{promisify as yL}from"node:util";var qL=yL(ML);function oZ($,f){$?.log(f,{severity:"warn"})}function wL($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,Z=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:Z}}async function $f($,f){let J=await qL("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function eZ($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:W}=await $f($,["for-each-ref","--format=%(refname)",J]),Z=W.trim().split(`
414
- `).filter(Boolean);await Promise.allSettled(Z.map((Q)=>$f($,["update-ref","-d",Q])))}catch{}}async function LX($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((W)=>$f($,["update-ref",`refs/cline/checkpoints/${f}/${W.runCount}`,W.ref])))}function SL($,f){let J=$.findIndex((W)=>W.runCount===f.runCount);if(J<0)return[...$,f];return $.map((W,Z)=>Z===J?f:W)}function OX($){let f=$.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await $f($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await W())return;let Q=async(A)=>{try{let V=(await $f($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!V)return;return{ref:V,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(Y){oZ($.logger,`${A}: ${Y instanceof Error?Y.message:String(Y)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,H="";try{H=(await $f($.cwd,["stash","create",j])).stdout.trim()}catch(A){return oZ($.logger,`Checkpoint snapshot failed: ${A instanceof Error?A.message:String(A)}`),Q("Checkpoint HEAD fallback failed")}if(!H)return Q("Checkpoint HEAD fallback failed");let X=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await $f($.cwd,["update-ref",X,H])}catch(A){oZ($.logger,`Checkpoint store failed: ${A instanceof Error?A.message:String(A)}`);return}return{ref:H,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||f<1)return;let j=await Z();if(!j)return;let H=await $.readSessionMetadata(),X=wL(H);if(X?.latest.ref===j.ref)return;let A=SL(X?.history??[],j);await $.writeSessionMetadata({...H??{},checkpoint:{latest:j,history:A}});return}}}import{spawn as gL}from"node:child_process";import{appendFileSync as vL,readFileSync as uL}from"node:fs";import{join as cL}from"node:path";import{augmentNodeCommandForDebug as TX,withResolvedClineBuildEnv as J9}from"@cline/shared";import{ensureHookLogDir as zX}from"@cline/shared/storage";function H2($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as hL,readdirSync as CL}from"node:fs";import{basename as EL,extname as bL,join as kL}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as L6,resolveHooksConfigSearchPaths as IL}from"@cline/shared/storage";function o8($){return IL($)}var X2;((Y)=>{Y.TaskStart="TaskStart";Y.TaskResume="TaskResume";Y.TaskCancel="TaskCancel";Y.TaskComplete="TaskComplete";Y.TaskError="TaskError";Y.PreToolUse="PreToolUse";Y.PostToolUse="PostToolUse";Y.UserPromptSubmit="UserPromptSubmit";Y.PreCompact="PreCompact";Y.SessionShutdown="SessionShutdown"})(X2||={});var e8={["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"},xL=new Map(Object.values(X2).map(($)=>[$.toLowerCase(),$])),mL=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function $J($){let f=bL($).toLowerCase();if(!mL.has(f))return;let J=EL($,f).trim().toLowerCase();return xL.get(J)}function A1($){let f=[],J=new Set,W=o8($).filter((Z)=>hL(Z));for(let Z of W)try{for(let Q of CL(Z,{withFileTypes:!0})){if(!Q.isFile())continue;let j=$J(Q.name);if(!j)continue;let H=kL(Z,Q.name);if(J.has(H))continue;J.add(H),f.push({fileName:j,hookEventName:e8[j],path:H})}}catch{}return f.sort((Z,Q)=>Z.path.localeCompare(Q.path))}function z6($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))f[J]=typeof W==="string"?W:JSON.stringify(W);return f}function O6($,f,J){let W=J instanceof Error?`: ${J.message}`:"",Z=`${f}${W}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function dL($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
415
- `),W=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:W.length>0?W:void 0}}function lL($){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 $9($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function F0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:W,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function pL($){let f=$.trim();if(!f)return{};let W=f.split(`
416
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function rL($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,Z)=>{let Q=!1,j=()=>{J.off("error",X),J.off("finish",A),$.off("close",Y)},H=(V)=>{if(Q)return;if(Q=!0,j(),V){let B=V.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){W();return}Z(V);return}W()},X=(V)=>H(V),A=()=>H(),Y=()=>H();J.on("error",X),J.once("finish",A),$.once("close",Y);try{J.end(f)}catch(V){H(V)}})}async function NX($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await _X($,f)}catch(J){let W=aL(f.command,process.platform,J);if(!W)throw J;return await _X($,{...f,command:W})}}async function _X($,f){let J=TX(f.command,{env:f.env,debugRole:"hook"}),W=gL(J[0],J.slice(1),{cwd:f.cwd,env:J9(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached}),Z=new Promise((B)=>{W.once("spawn",()=>B())}),Q=new Promise((B,K)=>{W.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,Q]),await rL(W,j),f.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let H="",X="",A=!1,Y;W.stdout.on("data",(B)=>{H+=B.toString()}),W.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,W.kill("SIGKILL")},f.timeoutMs);W.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:G,parseError:R}=pL(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:G,parseError:R,timedOut:A})})});return await Promise.race([V,Q])}function iL($){try{let J=uL($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let Z=W.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function nL($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function aL($,f=process.platform,J){if(f!=="win32"||!nL(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function MX($){if($.length===0)return;let[f,...J]=$,W=f.replace(/\\/g,"/").toLowerCase(),Z=W.split("/").at(-1)??W;if(Z==="env")return MX(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 tL($){let f=iL($);if(f&&f.length>0)return[...MX(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 TX(["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 sL($){let f={};for(let J of A1($)){if(!J.hookEventName)continue;let W=J.hookEventName,Z=f[W]??[];Z.push(tL(J.path)),f[W]=Z}return f}async function oL($){let f;for(let J of $.commands){let W=J.join(" ");try{let Z=await NX($.payload,{command:J,cwd:$.cwd,env:J9(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){O6($.logger,`hook command timed out: ${W}`);continue}if(Z?.parseError){O6($.logger,`hook command returned invalid JSON control output: ${W} (${Z.parseError})`);continue}f=dL(f,lL(Z?.parsedJson))}catch(Z){O6($.logger,`hook command failed: ${W}`,Z)}}return f}function ff($){for(let f of $.commands){let J=f.join(" ");NX($.payload,{command:f,cwd:$.cwd,env:J9(process.env),detached:!0}).catch((W)=>{O6($.logger,`hook command failed: ${J}`,W)})}}function Y1($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function f9($,f){return{...Y1($.snapshot),userMessage:f}}function yX($){return{...Y1($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function qX($){return{...Y1($.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 wX($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function eL($){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 A2($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(W)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...W})}
417
- `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??cL(zX(),"hooks.jsonl");zX(j),vL(j,Z,"utf8")};return{beforeRun:async(W)=>{let Z=f9(W,"");J({...F0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let Z=yX(W);J({...F0(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:z6(Z.call.input)}});return},afterTool:async(W)=>{let Z=qX(W);J({...F0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:z6(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:W,result:Z})=>{let Q=Y1(W);if(Z.status==="completed"){J({...F0(Q,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||$9(Z.error?.message)){J({...F0(Q,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...F0(Q,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let Z=f9({snapshot:W.snapshot},wX(W.message.content));J({...F0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function fJ($){let f=sL($.workspacePath);if(!Object.values(f).some((V)=>V.length>0))return;let W=async(V,B)=>{let K=f[B]??[];if(K.length===0)return;ff({commands:K,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...F0(V,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...F0(V,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=f.prompt_submit??[];if(B.length>0)ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...F0(V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},Q=async(V)=>{let B=f.tool_call??[];if(B.length===0)return;return oL({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...F0(V,$),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:z6(V.call.input)}}})},j=async(V)=>{let B=f.tool_result??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...F0(V,$),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:z6(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},H=async(V)=>{let B=f.agent_end??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...F0(V,$),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},X=async(V)=>{let B=f.agent_error??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...F0(V,$),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},A=async(V)=>{if($9(V.reason)){let K=f.agent_abort??[];if(K.length>0)ff({commands:K,cwd:$.cwd,logger:$.logger,payload:{...F0(V,$),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...F0(V,$),hookName:"session_shutdown",reason:V.reason}})},Y={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)Y.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(Y1(V.snapshot),B);return};if((f.prompt_submit?.length??0)>0)Y.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(f9({snapshot:V.snapshot},wX(V.message.content)))}}if((f.tool_call?.length??0)>0)Y.beforeTool=async(V)=>{let B=await Q(yX(V));return eL(B)};if((f.tool_result?.length??0)>0)Y.afterTool=async(V)=>{await j(qX(V));return};if((f.agent_end?.length??0)>0)Y.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await H({...Y1(V),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let V=Y.afterRun;Y.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:G}=B;if(G.status==="aborted"||$9(G.error?.message)){await A({...Y1(K),reason:G.error?.message});return}if(G.error)await X({...Y1(K),iteration:G.iterations,error:G.error})}}return Y}function Y2($){return H2("core.hook_config_files",fJ($))}function Jf($,f){let J=$.map((W)=>W[f]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let Z;for(let Q of J){let j=await Q(W);if(!j||typeof j!=="object")continue;let H=j;Z={...Z??{},...H,stop:Z?.stop===!0||H.stop===!0?!0:H.stop,options:Z?.options||H.options?{...Z?.options??{},...H.options??{}}:void 0}}return Z}}function Wf($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:Jf(f,"beforeRun"),afterRun:Jf(f,"afterRun"),beforeModel:Jf(f,"beforeModel"),afterModel:Jf(f,"afterModel"),beforeTool:Jf(f,"beforeTool"),afterTool:Jf(f,"afterTool"),onEvent:Jf(f,"onEvent")}}var SX={};w(SX,{normalizeRuntimeCapabilities:()=>R0});function R0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let W=f&&Object.keys(f).length>0;if(!W&&!J)return;return{...W?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}var fA={};w(fA,{toProviderConfig:()=>v0,emptyStoredProviderSettings:()=>G1,StoredProviderSettingsSchema:()=>G2,StoredProviderSettingsEntrySchema:()=>a6,ProviderSettingsSchemaTyped:()=>YJ});import{z as K1}from"zod";var $A={};w($A,{toProviderConfig:()=>v0,safeParseSettings:()=>n6,safeCreateProviderConfig:()=>U9,parseSettings:()=>i6,normalizeProviderId:()=>K2,isBuiltInProviderId:()=>G9,createProviderConfig:()=>P9,SapSettingsSchema:()=>l6,ReasoningSettingsSchema:()=>v6,ProviderSettingsSchema:()=>B1,ProviderProtocolSchema:()=>x6,ProviderIdSchema:()=>AJ,ProviderClientSchema:()=>m6,OcaSettingsSchema:()=>p6,ModelCatalogSettingsSchema:()=>r6,GcpSettingsSchema:()=>c6,BUILT_IN_PROVIDER_IDS:()=>K9,BUILT_IN_PROVIDER:()=>XJ,AzureSettingsSchema:()=>d6,AwsSettingsSchema:()=>u6,AuthSettingsSchema:()=>g6});import*as g0 from"@cline/llms";import{z as y}from"zod";L0();var rX={};w(rX,{refreshOcaToken:()=>WJ,loginOcaOAuth:()=>V2,getValidOcaCredentials:()=>ZJ,generateOcaOpcRequestId:()=>M6,createOcaRequestHeaders:()=>j9,createOcaOAuthProvider:()=>Q9,OCI_HEADER_OPC_REQUEST_ID:()=>gX,DEFAULT_INTERNAL_OCA_BASE_URL:()=>_6,DEFAULT_INTERNAL_IDCS_URL:()=>bX,DEFAULT_INTERNAL_IDCS_SCOPES:()=>kX,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>EX,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>T6,DEFAULT_EXTERNAL_IDCS_URL:()=>xX,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>mX,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>IX});import{nanoid as CX}from"nanoid";class W9{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+W})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var hX={};w(hX,{startLocalOAuthServer:()=>$$});function $O(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function $$($){let f=await import("node:http"),J=$.host??"127.0.0.1",W=$.timeoutMs??300000,Z=$.successHtml??fO,Q=$O(),j=!1,H=null,X=null,A=null,Y=(K)=>{if(j)return;j=!0,Q.resolve(K)},V=()=>{if(H)clearTimeout(H),H=null;let K=A;if(A=null,X)X.close(),X=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return H=setTimeout(()=>{V(),Y(null)},W),Q.promise};for(let K of $.ports){let G=f.createServer((P,U)=>{try{let F=new URL(P.url||"",`http://${J}:${K}`);if(F.pathname!==$.callbackPath){U.statusCode=404,U.end("Not found");return}let z={url:F,code:F.searchParams.get("code")??void 0,state:F.searchParams.get("state")??void 0,provider:F.searchParams.get("provider")??void 0,error:F.searchParams.get("error")??void 0};if(z.error){U.statusCode=400,U.end(`Authentication failed: ${z.error}`),V(),Y(z);return}if(!z.code){U.statusCode=400,U.end("Missing authorization code");return}if($.expectedState&&z.state!==$.expectedState){U.statusCode=400,U.end("State mismatch");return}U.statusCode=200,U.setHeader("Content-Type","text/html; charset=utf-8"),U.end(Z),V(),Y(z)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((P)=>{let U=(F)=>{G.off("error",U),P({bound:!1,error:F})};G.once("error",U),G.listen(K,J,()=>{G.off("error",U),X=G,P({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){A=K;let P=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:P})).catch(()=>{});return{callbackUrl:P,waitForCallback:B,cancelWait:()=>{V(),Y(null)},close:()=>{V(),Y(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var fO=`<!DOCTYPE html>
418
- <html lang="en">
419
- <head>
420
- <meta charset="utf-8">
421
- <meta name="viewport" content="width=device-width, initial-scale=1">
422
- <title>Authentication Successful</title>
423
- <style>
424
- * { margin: 0; padding: 0; box-sizing: border-box; }
425
- body {
426
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
427
- min-height: 100vh;
428
- display: flex;
429
- align-items: center;
430
- justify-content: center;
431
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
432
- color: #fff;
433
- }
434
- .container { text-align: center; padding: 48px; max-width: 420px; }
435
- .icon {
436
- width: 72px; height: 72px; margin: 0 auto 24px;
437
- background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%);
438
- border-radius: 50%;
439
- display: flex; align-items: center; justify-content: center;
440
- }
441
- .icon svg { width: 36px; height: 36px; stroke: #fff; stroke-width: 3; fill: none; }
442
- h1 { font-size: 24px; font-weight: 600; margin-bottom: 12px; }
443
- p { font-size: 15px; color: rgba(255,255,255,0.7); line-height: 1.5; }
444
- .closing { margin-top: 32px; font-size: 13px; color: rgba(255,255,255,0.5); }
445
- </style>
446
- </head>
447
- <body>
448
- <div class="container">
449
- <div class="icon">
450
- <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
451
- </div>
452
- <h1>Authentication Successful</h1>
453
- <p>You're now signed in. You can close this window.</p>
454
- <p class="closing">This window will close automatically...</p>
455
- </div>
456
- <script>setTimeout(() => window.close(), 3000);</script>
457
- </body>
458
- </html>`;var EX="a8331954c0cf48ba99b5dd223a14c6ea",bX="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",kX="openid offline_access",_6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",IX="c1aba3deed5740659981a752714eba33",xX="https://login-ext.identity.oraclecloud.com",mX="openid offline_access",T6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",gX="opc-request-id",JO="/auth/oca",WO=Array.from({length:11},($,f)=>48801+f),ZO=300000,QO=30000,vX=30000,jO=600000;class N6 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 V1={internal:{clientId:EX,idcsUrl:bX,scopes:kX,baseUrl:_6},external:{clientId:IX,idcsUrl:xX,scopes:mX,baseUrl:T6}},JJ=new Map,HO=86400000,XO=300000,AO=32,Z9=new W9(HO,AO);function uX($){if(typeof $==="function")return $();return $??"internal"}function cX($){return{internal:{clientId:$?.internal?.clientId??V1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??V1.internal.idcsUrl,scopes:$?.internal?.scopes??V1.internal.scopes,baseUrl:$?.internal?.baseUrl??V1.internal.baseUrl},external:{clientId:$?.external?.clientId??V1.external.clientId,idcsUrl:$?.external?.idcsUrl??V1.external.idcsUrl,scopes:$?.external?.scopes??V1.external.scopes,baseUrl:$?.external?.baseUrl??V1.external.baseUrl}}}function YO($=Date.now()){let f=$-jO;for(let[J,W]of JJ.entries())if(W.createdAt<f)JJ.delete(J)}function VO($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=_0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=_0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function dX($,f,J){let W=$.access_token;if(!W)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let Q=_0($.id_token),j=_0(W),H=Q?.sub??j?.sub,X=Q?.email??j?.email;return{access:W,refresh:Z,expires:VO($,W,$.id_token),accountId:H??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:H,idToken:$.id_token}}}async function lX($,f){let J=V6($),W=Z9.get(J);if(W)return W;let Z=`${J}/.well-known/openid-configuration`,Q=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!Q.ok){let X=`${J}/oauth2/v1/token`;return Z9.set(J,X,Date.now(),XO),X}let H=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return Z9.set(J,H),H}function pX($){return{code:$.error,message:$.error_description}}async function BO($){let f=JJ.get($.state);if(!f)throw Error("No PKCE verifier found for this state");JJ.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,W=await lX(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await Q.json();if(!Q.ok){let X=pX(j);throw new N6(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let H=_0(j.id_token);if(!j.id_token||!H)throw Error("No ID token received from OCA");if(H.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return dX(j,$.mode)}function KO($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${V6(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 V2($){O$($.telemetry,"oca");let f=cX($.config),J=uX($.mode),W=$.callbackPorts?.length?$.callbackPorts:WO,Z=$.callbackPath??JO,Q=$.requestTimeoutMs??vX,j=await $$({ports:W,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),H=j.callbackUrl;if(!H)throw Error("Unable to bind local OAuth callback server");let X=CX(16),A=CX(16),{verifier:Y,challenge:V}=await Y6();YO(),JJ.set(X,{verifier:Y,nonce:A,mode:J,redirectUri:H,createdAt:Date.now()});let B=KO({callbackUrl:H,mode:J,state:X,nonce:A,challenge:V,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await f2({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==X)throw Error("State mismatch");let P=await BO({code:G,state:R,mode:J,config:f,requestTimeoutMs:Q});return z$($.telemetry,"oca"),T$($.telemetry,{id:P.accountId,email:P.email,provider:"oca"}),P}catch(K){throw _$($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function WJ($,f={}){let J=cX(f.config),W=f.requestTimeoutMs??vX,Z=$.metadata?.mode,Q=Z==="internal"||Z==="external"?Z:uX(f.mode),j=Q==="external"?J.external:J.internal,H=await lX(j.idcsUrl,W),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),A=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(W)}),Y=await A.json();if(!A.ok){let V=pX(Y);throw new N6(`Token refresh failed: ${A.status}${V.message?` - ${V.message}`:""}`,{status:A.status,errorCode:V.code})}return dX(Y,Q,$)}async function ZJ($,f,J){if(!$)return null;let W=f?.refreshBufferMs??J?.refreshBufferMs??ZO,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??QO;if(f?.forceRefresh!==!0&&!a1($,W))return $;try{return await WJ($,J)}catch(j){if(j instanceof N6&&j.isLikelyInvalidGrant())return n$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function Q9($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return V2({...$,callbacks:f})},async refreshToken(f){return WJ(f,$)},getApiKey(f){return f.access}}}async function M6($,f){let J=new TextEncoder,W=async(A)=>{let Y=await crypto.subtle.digest("SHA-256",J.encode(A));return Array.from(new Uint8Array(Y).slice(0,4),(V)=>V.toString(16).padStart(2,"0")).join("")},[Z,Q]=await Promise.all([W(f),W($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),H=new Uint32Array(1);crypto.getRandomValues(H);let X=(H[0]??0).toString(16).padStart(8,"0");return Z+Q+j+X}async function j9($){let f=await M6($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[gX]:f}}var eX={};w(eX,{resolveProviderConfig:()=>HJ,getProviderConfig:()=>I6,getLiveModelsCatalog:()=>B2,clearPublicModelsCatalogCache:()=>bO,clearPrivateModelsCatalogCache:()=>B9,clearLiveModelsCatalogCache:()=>V9,OPENAI_COMPATIBLE_PROVIDERS:()=>jJ,DEFAULT_MODELS_CATALOG_URL:()=>C6});import*as X0 from"@cline/llms";function H9($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter((f)=>f.length>0)}function GO($,f){let J=H9($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let W=$,Z=H9(W.data??W.models);if(Z.length>0)return Z;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let j=Object.keys(W.models).filter((H)=>H.trim().length>0);if(j.length>0)return j}let Q=W.providers?.[f];if(Q&&typeof Q==="object"){let H=H9(Q.models??Q);if(H.length>0)return H}return[]}async function y6($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return GO(await J.json(),f)}function iX($){return $.replace(/\/+$/,"")}function q6($,f,J){let W=J?.trim();if(!W)return;let Z=$?.trim();if(!Z||!f?.trim())return W;try{let Q=new URL(W),j=new URL(f),H=new URL(Z);if(Q.origin!==j.origin)return W;let X=iX(j.pathname),A=iX(H.pathname);if(X&&Q.pathname.startsWith(`${X}/`)){let Y=Q.pathname.slice(X.length);H.pathname=`${A}${Y}`}else H.pathname=Q.pathname;return H.search=Q.search,H.hash=Q.hash,H.toString()}catch{return W}}function PO($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function UO($){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 FO=Object.values(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:PO($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),aX=Object.fromEntries(FO.map(($)=>[$.id,$]));function RO($){return aX[$]}function DO(){return Object.fromEntries(Object.entries(aX).filter(([,$])=>UO($)))}function tX($=[]){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 C6="https://models.dev/api.json",LO=600000,sX=300000,OO=5000,h6=new Map,QJ=new Map,X9=new Map,w6=new Map;async function zO(){return X0.getGeneratedProviderModels()}async function _O($,f={},J={},W={},Z={},Q={}){let j=await zO(),H=X0.resolveProviderModelCatalogKeys($),X=Object.assign({},...H.map((V)=>j[V]??{})),A=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),Y=Object.keys(Z).length>0;if(A&&Y)return X0.sortModelsByReleaseDate({...Z,...Q});if($==="openai-codex")return X0.sortModelsByReleaseDate({...f,...X0.filterOpenAICodexModels(J),...Z,...Q});return X0.sortModelsByReleaseDate({...X,...f,...J,...W,...Z,...Q})}function TO($,f){let J=X0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((W)=>f[W]??{}))}function E6($){let f=$?.trim();return f&&f.length>0?f:""}function Y9($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function NO($){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 MO($,f){return`${$}:${E6(f.baseUrl)}:${NO(Y9(f)??"")}`}async function b6($,f,J=OO){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await fetch($,{...f,signal:W.signal})}finally{clearTimeout(Z)}}function Zf($,f,J){if(J&&!$.includes(f))$.push(f)}function k6($,f){let J=["streaming","tools"];return Zf(J,"images",Boolean(f.supportsImages)),Zf(J,"prompt-cache",Boolean(f.supportsPromptCache)),Zf(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 yO($,f){let J=await b6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let H=j.id?.trim();if(!H)continue;if(H.includes("whisper")||H.includes("tts")||H.includes("embedding"))continue;let X=j.supported_features??[];Q[H]=k6(H,{name:H,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return Q}function nX($){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 b6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let H=j.id?.trim();if(!H)continue;Q[H]=k6(H,{name:H,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}async function wO($,f){let W=`${(E6($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await b6(W,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],H={};for(let X of j){let A=X.id?.trim();if(!A)continue;let Y=X.supported_features??[],V=X.supported_sampling_parameters??[],B=X.input_modalities??[],K=["streaming"];Zf(K,"tools",Y.includes("tools")),Zf(K,"reasoning",Y.includes("reasoning")),Zf(K,"temperature",V.includes("temperature")),Zf(K,"images",B.includes("image"));let G={input:nX(X.pricing?.prompt),output:nX(X.pricing?.completion)};H[A]={id:A,name:X.name??A,description:X.description,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return H}function SO($){let f=E6($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function hO($,f){let W=`${SO($.baseUrl)}/v1/model/info`,Z=async(A)=>b6(W,{method:"GET",headers:{accept:"application/json",...A}}),Q=await Z({"x-litellm-api-key":f});if(!Q.ok)Q=await Z({Authorization:`Bearer ${f}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let H=(await Q.json())?.data??[],X={};for(let A of H){let Y=A.model_name?.trim(),B=A.litellm_params?.model?.trim()||Y;if(!B)continue;let K=A.model_info,G=k6(B,{name:Y??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(X[B]=G,Y)X[Y]={...G,id:Y,name:Y}}return X}var oX={baseten:yO,hicap:qO,litellm:hO,poolside:wO},A9=new Map,S6=new Map;function CO($,f){return`${$}:${E6(f.baseUrl)}`}async function EO($,f,J){let W=X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=q6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!Z)return{};let Q=f?.cacheTtlMs??sX,j=CO($,J),H=Date.now(),X=A9.get(j);if(X&&X.expiresAt>H)return X.data;let A=S6.get(j);if(A)return A;let Y=y6(Z,$).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,k6(K,{name:K})]));return A9.set(j,{data:B,expiresAt:H+Q}),B}).finally(()=>{S6.delete(j)});return S6.set(j,Y),Y}function bO(){A9.clear(),S6.clear()}async function kO($,f){let J=Y9(f);if(!J)return{};let W=oX[$];if(!W)return{};return W(f,J)}function IO($,f,J){if(!J)return!1;if(!oX[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(Y9(J))}async function xO($,f,J){let W=f?.cacheTtlMs??sX,Z=MO($,J),Q=Date.now(),j=X9.get(Z);if(j&&j.expiresAt>Q)return j.data;let H=w6.get(Z);if(H)return H;let X=kO($,J).then((A)=>{return X9.set(Z,{data:A,expiresAt:Q+W}),A}).finally(()=>{w6.delete(Z)});return w6.set(Z,X),X}async function mO($){return X0.fetchModelsDevProviderModels($,globalThis.fetch)}async function B2($={}){let f=$.url??C6,J=$.cacheTtlMs??LO,W=Date.now(),Z=h6.get(f);if(Z&&Z.expiresAt>W)return Z.data;let Q=QJ.get(f);if(Q)return Q;let j=mO(f).then((H)=>{return h6.set(f,{data:H,expiresAt:W+J}),H}).finally(()=>{QJ.delete(f)});return QJ.set(f,j),j}function V9($){if($){h6.delete($),QJ.delete($);return}h6.clear(),QJ.clear()}function B9(){X9.clear(),w6.clear()}function gO($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:tX(J.capabilities)}]))}var jJ=gO(DO());function I6($){let f=RO($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:tX(f.capabilities)}}async function HJ($,f,J){let W=I6($);if(!W)return;try{let Z=f?.loadLatestOnInit?await B2(f):void 0,Q=Z?TO($,Z):{},j=J&&IO($,f,J)?await xO($,f,J):{},X=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:W.modelId,baseUrl:W.baseUrl}:J,A=X?await EO($,f,X).catch(()=>({})):{},Y=await _O($,W.knownModels,Q,j,A,J?.knownModels);return{...W,knownModels:Y}}catch(Z){if(f?.failOnError)throw Z;return W}}var XJ=g0.BUILT_IN_PROVIDER,K9=g0.BUILT_IN_PROVIDER_IDS,G9=g0.isBuiltInProviderId,K2=g0.normalizeProviderId,AJ=y.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),x6=y.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),m6=y.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),g6=y.object({apiKey:y.string().optional(),accessToken:y.string().optional(),refreshToken:y.string().optional(),expiresAt:y.number().int().positive().optional(),accountId:y.string().optional()}),vO=y.enum(["none","low","medium","high","xhigh"]),v6=y.object({enabled:y.boolean().optional(),effort:vO.optional(),budgetTokens:y.number().int().positive().optional()}),u6=y.object({accessKey:y.string().optional(),secretKey:y.string().optional(),sessionToken:y.string().optional(),region:y.string().optional(),profile:y.string().optional(),authentication:y.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:y.boolean().optional(),useCrossRegionInference:y.boolean().optional(),useGlobalInference:y.boolean().optional(),endpoint:y.string().url().optional(),customModelBaseId:y.string().optional()}),c6=y.object({projectId:y.string().optional(),region:y.string().optional()}),d6=y.object({apiVersion:y.string().optional(),useIdentity:y.boolean().optional()}),l6=y.object({clientId:y.string().optional(),clientSecret:y.string().optional(),tokenUrl:y.string().url().optional(),resourceGroup:y.string().optional(),deploymentId:y.string().optional(),useOrchestrationMode:y.boolean().optional(),api:y.enum(["orchestration","foundation-models"]).optional(),defaultSettings:y.record(y.string(),y.unknown()).optional()}),p6=y.object({mode:y.enum(["internal","external"]).optional(),usePromptCache:y.boolean().optional()}),r6=y.object({loadLatestOnInit:y.boolean().optional(),loadPrivateOnAuth:y.boolean().optional(),url:y.string().url().optional(),cacheTtlMs:y.number().int().positive().optional(),failOnError:y.boolean().optional()}),B1=y.object({provider:AJ,apiKey:y.string().optional(),auth:g6.optional(),model:y.string().optional(),protocol:x6.optional(),client:m6.optional(),routingProviderId:AJ.optional(),maxTokens:y.number().int().positive().optional(),contextWindow:y.number().int().positive().optional(),baseUrl:y.string().url().optional(),headers:y.record(y.string(),y.string()).optional(),timeout:y.number().int().positive().optional(),reasoning:v6.optional(),aws:u6.optional(),gcp:c6.optional(),azure:d6.optional(),sap:l6.optional(),oca:p6.optional(),region:y.string().optional(),apiLine:y.enum(["china","international"]).optional(),capabilities:y.array(y.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:r6.optional()});function i6($){return B1.parse($)}function n6($){return B1.safeParse($)}function uO($){return $.protocol==="openai-responses"||$.client==="openai"}function v0($,f={}){let J=$.provider,W=K2(J),Z=f.includeKnownModels!==!1,Q=$.reasoning?.effort||"none",j=Q==="none"?void 0:Q,H=jJ[W],X=Object.assign({},...g0.resolveProviderModelCatalogKeys(W).map((R)=>g0.getGeneratedModelsForProvider(R))),A=Object.keys(X)[0],Y=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,V=$.baseUrl??(W==="oca"?$.oca?.mode==="internal"?_6:T6:H?.baseUrl),B=$.routingProviderId??(uO($)&&W!==XJ.OPENAI_NATIVE?XJ.OPENAI_NATIVE:void 0),K=Z?H?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??H?.modelId??A??"default",...Z?{knownModels:K}:{},apiKey:Y,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:V,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??H?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,P])=>P!==void 0))}function P9($){let f=i6($);return v0(f)}function U9($){let f=n6($);if(f.success)return{success:!0,config:v0(f.data)};return{success:!1,error:f.error}}var YJ=B1;var a6=K1.object({settings:B1,updatedAt:K1.string().datetime(),tokenSource:K1.enum(["manual","oauth","migration"]).default("manual")}),G2=K1.object({version:K1.literal(1),lastUsedProvider:K1.string().min(1).optional(),providers:K1.record(K1.string(),a6)});function G1(){return{version:1,providers:{}}}Z$();var JA={};w(JA,{InMemoryWorkspaceManager:()=>P2});import{upsertWorkspaceInfo as cO,WorkspaceManifestSchema as F9}from"@cline/shared";class P2{manifest;listeners=new Set;constructor($){this.manifest=F9.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await yf($);return this.manifest=cO(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=L$($),J=this.manifest.workspaces[f];if(J)return this.manifest=F9.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath(f);return this.manifest=F9.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=L$($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}L0();import{createHash as dO}from"node:crypto";var WA=new Set,ZA=new Set;function lO($){return dO("sha256").update($).digest("hex")}function pO($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function QA($){if(!$.telemetry)return;let f=lO($.rootPath),J=$.rootCount??1;if(!WA.has(f))WA.add(f),P4($.telemetry,{root_count:J,vcs_types:pO($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!ZA.has(f)){ZA.add(f);let W=Error($.initError.message);W.name=$.initError.errorType||"Error",U4($.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function iO($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function nO($,f,J){if(f.length>0)for(let Q of f)J?.log(Q.message,{severity:"warn"});if($.length===0)return;let W=$.slice(0,3).map(iO).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let Q of $)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function aO($,f){let J=typeof $.thinking==="boolean",W=typeof $.reasoningEffort==="string";if(!J&&!W)return f;return{...f??{},...J?{enabled:$.thinking}:{},...W?{effort:$.reasoningEffort}:{}}}function jA($,f){return rO($,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 sO($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||oO($.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 oO($){let f=$?.trim();if(!f)return;let J=_0(f),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function eO($,f,J,W,Z){let Q=J.getProviderSettings($.providerId),j=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,H={...Q??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Q?.apiKey,baseUrl:$.baseUrl??Q?.baseUrl,headers:$.providerId==="openai-codex"?sO({sessionId:f,configHeaders:$.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:$.apiKey??Q?.auth?.accessToken??Q?.apiKey}):$.headers??Q?.headers,reasoning:aO($,Q?.reasoning),modelCatalog:j},X=v0(H);if($.knownModels)X.knownModels=$.knownModels;if($.extensionContext)X.extensionContext=$.extensionContext;let Y=$.fetch??X.fetch??Z;if(Y)X.fetch=Y;return X}async function HA($){let{input:f,sessionId:J,providerSettingsManager:W,defaultTelemetry:Z,defaultCapabilities:Q,defaultToolPolicies:j,defaultFetch:H,onPluginEvent:X,onTeamEvent:A,createSpawnTool:Y,localRuntime:V,readSessionMetadata:B,writeSessionMetadata:K}=$,G=H1(f.config),{modelCatalogDefaults:R,userInstructionService:P,configExtensions:U,onTeamRestored:F,...z}=V??{},_=Object.keys(z).length>0?z:void 0,{workspaceInfo:D,workspaceMetadata:O,durationMs:N,vcsType:q,initError:$0}=await GW(G),A0=_?.extensionContext,o={...A0??{},workspace:{...D,...A0?.workspace??{}},session:{...A0?.session??{},sessionId:J},logger:A0?.logger??_?.logger,telemetry:A0?.telemetry??_?.telemetry??Z};QA({telemetry:o.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:q,durationMs:N,initError:$0,featureFlagEnabled:!0});let Y0=Y2({cwd:f.config.cwd,workspacePath:G,rootSessionId:J,logger:_?.logger,workspaceInfo:D}),i=cH(_?.hooks)?void 0:A2({rootSessionId:J,workspacePath:G,workspaceInfo:D}),J$=Wf([_?.hooks,i]),p;if(jA(U,"plugins"))try{p=await j2({pluginPaths:_?.pluginPaths,workspacePath:G,cwd:f.config.cwd,onEvent:X,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:D,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),nO(p.failures,p.warnings,_?.logger)}catch(l2){let r=l2 instanceof Error?l2.message:String(l2);_?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let k=hZ(Y0?[Y0]:void 0,hZ(_?.extensions,I4(p?.extensions))),D0=jA(U,"plugins")?e1(p?.pluginPaths??[]):void 0,n={...f.config,..._??{},sessionId:J,hooks:J$,extensions:k,extensionContext:o,telemetry:o.telemetry},a0=eO(n,J,W,R,H),T1=Wf([n.hooks,n.checkpoint?.enabled===!0?OX({cwd:n.cwd,sessionId:J,logger:n.logger,createCheckpoint:n.checkpoint?.createCheckpoint,initialRunCount:tO(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:K}):void 0]),N1={...n,providerConfig:a0,workspaceMetadata:O,hooks:T1},zf=f.toolPolicies??n.toolPolicies??j,d2=R0(Q,f.capabilities),X4=d2?.requestToolApproval,YW=d2?.toolExecutors,_f=new P2({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:f,config:N1,providerConfig:a0,workspaceMetadata:O,workspaceInfo:D,extensions:k,hooks:T1,toolPolicies:zf,requestToolApproval:X4,pluginSandboxShutdown:p?.shutdown,runtimeBuilderInput:{config:N1,hooks:T1,extensions:k,onTeamEvent:A,createSpawnTool:Y,onTeamRestored:F,userInstructionService:P,pluginSkillDirectories:D0,configExtensions:U,toolExecutors:YW,workspaceManager:_f,logger:N1.logger,telemetry:N1.telemetry}}}import{existsSync as s6,mkdirSync as $z,readdirSync as fz,rmdirSync as Jz,rmSync as Wz,unlinkSync as Zz}from"node:fs";import{dirname as XA,join as t6}from"node:path";function s(){return new Date().toISOString()}function VJ($){if(!$||!s6($))return;try{Zz($)}catch{}}function Qz($){let f=tf($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=v8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class R9{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return t6(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!s6(f))$z(f,{recursive:!0});return f}sessionMessagesPath($){return t6(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return t6(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!s6(f)){f=XA(f);continue}try{if(fz(f).length>0)break;Jz(f)}catch{break}f=XA(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!s6($))return;try{Wz($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:W,fileStem:Z}=Qz($),Q=this.sessionArtifactsDir(W);return{messagesPath:t6(Q,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as jz}from"@cline/shared/storage";L0();function AA($,f,J,W,Z){if(J)R4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else F4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});Hz($.telemetry,{workspacePath:W})}function Hz($,f){let J=jz("Hooks"),W=A1(f.workspacePath),Z=new Map;for(let Q of W){let j=Q.hookEventName??"unknown",H=Z.get(j)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))H.global+=1;else H.workspace+=1;Z.set(j,H)}for(let[Q,j]of Z.entries())q4($,Q,j.global,j.workspace)}function YA($,f){for(let J of f.mentions)M4($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)T4($,"file",J.length);for(let J of f.ignoredMentions)N4($,"file","not_found",J)}var _B={};w(_B,{ProviderSettingsManager:()=>R$});import{chmodSync as wB,existsSync as P7,mkdirSync as Kw,readFileSync as Gw,writeFileSync as Pw}from"node:fs";import{basename as SB,dirname as U7}from"node:path";import{resolveProviderSettingsPath as Uw}from"@cline/shared/storage";var T={};w(T,{writeHubDiscovery:()=>v4,writeGlobalSettings:()=>N$,withHubStartupLock:()=>u4,verifyHubConnection:()=>H$,updateMcpServerOAuthState:()=>Af,updateLocalProvider:()=>p5,uninstallPlugin:()=>mQ,truncateNotificationBody:()=>f4,toggleDisabledTool:()=>b4,toTeamProgressLifecycleEvent:()=>q2,toProviderConfig:()=>v0,toHubHealthUrl:()=>CW,toHookConfigFileName:()=>$J,summarizeUsageFromMessages:()=>of,stopLocalHubServerGracefully:()=>lW,startLocalOAuthServer:()=>$$,startHubWebSocketServer:()=>Z4,startHubServer:()=>MB,startClineDeviceAuth:()=>T9,splitCoreSessionConfig:()=>X8,spawnDetachedHubServerWithRetry:()=>kf,spawnDetachedHubServer:()=>mW,setTelemetryOptOutGlobally:()=>P3,setMcpServerDisabled:()=>Hf,setDisabledTools:()=>NW,setDisabledPlugin:()=>O3,setAutoUpdateEnabledGlobally:()=>F3,sendHubCommand:()=>n3,saveLocalProviderSettings:()=>rQ,saveLocalProviderOAuthCredentials:()=>tQ,sanitizeSessionToken:()=>r1,safeParseSettings:()=>n6,safeCreateProviderConfig:()=>U9,runSubprocessEvent:()=>C2,runHook:()=>b2,reviveTeamStateDates:()=>Z6,restartLocalHubIfIdleAfterStartupTimeout:()=>l4,resolveWorkspaceHubOwnerContext:()=>I3,resolveWorkflowsConfigSearchPaths:()=>yJ,resolveSkillsConfigSearchPaths:()=>NJ,resolveSharedHubOwnerContext:()=>G0,resolveSessionBackend:()=>DQ,resolveRulesConfigSearchPaths:()=>MJ,resolveProviderConfig:()=>HJ,resolvePluginSkillDirectoriesFromPaths:()=>e1,resolvePluginConfigSearchPaths:()=>t8,resolveMcpServerRegistrations:()=>Y$,resolveLocalClineAuthToken:()=>sQ,resolveHubUrl:()=>pW,resolveHubOwnerContext:()=>w$,resolveHubEndpointOptions:()=>j$,resolveHubBuildId:()=>t$,resolveHooksConfigSearchPaths:()=>o8,resolveDisabledToolNames:()=>W$,resolveDisabledPluginPaths:()=>W8,resolveDefaultMcpSettingsPath:()=>T0,resolveDefaultHubPort:()=>bf,resolveDefaultHubPathname:()=>xW,resolveDefaultHubHost:()=>IW,resolveCoreSelectedToolIds:()=>j6,resolveCompatibleLocalHubUrl:()=>G8,resolveClineDir:()=>C3,resolveClineDataDir:()=>Y8,resolveAndLoadAgentPlugins:()=>j2,resolveAgentPluginPaths:()=>o1,requestHubShutdown:()=>K8,requestDesktopToolApproval:()=>SQ,rememberRecoverableLocalHubUrl:()=>s$,registerRemoteConfigSessionBlobUpload:()=>b5,registerMcpServersFromSettingsFile:()=>Yf,registerDisposable:()=>Aw,refreshProviderModelsFromSource:()=>iQ,refreshOpenAICodexToken:()=>FJ,refreshOcaToken:()=>WJ,refreshClineToken:()=>PJ,readSessionCheckpointHistory:()=>eJ,readRemoteConfigSessionBlobUploadMetadata:()=>OQ,readHubDiscovery:()=>V0,readGlobalSettings:()=>O0,probeHubServer:()=>Q$,probeHubConnection:()=>i3,prewarmFileIndex:()=>s4,prewarmDetachedHubServer:()=>c4,prepareRemoteConfigCoreIntegration:()=>_Q,parseWorkflowConfigFromMarkdown:()=>TJ,parseUserCommandEnvelope:()=>Xw,parseSkillConfigFromMarkdown:()=>zJ,parseSettings:()=>i6,parseRuleConfigFromMarkdown:()=>_J,parseHookEventPayload:()=>E2,openaiCodexOAuthProvider:()=>w9,normalizeWorkspacePath:()=>L$,normalizeUserInput:()=>Hw,normalizeSdkError:()=>jw,normalizeRuntimeCapabilities:()=>R0,normalizeProviderId:()=>K2,normalizeOpenAICodexCredentials:()=>q9,normalizeOAuthProvider:()=>nQ,normalizeHubWebSocketUrl:()=>o$,noopBasicLogger:()=>Qw,migrateLegacyProviderSettings:()=>oJ,mergeRulesForSystemPrompt:()=>Mf,mergeAgentHooks:()=>Wf,makeTeamTaskSubSessionId:()=>g8,makeSubSessionId:()=>af,loginOpenAICodex:()=>R2,loginOcaOAuth:()=>V2,loginLocalProvider:()=>aQ,loginClineOAuth:()=>F2,loadOpenTelemetryAdapter:()=>iq,loadMcpSettingsFile:()=>jf,loadLlmsConfigFromFile:()=>B7,loadAgentPluginsFromPathsWithDiagnostics:()=>s1,loadAgentPluginsFromPaths:()=>K6,loadAgentPluginFromPath:()=>n8,listSessionHistoryFromBackend:()=>$Q,listPluginToolsWithDiagnostics:()=>F5,listPluginTools:()=>IJ,listMcpServerOAuthStatuses:()=>bJ,listLocalProviders:()=>lQ,listHookConfigFiles:()=>A1,isToolDisabledGlobally:()=>R3,isTelemetryOptedOutGlobally:()=>E4,isSessionNotFoundError:()=>q$,isRuleEnabled:()=>A4,isPluginDisabledGlobally:()=>L3,isOpenAICodexTokenExpired:()=>y9,isHubReconnectableTransportError:()=>cW,isHubCommandTimeoutError:()=>d4,isDiscoveryFilePresent:()=>b3,isClineAccountActionRequest:()=>o6,isBuiltInProviderId:()=>G9,isAutoUpdateEnabledGlobally:()=>U3,identifyAccount:()=>T$,hasMcpSettingsFile:()=>m$,getValidOpenAICodexCredentials:()=>RJ,getValidOcaCredentials:()=>ZJ,getValidClineCredentials:()=>UJ,getProviderConfigFields:()=>oQ,getProviderConfig:()=>I6,getMcpServerOAuthState:()=>Xf,getLocalProviderModels:()=>pQ,getLiveModelsCatalog:()=>B2,getFileIndex:()=>E$,getCurrentContextSize:()=>kZ,getCoreHeadlessToolNames:()=>m8,getCoreDefaultEnabledToolIds:()=>Q6,getCoreBuiltinToolCatalog:()=>l1,getCoreAcpToolNames:()=>H6,getClineDefaultSystemPrompt:()=>aq,generateWorkspaceInfoWithDiagnostics:()=>r2,generateWorkspaceInfo:()=>yf,generateOcaOpcRequestId:()=>M6,formatRulesForSystemPrompt:()=>Nf,formatDisplayUserInput:()=>Zw,filterExtensionToolRegistrations:()=>I4,filterDisabledTools:()=>S1,filterDisabledPluginPaths:()=>k4,fetchClineRecommendedModels:()=>Y7,executeClineAccountAction:()=>e6,ensureHubWebSocketServer:()=>WW,ensureHubServer:()=>yB,ensureDetachedHubServer:()=>m3,ensureCustomProvidersLoaded:()=>c5,ensureCompatibleLocalHubUrl:()=>b1,enrichPromptWithMentions:()=>gf,emptyWorkspaceManifest:()=>Ww,emptyStoredProviderSettings:()=>G1,discoverPluginModulePaths:()=>s8,deriveSubsessionStatus:()=>u8,deleteLocalProvider:()=>r5,defineLlmsConfig:()=>V7,createWorkflowsConfigDefinition:()=>SJ,createUserInstructionConfigService:()=>U1,createToolPoliciesWithPreset:()=>e4,createTool:()=>Jw,createTeamName:()=>I5,createSubprocessHooks:()=>h5,createSpawnAgentTool:()=>Q1,createSkillsConfigDefinition:()=>qJ,createSessionHost:()=>h2,createRuntimeHost:()=>h2,createRulesConfigDefinition:()=>wJ,createRemoteConfigSessionMessagesArtifactUploader:()=>zQ,createProviderConfig:()=>P9,createOpenTelemetryTelemetryService:()=>H8,createOcaRequestHeaders:()=>j9,createOcaOAuthProvider:()=>Q9,createOAuthClientCallbacks:()=>GJ,createMcpTools:()=>_2,createLocalHubScheduleRuntimeHandlers:()=>NB,createLlmsSdk:()=>G7,createInitialAccumulatedUsage:()=>B0,createInMemoryHubOwnerContext:()=>E3,createHubServerUrl:()=>t0,createHubAuthToken:()=>g4,createHookConfigFileHooks:()=>fJ,createHookConfigFileExtension:()=>Y2,createHookAuditHooks:()=>A2,createDisabledMcpToolPolicy:()=>kJ,createDisabledMcpToolPolicies:()=>U5,createDelegatedAgentConfigProvider:()=>lf,createDelegatedAgent:()=>pf,createDefaultToolsWithPreset:()=>$6,createDefaultTools:()=>J1,createDefaultMcpServerClientFactory:()=>z2,createDefaultExecutors:()=>vf,createCoreSettingsService:()=>Bf,createCoreSessionSnapshot:()=>B$,createContributionRegistry:()=>fw,createContextCompactionPrepareTurn:()=>L8,createConfiguredTelemetryService:()=>M$,createConfiguredTelemetryHandle:()=>Ef,createClineTelemetryServiceMetadata:()=>$w,createClineTelemetryServiceConfig:()=>eq,createClineOAuthProvider:()=>M9,createBuiltinTools:()=>p1,createAgentTeamsTools:()=>d1,createAgentRuntime:()=>Bw,createAgentHooksExtension:()=>H2,connectToHub:()=>p4,completeClineDeviceAuth:()=>N9,clearPrivateModelsCatalogCache:()=>B9,clearLiveModelsCatalogCache:()=>V9,clearHubDiscovery:()=>b0,captureWorkspacePathResolved:()=>A3,captureWorkspaceInitialized:()=>P4,captureWorkspaceInitError:()=>U4,captureToolUsage:()=>O4,captureTokenUsage:()=>D4,captureTaskRestarted:()=>R4,captureTaskCreated:()=>F4,captureTaskCompleted:()=>e2,captureSubagentExecution:()=>f8,captureSkillUsed:()=>z4,captureSdkError:()=>oq,captureProviderConfigured:()=>Y3,captureProviderApiError:()=>$8,captureModeSwitch:()=>L4,captureMentionUsed:()=>T4,captureMentionSearchResults:()=>M4,captureMentionFailed:()=>N4,captureHookDiscovery:()=>q4,captureExtensionActivated:()=>X3,captureDiffEditFailure:()=>_4,captureConversationTurnEvent:()=>wf,captureCompactionSkipped:()=>S4,captureCompactionExecuted:()=>w4,captureAuthSucceeded:()=>z$,captureAuthStarted:()=>O$,captureAuthLoggedOut:()=>n$,captureAuthFailed:()=>_$,captureAgentTeamCreated:()=>y4,captureAgentCreated:()=>a$,buildWorkspaceMetadata:()=>i2,buildTeamProgressSummary:()=>y2,buildSdkErrorProperties:()=>tq,buildRemoteConfigSessionBlobUploadMetadata:()=>C5,buildDelegatedAgentConfig:()=>u1,bootstrapAgentTeams:()=>nf,authorizeMcpServerOAuth:()=>K5,addLocalProvider:()=>dQ,accumulateUsageTotals:()=>H0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>OJ,UnifiedConfigFileWatcher:()=>Qf,ToolPresets:()=>m0,TelemetryService:()=>hf,TelemetryLoggerSink:()=>j8,TEAM_TOOL_NAMES:()=>rf,SubprocessSandbox:()=>Z2,StoredProviderSettingsSchema:()=>G2,StoredProviderSettingsEntrySchema:()=>a6,SqliteTeamStore:()=>Ff,SqliteSessionStore:()=>G$,SessionVersioningService:()=>z1,SessionVersioningError:()=>S0,SessionSource:()=>P0,SessionNotFoundError:()=>y$,SapSettingsSchema:()=>l6,SKILLS_CONFIG_DIRECTORY_NAME:()=>LJ,SESSION_STATUSES:()=>c8,SESSION_NOT_FOUND_ERROR_CODE:()=>C1,SDK_ERROR_TELEMETRY_EVENT:()=>Yw,RpcClineAccountService:()=>KJ,RemoteRuntimeHost:()=>M2,ReasoningSettingsSchema:()=>v6,RULES_CONFIG_DIRECTORY_NAME:()=>X5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>E5,ProviderSettingsSchema:()=>B1,ProviderSettingsManager:()=>R$,ProviderProtocolSchema:()=>x6,ProviderIdSchema:()=>AJ,ProviderClientSchema:()=>m6,OpenTelemetryProvider:()=>Cf,OcaSettingsSchema:()=>p6,OPENAI_COMPATIBLE_PROVIDERS:()=>jJ,NodeHubClient:()=>s0,NativeHubTransportAdapter:()=>W4,ModelCatalogSettingsSchema:()=>r6,LocalRuntimeHost:()=>F$,Llms:()=>nq,InMemoryWorkspaceManager:()=>P2,InMemoryMcpManager:()=>Vf,HubUIClient:()=>nW,HubTransportError:()=>z0,HubSessionClient:()=>iW,HubServerTransport:()=>c2,HubScheduleService:()=>qf,HubScheduleCommandService:()=>Tf,HubRuntimeHost:()=>g$,HubCommandError:()=>If,HookEventPayloadSchema:()=>S5,HookEventNameSchema:()=>w5,HookConfigFileName:()=>X2,HOOK_CONFIG_FILE_EVENT_MAP:()=>e8,HOOKS_CONFIG_DIRECTORY_NAME:()=>L6,GlobalSettingsSchema:()=>J8,GcpSettingsSchema:()=>c6,FileTeamPersistenceStore:()=>t5,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW,DefaultToolNames:()=>J0,DefaultRuntimeBuilder:()=>x2,DefaultLlmsSdk:()=>$4,DEFAULT_MODELS_CATALOG_URL:()=>C6,DEFAULT_HUB_PORT:()=>bW,DEFAULT_HUB_PATHNAME:()=>kW,DEFAULT_HUB_HOST:()=>EW,CoreSettingsService:()=>F1,CoreSessionService:()=>U$,ContributionRegistry:()=>sq,ClineCore:()=>aJ,ClineAccountService:()=>BJ,ChatViewStateSchema:()=>X7,ChatSummarySchema:()=>fW,ChatSessionStatusSchema:()=>o5,ChatSessionConfigSchema:()=>s5,ChatMessageSchema:()=>$W,ChatMessageRoleSchema:()=>e5,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>A7,BrowserWebSocketHubAdapter:()=>J4,BUILT_IN_PROVIDER_IDS:()=>K9,BUILT_IN_PROVIDER:()=>XJ,AzureSettingsSchema:()=>d6,AwsSettingsSchema:()=>u6,AuthSettingsSchema:()=>g6,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>S2,Agent:()=>Vw,ALL_DEFAULT_TOOL_NAMES:()=>p$});M(T,hc);import*as nq from"@cline/llms";import{buildClineSystemPrompt as aq,buildSdkErrorProperties as tq,ContributionRegistry as sq,captureSdkError as oq,createClineTelemetryServiceConfig as eq,createClineTelemetryServiceMetadata as $w,createContributionRegistry as fw,createTool as Jw,emptyWorkspaceManifest as Ww,formatDisplayUserInput as Zw,noopBasicLogger as Qw,normalizeSdkError as jw,normalizeUserInput as Hw,parseUserCommandEnvelope as Xw,registerDisposable as Aw,SDK_ERROR_TELEMETRY_EVENT as Yw}from"@cline/shared";import"@cline/shared/storage";var BA={};w(BA,{isClineAccountActionRequest:()=>o6,executeClineAccountAction:()=>e6,RpcClineAccountService:()=>KJ,ClineAccountService:()=>BJ});function Xz($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function VA($,f,J){let W=Xz(J);if(W)return W;let Z=f.trim();if(Z){let Q=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${Q}`}return`Cline account request failed with status ${$}`}class BJ{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((H)=>H.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,Q=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let H=await j.text(),X;if(H.trim())try{X=JSON.parse(H)}catch{if(!j.ok)throw Error(VA(j.status,H,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(VA(j.status,H,X));if(typeof X==="object"&&X!==null){let A=X;if(typeof A.success==="boolean"){if(!A.success)throw Error(A.error||"Cline account request failed");if(A.data!==void 0)return A.data}}if(X===void 0||X===null)throw Error("Cline account response payload was empty");return X}finally{clearTimeout(Q)}}}function o6($){return $.action==="clineAccount"}async function e6($,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 KJ{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 KA={};w(KA,{createOAuthClientCallbacks:()=>GJ});function GJ($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((W)=>{$.onOpenUrlError?.({url:f,error:W})})}catch(W){$.onOpenUrlError?.({url:f,error:W})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}L0();var OA={};w(OA,{startClineDeviceAuth:()=>T9,refreshClineToken:()=>PJ,loginClineOAuth:()=>F2,getValidClineCredentials:()=>UJ,createClineOAuthProvider:()=>M9,completeClineDeviceAuth:()=>N9});import{getClineEnvironmentConfig as D9}from"@cline/shared";var $5={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},FA={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},L9="https://api.workos.com",Az="/auth",GA=Array.from({length:11},($,f)=>48801+f),Yz=300000,Vz=30000,U2=30000,Bz=300,Kz=5;class P1 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 Gz($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function O9($,f,J={}){let W=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:Gz($.expiresAt),accountId:W??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function z9($){if(!$)return{};return typeof $==="function"?await $():$}function PA($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function UA($){await new Promise((f)=>setTimeout(f,$))}function _9($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function RA($,f){let J=await fetch(n1(L9,FA.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??U2)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new P1(`Device authorization failed: ${J.status}${W.error_description?` - ${W.error_description}`:""}`,{status:J.status,errorCode:W.error});if(!W.device_code||!W.user_code||!W.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:W.device_code,userCode:W.user_code,verificationUri:W.verification_uri,verificationUriComplete:W.verification_uri_complete,expiresInSeconds:PA(W.expires_in,Bz),pollIntervalSeconds:PA(W.interval,Kz)}}async function DA($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let W=await fetch(n1($.workosApiBaseUrl,FA.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await W.json().catch(()=>({}));if(W.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await UA(J*1000);break}case"slow_down":{J+=1,await UA(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new P1(Z.error_description||"WorkOS authorization failed",{status:W.status,errorCode:Z.error});default:throw new P1(`WorkOS token polling failed: ${W.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:W.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function LA($,f,J){let W={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(n1(f.apiBaseUrl,$5.register),{method:"POST",headers:{"Content-Type":"application/json",...await z9(f.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(f.requestTimeoutMs??U2)});if(!Z.ok){let j=await Z.text().catch(()=>""),H=$2(j);throw new P1(`Token registration failed: ${Z.status}${H.message?` - ${H.message}`:""}`,{status:Z.status,errorCode:H.code})}let Q=await Z.json();return O9(_9(Q,"Invalid token exchange response"),J??f.provider)}async function Pz($,f,J,W){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:W??J.provider},Q=await fetch(n1(J.apiBaseUrl,$5.token),{method:"POST",headers:{"Content-Type":"application/json",...await z9(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??U2)});if(!Q.ok){let H=await Q.text().catch(()=>""),X=$2(H);throw new P1(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let j=await Q.json();return O9(_9(j,"Invalid token exchange response"),W??J.provider)}async function F2($){O$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:GA,W=$.callbackPath??Az,Z=f?null:await $$({ports:J,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Q=Z?.callbackUrl||`http://127.0.0.1:${J[0]??GA[0]}${W}`;try{let j;if(f){let H=D9().workOsClientId,X=await RA(H,$);$.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await DA({clientId:H,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??U2,workosApiBaseUrl:L9,onProgress:$.callbacks.onProgress});j=await LA(A,$,$.provider)}else{let H=new URL(n1($.apiBaseUrl,$5.authorize));H.searchParams.set("client_type","extension"),H.searchParams.set("callback_url",Q),H.searchParams.set("redirect_uri",Q),$.callbacks.onAuth({url:H.toString(),instructions:"Continue the authentication process in your browser."});let X,A=$.provider,Y=await f2({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(Y.error)throw Error(`OAuth error: ${Y.error}`);if(X=Y.code,A=Y.provider??A,!X){let V=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=ef(V,{includeProvider:!0});X=B.code,A=B.provider??A}if(!X)throw Error("Missing authorization code");j=await Pz(X,Q,$,A)}return z$($.telemetry,$.provider??"cline"),T$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw _$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function T9($){return await RA(D9().workOsClientId,$)}async function N9($){let f=$.provider??"cline";O$($.telemetry,f);try{let J=await DA({clientId:D9().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??U2,workosApiBaseUrl:L9}),W=await LA(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return z$($.telemetry,f),T$($.telemetry,{id:W.accountId,email:W.email,provider:f}),W}catch(J){throw _$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function PJ($,f){let J=await fetch(n1(f.apiBaseUrl,$5.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await z9(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??U2)});if(!J.ok){let Q=await J.text().catch(()=>""),j=$2(Q);throw new P1(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let W=await J.json(),Z=$.metadata?.provider??f.provider;return O9(_9(W,"Invalid token refresh response"),Z,$)}async function UJ($,f,J){if(!$)return null;let W=J?.refreshBufferMs??Yz,Z=J?.retryableTokenGraceMs??Vz;if(J?.forceRefresh!==!0&&!a1($,W))return $;try{return await PJ($,f)}catch(j){if(j instanceof P1&&j.isLikelyInvalidGrant())return n$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function M9($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return F2({...$,callbacks:f})},async refreshToken(f){return PJ(f,$)},getApiKey(f){return`workos:${f.access}`}}}L0();var TA={};w(TA,{refreshOpenAICodexToken:()=>FJ,openaiCodexOAuthProvider:()=>w9,normalizeOpenAICodexCredentials:()=>q9,loginOpenAICodex:()=>R2,isOpenAICodexTokenExpired:()=>y9,getValidOpenAICodexCredentials:()=>RJ,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as Uz}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 f5 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 Fz($,f,J=e.redirectUri){let W=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(!W.ok)return{type:"failed"};let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function Rz($){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 W=await f.text().catch(()=>""),Z=$2(W);throw new f5(`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 f5)throw f;return{type:"failed"}}}async function Dz($="pi"){let{verifier:f,challenge:J}=await Y6(),W=Uz(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",W),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:W,url:Z.toString()}}function Lz(){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 zA($,f){let J=f?_0(f):_0($),W=J?J:_0($),Q=W?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let j=W?.organizations;if(Array.isArray(j)&&j.length>0){let X=j[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let H=W?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;return null}function _A($,f){let J=zA($.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 R2($){O$($.telemetry,"openai-codex");let f=Lz(),{verifier:J,state:W,url:Z}=await Dz($.originator),Q=await $$({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:W});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let H=await f2({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(H.state&&H.state!==W)throw Error("State mismatch");if(j=H.code,!j){let Y=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=ef(Y,{allowHashCodeState:!0});if(V.state&&V.state!==W)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let X=await Fz(j,J,f.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=_A(X);return z$($.telemetry,"openai-codex"),T$($.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(H){throw _$($.telemetry,"openai-codex",H instanceof Error?H.message:String(H)),H}finally{Q.close()}}async function FJ($,f){let J=await Rz($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=_A(J,f);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function RJ($,f){if(!$)return null;let J=f?.refreshBufferMs??e.refreshBufferMs,W=f?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!a1($,J))return $;try{return await FJ($.refresh,$)}catch(Q){if(Q instanceof f5&&Q.isLikelyInvalidGrant())return n$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}function y9($,f=e.refreshBufferMs){return a1($,f)}function q9($){let f=$.accountId??zA($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var w9={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return R2({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return FJ($.refresh,$)},getApiKey($){return $.access}};var PV={};w(PV,{ClineCore:()=>aJ});function NA($){if($===!0)return{};if(!$)return;return $}function MA($){if($==="user")return"global";return $}class S9{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 yA($){let{host:f}=$;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||P0.CLI,interactive:!1,config:{providerId:K2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:_z(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:zz(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 J5($){let f=Oz($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),W=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,Q=$.context?.telemetry??$.telemetry;if(!f&&!J&&!W&&!Z&&!Q)return $.context;return{...$.context??{},...J?{client:J}:{},...W?{user:W}:{},...Z?{logger:Z}:{},...Q?{telemetry:Q}:{},...f?{automation:f}:{}}}function Oz($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function zz($){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 _z($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var KY={};w(KY,{createCoreSettingsService:()=>Bf,CoreSettingsService:()=>F1});import{existsSync as R5}from"node:fs";import{basename as YY,isAbsolute as p_,relative as r_}from"node:path";var vA={};w(vA,{resolveWorkflowsConfigSearchPaths:()=>yJ,resolveSkillsConfigSearchPaths:()=>NJ,resolveRulesConfigSearchPaths:()=>MJ,parseWorkflowConfigFromMarkdown:()=>TJ,parseSkillConfigFromMarkdown:()=>zJ,parseRuleConfigFromMarkdown:()=>_J,createWorkflowsConfigDefinition:()=>SJ,createUserInstructionConfigService:()=>U1,createSkillsConfigDefinition:()=>qJ,createRulesConfigDefinition:()=>wJ,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>OJ,UnifiedConfigFileWatcher:()=>Qf,SKILLS_CONFIG_DIRECTORY_NAME:()=>LJ,RULES_CONFIG_DIRECTORY_NAME:()=>X5});import{createHash as Tz}from"node:crypto";import{watch as Nz}from"node:fs";import{readdir as Mz,readFile as yz}from"node:fs/promises";import{join as qz}from"node:path";function wz($){return Tz("sha1").update($).digest("hex")}function SA($){return Boolean($&&typeof $==="object"&&"code"in $)}function qA($){return SA($)&&$.code==="ENOENT"}function wA($){return SA($)&&($.code==="EACCES"||$.code==="EPERM")}class Qf{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let Z=this.baseTypesByDirectory.get(W);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([W,Z])=>[W,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=Nz(f,()=>{let W=this.watchedTypesByDirectory.get(f);if(!W)return;for(let Z of W)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(W)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let Q of Z)this.emit({kind:"error",type:Q,error:W,filePath:f})})}catch(J){if(!qA(J)&&!wA(J)){let W=$.get(f);if(!W)continue;for(let Z of W)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),W=this.recordsByType.get($.type)??new Map;for(let[Z,Q]of W.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:Q.filePath})}for(let[Z,Q]of f.entries()){let j=W.get(Z);if(j&&j.filePath===Q.filePath&&j.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:Z,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let W of $.directories){J.add(W);let Z=$.discoverFiles?await $.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of Z){let{fileName:j,filePath:H}=Q;if(J.add(Q.directoryPath),$.includeFile&&!$.includeFile(j,H))continue;try{let X=await yz(H,"utf8"),A={type:$.type,directoryPath:Q.directoryPath,fileName:j,filePath:H,content:X},Y=$.parseFile(A),V=$.resolveId(Y,A).trim();if(!V)continue;f.set(V,{type:$.type,id:V,item:Y,filePath:H,fingerprint:wz(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:X,filePath:H})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let Z=$.get(W);if(Z)Z.add(f);else $.set(W,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await Mz($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:qz($,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch(f){if(qA(f)||wA(f))return[];throw f}}}import{readdir as C9,readFile as Sz,stat as h9}from"node:fs/promises";import{basename as x$,dirname as hz,extname as Z5,join as q0,resolve as DJ}from"node:path";import{AGENTS_RULES_FILE_NAME as hA,RULES_CONFIG_DIRECTORY_NAME as X5,resolveGlobalAgentsRulesPath as Cz,resolveRulesConfigSearchPaths as Ez,resolveSkillsConfigSearchPaths as bz,resolveWorkflowsConfigSearchPaths as kz,SKILLS_CONFIG_DIRECTORY_NAME as LJ,WORKFLOWS_CONFIG_DIRECTORY_NAME as OJ}from"@cline/shared/storage";import Iz from"yaml";var W5="SKILL.md",xz="managed.json",mz=new Set([".md",".markdown",".txt"]);function E9($){return $.trim().toLowerCase()}function D2($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"||f?.code==="ELOOP"}function Q5($){return mz.has(Z5($).toLowerCase())}function CA($){let f=[],J=new Set;for(let W of $){let Z=DJ(W);if(J.has(Z))continue;J.add(Z),f.push(W)}return f}function gz($){let f=[...$?.directories??NJ($?.workspacePath)];if($?.pluginSkillDirectories)f.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)f.push(...DX({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return CA(f)}async function b9($){try{let f=await C9($,{withFileTypes:!0}),J=[];for(let W of f){if(!W.isDirectory())continue;let Z=q0($,W.name),Q=q0(Z,xz);try{let j=await Sz(Q,"utf8"),H=JSON.parse(j);if(H&&typeof H==="object")J.push(Z)}catch(j){if(D2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((W,Z)=>W.localeCompare(Z))}catch(f){if(D2(f))return[];throw f}}function k9($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J;try{let Q=Iz.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}catch(Q){let j=Q instanceof Error?Q.message:String(Q);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function j5($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let W=$.trim();if(!W&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return W||void 0}function L2($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function vz($,f){if(x$($.filePath).toLowerCase()!==hA.toLowerCase())return x$($.filePath,Z5($.filePath));if(f&&DJ($.filePath)===DJ(f,hA))return"Workspace AGENTS.md";if(DJ($.filePath)===DJ(Cz()))return"Global AGENTS.md";return x$($.filePath,Z5($.filePath))}function zJ($,f){let{data:J,body:W,parseError:Z}=k9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let H=j5(J.name,"name",!1)??f.trim();if(!H)throw Error("Missing skill name.");return{name:H,description:j5(J.description,"description",!1),disabled:L2(J.disabled,"disabled")??(L2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function _J($,f){let{data:J,body:W,parseError:Z}=k9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let j=j5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:L2(J.disabled,"disabled")??(L2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function TJ($,f){let{data:J,body:W,parseError:Z}=k9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let j=j5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:L2(J.disabled,"disabled")??(L2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function NJ($){return bz($)}function MJ($){return Ez($)}function yJ($){return kz($)}async function EA($){if(x$($)===".cline"){let f=await b9($);return(await Promise.all(f.map((W)=>EA(q0(W,LJ))))).flat()}try{let f=await C9($,{withFileTypes:!0}),J=[];for(let W of f){if(W.isFile()&&W.name===W5){J.push({directoryPath:$,fileName:W.name,filePath:q0($,W.name)});continue}let Z=q0($,W.name);if(W.isDirectory()||W.isSymbolicLink()&&await h9(Z).then((j)=>j.isDirectory()).catch((j)=>{if(D2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:W5,filePath:q0(Z,W5)})}return J}catch(f){if(D2(f))return[];throw f}}async function H5($){if(x$($)===".cline"){let f=await b9($);return(await Promise.all(f.map((W)=>H5(q0(W,"rules.md"))))).flat()}try{if((await h9($)).isFile())return[{directoryPath:hz($),fileName:x$($),filePath:$}]}catch(f){if(!D2(f))throw f}try{let J=(await C9($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&Q5(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:q0($,Z.name)})),W=q0($,"AGENTS.md");try{if((await h9(W)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch(f){if(D2(f))return[];throw f}}async function uz($){if(x$($)===".cline"){let f=await b9($);return(await Promise.all(f.map((W)=>H5(q0(W,OJ))))).flat()}return H5($)}function qJ($){let f=gz($),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?CA([...f,J]):f,discoverFiles:EA,includeFile:(W)=>W===W5,parseFile:(W)=>zJ(W.content,x$(W.directoryPath)),resolveId:(W)=>E9(W.name)}}function wJ($){let f=$?.directories??MJ($?.workspacePath),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:H5,includeFile:(W,Z)=>W===".clinerules"||Q5(W)||Q5(Z),parseFile:(W)=>_J(W.content,vz(W,$?.workspacePath)),resolveId:(W)=>E9(W.name)}}function SJ($){let f=$?.directories??yJ($?.workspacePath),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:uz,includeFile:(W)=>Q5(W),parseFile:(W)=>TJ(W.content,x$(W.filePath,Z5(W.filePath))),resolveId:(W)=>E9(W.name)}}function bA($){let f=[qJ($?.skills),wJ($?.rules),SJ($?.workflows)];return new Qf(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as kA}from"@cline/shared";function cz($,f){if($.description?.trim())return kA($.description,".");if(f==="workflow")return;return kA($.instructions,".")}function dz($){return $.disabled!==!0}function IA($,f){return[...$.getSnapshot(f).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>dz(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:cz(W.item,f),kind:f})).sort((J,W)=>J.name.localeCompare(W.name))}function hJ($){let f=new Map;for(let J of[...IA($,"workflow"),...IA($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,W)=>J.name.localeCompare(W.name))}function xA($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let W=J[1];if(!W)return $;let Z=W.length+1,Q=$.slice(Z),j=hJ(f).find((H)=>H.name===W);return j?`${j.instructions}${Q}`:$}function A5($){return $.trim().replace(/^\/+/,"").toLowerCase()}function lz($){if(!$||$.length===0)return;let f=$.map(A5).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function pz($,f,J){if(!J)return!0;let W=A5($),Z=A5(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function CJ($,f){let J=lz(f);return[...$.getSnapshot("skill").entries()].map(([Z,Q])=>{let j=Q.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>pz(Z.id,Z.name,J))}function rz($,f){return CJ($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function iz($,f,J){let W=A5(f);if(!W)return{error:"Missing skill name."};let Z=CJ($,J),Q=Z.find((Y)=>Y.id===W);if(Q){let{skill:Y}=Q;if(Y.disabled===!0)return{error:`Skill "${Y.name}" is configured but disabled.`};return{id:Q.id,skill:Y}}let j=W.includes(":")?W.split(":").at(-1)??W:W,H=Z.filter(({id:Y})=>{if(Y===j)return!0;return Y.endsWith(`:${j}`)}),X=H.filter(({skill:Y})=>Y.disabled!==!0);if(X.length===1){let{id:Y,skill:V}=X[0];return{id:Y,skill:V}}if(X.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${X.map(({id:Y})=>Y).join(", ")}`};if(H.length===1){let{skill:Y}=H[0];return{error:`Skill "${Y.name}" is configured but disabled.`}}if(H.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${H.map(({id:Y})=>Y).join(", ")}`};let A=rz($,J);return{error:A.length>0?`Skill "${f}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function nz($,f=Promise.resolve(),J){let W=new Set,Z=async(Q,j)=>{await f;let H=iz($,Q,J);if("error"in H)return H.error;let{id:X,skill:A}=H;if(W.has(X))return`Skill "${A.name}" is already running.`;W.add(X);try{let Y=j?.trim(),V=Y?`
450
+ ${Q}`;return J||Q}function nD(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let Q of $){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of $)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of $){let j=await W.beforeModel?.({...J,request:Q});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},Q={...Q,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...Q.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let Q of $){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of $){let j=await W.beforeTool?.({...J,input:Q});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))Q=j.input}return Z},afterTool:async(J)=>{let Q=J.result,Z;for(let W of $){let j=await W.afterTool?.({...J,result:Q});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)Q=j.result}return Z},onEvent:async(J)=>{for(let Q of $)await Q.onEvent?.(J)}}}class 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 JZ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor(f,$={}){this.config=f,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=f.parentAgentId,this.logger=$.logger??f.logger,this.telemetry=$.telemetry??f.telemetry,this.createAgentRuntimeImpl=$.createAgentRuntimeImpl??dD,this.conversation=new oQ(f.initialMessages),this.messageBuilder=new tQ,this.contributionRegistry=lD({extensions:f.extensions?[...f.extensions]:[],setupContext:{session:f.extensionContext?.session,client:f.extensionContext?.client,user:f.extensionContext?.user,workspaceInfo:f.extensionContext?.workspace,automation:f.extensionContext?.automation,logger:f.extensionContext?.logger??this.logger,telemetry:f.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=f.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new $Z({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,H)=>aD(this.logger,W,j,H),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(W,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:W}]})}});let Q=f.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new fZ(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools(f){if(f.length===0)return;let $=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of f)if(!$.has(Q.name))J.push(Q),$.add(Q.name);this.config={...this.config,tools:J}}updateConnection(f){let $={...this.config};if(f.providerId!==void 0)$.providerId=f.providerId;if(f.modelId!==void 0)$.modelId=f.modelId;if(f.apiKey!==void 0)$.apiKey=f.apiKey;if(f.baseUrl!==void 0)$.baseUrl=f.baseUrl;if(f.headers!==void 0)$.headers=f.headers;if(f.providerConfig!==void 0)$.providerConfig=f.providerConfig;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinking!==void 0)$.thinking=f.thinking;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;this.config=$}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore(f){this.conversation.restore(f),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}abort(f){let $=typeof f==="string"?f:f instanceof Error?f.message:f===void 0?void 0:String(f);if(this.abortRequested=!0,this.abortReason=$,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort($)}async shutdown(f,$){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run(f,$,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!1})}continue(f,$,J){return this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let f=[];for(let $ of this.contributionRegistry.getRegisteredRules()){let J=await rD($);if(J)f.push(J)}return iD(this.config.systemPrompt,f)}executeRun(f){let $;return $=this.executeRunInternal(f).finally(()=>{if(this.activeRunPromise===$)this.activeRunPromise=null}),this.activeRunPromise=$,$}async executeRunInternal(f){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let $=new Date,J=f.userMessage;if(J!==void 0){let F=await sD(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Q=await this.composeSystemPrompt(),Z=nH(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let F of W)j.set(F.name,F);for(let F of this.config.tools)j.set(F.name,F);let H=this.conversation.getConversationId(),X=$X(this.config),A=Array.from(j.values()),Y=M6(this.conversation.getMessages()),V=oH({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:H,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:A,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[FH]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,A),initialMessages:Y,systemPrompt:Q}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),P,R;try{if(f.isContinue)P=await B.continue(void 0);else P=await B.run("")}catch(F){R=F instanceof Error?F:Error(String(F))}finally{K();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(P&&P.messages.length>0){let F=Q2(P.messages);this.conversation.replaceMessages(F)}let G=new Date;try{return this.buildLegacyResult({runResult:P,thrownError:R,startedAt:$,endedAt:G})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch(f){if(this.config.hookErrorMode==="throw")throw f;this.emitLegacyEvent({type:"error",error:f instanceof Error?f:Error(String(f)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let f=nD([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let Q=J?.messages??$.request.messages,Z=await this.prepareMessagesForModelRequest(Q);return{...J,messages:Z}}}}createRuntimePrepareTurn(f,$){let J=this.config.prepareTurn;if(!J)return;return async(Q)=>{let Z=Q2(Q.messages),W=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:Z,apiMessages:W,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:M6(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(N6(f));return M6($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)$=await Q.build($);return this.messageBuilder.buildForApi($)}handleRuntimeEvent(f){switch(f.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage(f.snapshot.messages,[f.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set(f.toolCall.toolCallId,new Date),this.toolInputs.set(f.toolCall.toolCallId,f.toolCall.input),this.inspectLoopForToolCall(f.toolCall.toolName,f.toolCall.input,f.iteration);break}case"tool-finished":{let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=new Date,Q=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let Z=f.message.content.find((X)=>X.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?pD(Z?.type==="tool-result"?Z.output:void 0):void 0,H={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(H),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost};break}default:break}for(let $ of this.eventAdapter.translate(f))this.emitLegacyEvent($)}syncConversationFromRuntimeMessage(f,$){if(f.length>0){this.conversation.replaceMessages(Q2(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=Q2($).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent(f){for(let $ of this.listeners)try{$(f)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall(f,$,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:f,input:$});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${f}\`; stopping to avoid a loop.`})}enqueueMistakeRecord(f){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let $=await this.mistakeTracker.record(f);if($.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:$.message}]}),this.activeRuntime?.abort($.reason??$.message)})}buildLegacyResult(f){let{runResult:$,thrownError:J,startedAt:Q,endedAt:Z}=f,W=Z.getTime()-Q.getTime(),j=J?"error":tD($),H=$?.outputText||($?.status==="failed"?$.error?.message:void 0)||"",X=$?{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost}:this.currentRunUsage,A=$?Q2($.messages):this.conversation.getMessages(),Y=$X(this.config);if(J)throw J;return{text:H,usage:X,messages:A,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:Y},startedAt:Q,endedAt:Z,durationMs:W}}}function aD(f,$,J,Q){if(!f)return;if($==="debug"){f.debug(J,Q);return}if($==="error"&&f.error){f.error(J,Q);return}let Z=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...Q,severity:Z})}function tD(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function sD(f,$,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => fX);return Z(f,$,J,Q)}function $X(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=nQ(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as JX}from"@cline/shared";function QX(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return JX({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
451
+ ${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function ZX(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return JX({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function K$(f){let $={...f};return{getRuntimeConfig:()=>$,getConnectionConfig:()=>({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking}),updateConnectionDefaults:(J)=>{$={...$,...J}}}}function s$(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?QX(f.prompt,$):ZX(f.prompt,$);return{...f.configProvider.getConnectionConfig(),systemPrompt:J,tools:f.tools,maxIterations:f.maxIterations??$.maxIterations,parentAgentId:f.parentAgentId,abortSignal:f.abortSignal,onEvent:f.onEvent,hooks:$.hooks,extensions:$.extensions,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval,logger:$.logger,role:f.role}}function P$(f){let $=s$(f),J=new B$($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var fL=QZ.object({systemPrompt:QZ.string().describe("System prompt defining the sub-agent's behavior"),task:QZ.string().describe("Task for the sub-agent to complete")});function G$(f){return oD({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:eD(fL),execute:async($,J)=>{let Q=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],Z=P$({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:Q,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),H=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:H,input:$})}catch{}try{let X=await Z.run($.task),A={text:X.text,iterations:X.iterations,finishReason:X.finishReason,usage:{inputTokens:X.usage.inputTokens,outputTokens:X.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:H,input:$,result:A,agentResult:X})}catch{}return A}catch(X){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:H,input:$,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as W0,TEAM_AWAIT_TIMEOUT_MS as $L,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as JL,TEAM_RUN_TEXT_PREVIEW_LIMIT as QL,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as ZL,TeamAttachOutcomeFragmentInputSchema as WX,TeamAwaitRunsInputSchema as jX,TeamBroadcastInputSchema as HX,TeamBroadcastToolResultSchema as WL,TeamCancelRunInputSchema as XX,TeamCancelRunToolResultSchema as jL,TeamCleanupInputSchema as AX,TeamCleanupToolResultSchema as HL,TeamCreateOutcomeInputSchema as YX,TeamCreateOutcomeToolResultSchema as XL,TeamFinalizeOutcomeInputSchema as VX,TeamFinalizeOutcomeToolResultSchema as AL,TeamListOutcomesInputSchema as BX,TeamListRunsInputSchema as KX,TeamMailboxMessageToolResultSchema as YL,TeamMissionLogInputSchema as PX,TeamMissionLogToolResultSchema as VL,TeamOutcomeFragmentToolResultSchema as GX,TeamOutcomeToolResultSchema as BL,TeamReadMailboxInputSchema as FX,TeamReviewOutcomeFragmentInputSchema as UX,TeamRunTaskInputSchema as RX,TeamRunTaskToolResultSchema as ZZ,TeamRunToolSummarySchema as WZ,TeamSendMessageInputSchema as DX,TeamSendMessageToolResultSchema as KL,TeamShutdownTeammateInputSchema as LX,TeamSimpleAgentStatusToolResultSchema as OX,TeamSpawnTeammateInputSchema as _X,TeamStatusInputSchema as TX,TeamStatusToolResultSchema as PL,TeamTaskInputSchema as zX,TeamTaskToolResultSchema as o8,validateWithZod as h,zodToJsonSchema as j0}from"@cline/shared";function MX(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function o$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function GL(f){let $=f.result;if(!$)return;return{textPreview:MX($.text,QL),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function q6(f){return f?.toISOString()}function jZ(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:MX(f.message,JL),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:q6(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:q6(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:q6(f.heartbeatAt),lastProgressAt:q6(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:GL(f)}}function FL(f){if(f.status==="failed")throw Error(`Run "${f.id}" failed${f.error?`: ${f.error}`:""}`);if(f.status==="cancelled")throw Error(`Run "${f.id}" was cancelled${f.error?`: ${f.error}`:""}`);if(f.status==="interrupted")throw Error(`Run "${f.id}" was interrupted${f.error?`: ${f.error}`:""}`)}var Z2=["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 NX(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...e$({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:s$({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function W2(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,Q=e$({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),Z=[];for(let W of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(W.agentId))continue;NX({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function e$(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,Q=f.includeManagementTools??!0,Z=[];if(J)Z.push(W0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(_X),execute:async(j)=>{let H=h(_X,j);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!$)throw Error("Spawning teammates is disabled in this context.");let X={agentId:H.agentId,rolePrompt:H.rolePrompt};if(NX({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:X}),!Q)f.onLeadToolsUnlocked?.(e$({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return h(OX,{agentId:H.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(W0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(LX),execute:async(j)=>{let H=h(LX,j);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(H.agentId,H.reason),h(OX,{agentId:H.agentId,status:"stopped"})}})),Z.push(W0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(TX),execute:async(j)=>{return h(TX,j),h(PL,f.runtime.getSnapshot())}})),Z.push(W0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:j0(zX),execute:async(j)=>{let H=h(zX,j);switch(H.action){case"create":{let X=new Set(ZL.create??[]),A=Object.entries(j).filter(([V,B])=>X.has(V)&&B!=null).map(([V])=>V),Y=f.runtime.createTask({title:o$(H.title,"title"),description:o$(H.description,"description"),dependsOn:H.dependsOn,assignee:H.assignee,createdBy:f.requesterId});return h(o8,{action:"create",taskId:Y.id,status:Y.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return h(o8,{action:"list",tasks:f.runtime.listTaskItems({status:H.status,assignee:H.assignee})});case"claim":{let X=f.runtime.claimTask(o$(H.taskId,"taskId"),f.requesterId);return h(o8,{action:"claim",taskId:X.id,status:X.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let X=f.runtime.completeTask(o$(H.taskId,"taskId"),f.requesterId,o$(H.summary,"summary"));return h(o8,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=f.runtime.blockTask(o$(H.taskId,"taskId"),f.requesterId,o$(H.reason,"reason"));return h(o8,{action:"block",taskId:X.id,status:X.status})}}}}));let W=new Map;return Z.push(W0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(RX),execute:async(j)=>{let H=h(RX,j);if(H.runMode==="async"){let Y=f.runtime.startTeammateRun(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:f.requesterId,continueConversation:H.continueConversation||void 0});return h(ZZ,{agentId:H.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${H.agentId} and queued as ${Y.id}.`,runId:Y.id})}let X=W.get(H.agentId);if(X){let Y=await X;return h(ZZ,{...Y,status:"joined",deduped:!0,message:`Task for ${H.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=f.runtime.routeToTeammate(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:f.requesterId,continueConversation:H.continueConversation||void 0}).then((Y)=>h(ZZ,{agentId:H.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${H.agentId} and completed in sync mode.`,text:Y.text,iterations:Y.iterations})).finally(()=>{W.delete(H.agentId)});return W.set(H.agentId,A),await A}})),Z.push(W0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(XX),execute:async(j)=>{let H=h(XX,j),X=f.runtime.cancelRun(H.runId,H.reason);return h(jL,{runId:X.id,status:X.status})}})),Z.push(W0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(KX),execute:async(j)=>h(WZ.array(),f.runtime.listRuns(h(KX,j)).map(jZ))})),Z.push(W0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:j0(jX),timeoutMs:$L,execute:async(j)=>{let H=h(jX,j);if(H.runId){let Y=await f.runtime.awaitRun(H.runId);return FL(Y),h(WZ,jZ(Y))}let X=await f.runtime.awaitAllRuns(),A=X.filter((Y)=>["failed","cancelled","interrupted"].includes(Y.status));if(A.length>0){let Y=A.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${Y}`)}return h(WZ.array(),X.map(jZ))}})),Z.push(W0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(DX),execute:async(j)=>{let H=h(DX,j),X=f.runtime.sendMessage(f.requesterId,H.toAgentId,H.subject,H.body,H.taskId??void 0);return h(KL,{id:X.id,toAgentId:X.toAgentId})}})),Z.push(W0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(HX),execute:async(j)=>{let H=h(HX,j),X=f.runtime.broadcast(f.requesterId,H.subject,H.body,{taskId:H.taskId??void 0});return h(WL,{delivered:X.length})}})),Z.push(W0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(FX),execute:async(j)=>{let H=h(FX,j);return h(YL.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:H.unreadOnly,markRead:!0}))}})),Z.push(W0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(PX),execute:async(j)=>{let H=h(PX,j),X=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:H.taskId||void 0,kind:H.kind,summary:H.summary,evidence:H.evidence?.length?H.evidence:void 0,nextAction:H.nextAction||void 0});return h(VL,{id:X.id})}})),Z.push(W0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(AX),execute:async(j)=>{if(h(AX,j),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),h(HL,{status:"cleaned"})}})),Z.push(W0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(YX),execute:async(j)=>{let H=h(YX,j),X=f.runtime.createOutcome({title:H.title,requiredSections:H.requiredSections,createdBy:f.requesterId});return h(XL,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),Z.push(W0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(WX),execute:async(j)=>{let H=h(WX,j),X=f.runtime.attachOutcomeFragment({outcomeId:H.outcomeId,section:H.section,sourceAgentId:f.requesterId,sourceRunId:H.sourceRunId||void 0,content:H.content});return h(GX,{fragmentId:X.id,status:X.status})}})),Z.push(W0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(UX),execute:async(j)=>{let H=h(UX,j),X=f.runtime.reviewOutcomeFragment({fragmentId:H.fragmentId,reviewedBy:f.requesterId,approved:H.approved});return h(GX,{fragmentId:X.id,status:X.status})}})),Z.push(W0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(VX),execute:async(j)=>{let H=h(VX,j),X=f.runtime.finalizeOutcome(H.outcomeId);return h(AL,{outcomeId:X.id,status:X.status})}})),Z.push(W0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(BX),execute:async(j)=>{return h(BX,j),h(BL.array(),f.runtime.listOutcomes())}})),Z}function y6(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}function qX(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var UL=[{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:G$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...Z2]}],RL={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function DL(f){return f==="plan"||f==="yolo"?f:"act"}function wX(f){let $=DL(f.mode),J=c0[mf({mode:$})],Q=J2(f.providerId??"",f.modelId??"",$,$2);return{mode:$,flags:{...J,...Q,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function yX(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=wX($);if(f==="spawn_agent")return J.enableSpawnAgent===!0;if(f==="teams")return J.enableAgentTeams===!0;if(f==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let Q=RL[f];return Q?J[Q]===!0:!1}function LL(f,$){if(f.id==="editor"){let{flags:J}=wX($),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:yX(f.id,$),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...f,defaultEnabled:yX(f.id,$)}}function f1(f={}){return UL.map(($)=>LL($,f))}function w6(f={}){return f1(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function C6(f){if(!f.enabled)return new Set;let $=f1(f.availabilityContext),J=new Set($.map((Q)=>Q.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of f.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${$.map((Z)=>Z.id).join(", ")}`);return new Set(f.allowlist)}function e8(f,$={}){return f1($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function S6(f,$={}){return e8(f,$)}function $1(f={}){let{executorOptions:$={},executors:J,...Q}=f,Z={...f2($),...J??{}};return Y$({...Q,executors:Z})}import{mkdirSync as NL,writeFileSync as qL}from"node:fs";import{dirname as yL}from"node:path";import{normalizeUserInput as wL}from"@cline/shared";import{nanoid as CL}from"nanoid";var SX={};q(SX,{sanitizeSessionToken:()=>J1,parseTeamTaskSubSessionId:()=>H2,parseSubSessionId:()=>$J,makeTeamTaskSubSessionId:()=>fJ,makeSubSessionId:()=>j2,deriveSubsessionStatus:()=>JJ});import{nanoid as TL}from"nanoid";function J1(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function j2(f,$){let J=J1(f),Q=J1($),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function fJ(f,$){let J=J1(f),Q=J1($);return`${J}__teamtask__${Q}__${TL(6)}`}function H2(f){let J=f.indexOf("__teamtask__");if(J<=0)return null;let Q=f.slice(0,J),Z=f.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),H=Z.slice(W+2);if(!Q||!j||!H)return null;return{rootSessionId:Q,agentId:j,teamTaskId:H}}function $J(f){if(H2(f))return null;let $="__",J=f.indexOf($);if(J<=0)return null;let Q=f.slice(0,J),Z=f.slice(J+$.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function JJ(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var bX={};q(bX,{isTerminalSessionStatus:()=>hX,isNonTerminalSessionStatus:()=>J0,SessionSource:()=>U0,SESSION_STATUSES:()=>QJ,NON_TERMINAL_SESSION_STATUSES:()=>EX});import{SESSION_STATUS_VALUES as zL}from"@cline/shared";var QJ=zL,EX=["idle","running","pending"];function hX(f){return!EX.includes(f)}function J0(f){return!hX(f)}var U0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var ML=a.enum(QJ),C0=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:ML,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 kX(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function XZ(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 IX(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function vf(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function HZ(f,$){let J={...f};J.id=vf(J.id)??CL();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:vf(Q?.id)??vf(J.modelId)??vf($?.id),provider:vf(Q?.provider)??vf(J.providerId)??vf($?.provider),family:vf(Q?.family)??vf($?.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 E6(f){return f.map(($)=>HZ($))}function h6(f,$,J=[]){let Q=f.map((X,A)=>{let Y=J[A],B=Y?.role===X.role&&JSON.stringify(Y.content)===JSON.stringify(X.content)?{...Y,...X}:{...X};return HZ(B)}),Z=J.length,W=[];for(let X=Z;X<Q.length;X+=1)if(Q[X]?.role==="assistant")W.push(X);if(W.length===0){let X=[...Q].reverse().findIndex((A)=>A.role==="assistant");if(X===-1)return Q;W.push(Q.length-1-X)}let j=W[W.length-1],H=W.some((X)=>Q[X]?.metrics);for(let X of W){let A=Q[X],Y=A.metrics;if(!Y&&X===j&&!H){let V=$.usage;Y={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}Q[X]={...HZ(A,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...Y?{metrics:Y}:{},ts:A.ts??$.endedAt.getTime()}}return Q}function ZJ(f){return{sessionId:f.sessionId,source:f.source,pid:f.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??void 0,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:f.parentSessionId??void 0,parentAgentId:f.parentAgentId??void 0,agentId:f.agentId??void 0,conversationId:f.conversationId??void 0,isSubagent:f.isSubagent,prompt:f.prompt??void 0,metadata:f.metadata??void 0,messagesPath:f.messagesPath??void 0,updatedAt:f.updatedAt}}var SL=120;function Q1(f){let $=f?.trim();return $?$.slice(0,SL):void 0}function AZ(f){let $=wL(f??"").trim();if(!$)return;return Q1($.split(`
452
+ `)[0]?.trim())}function F$(f){if(!f)return;let $={...f},J=Q1(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function WJ(f){let $=F$(f.metadata)??{},J=f.title!==void 0?Q1(f.title):AZ(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function YZ(f){let $=H2(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=$J(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function VZ(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:E6(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function xX(f,$,J){NL(yL(f),{recursive:!0}),qL(f,`${JSON.stringify(VZ({updatedAt:$,context:J,messages:[]}),null,2)}
453
+ `,"utf8")}function gX(f,$){return C0.parse({version:1,session_id:f.sessionId,source:f.source,pid:f.pid,started_at:f.startedAt,ended_at:$?.endedAt??f.endedAt??void 0,exit_code:$?.exitCode??f.exitCode??void 0,status:$?.status??f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName??void 0,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt??void 0,metadata:$?.metadata??f.metadata??void 0,messages_path:f.messagesPath??void 0})}async function mX(f,$,J){let Q=0;while(!0){let Z=await f();if(Z===void 0)return{updated:!1};let W=await $(Z);if(typeof W==="object"&&W!==null&&"updated"in W&&W.updated===!1){if(Q+=1,Q>=J)return W;continue}return W}}O0();var vX={};q(vX,{summarizeUsageFromMessages:()=>A2,sumUsageTotals:()=>jJ,getCurrentContextSize:()=>BZ,createInitialAccumulatedUsage:()=>K0,accumulateUsageTotals:()=>H0});function K0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0(f,$){return{inputTokens:f.inputTokens+Math.max(0,$.inputTokens??0),outputTokens:f.outputTokens+Math.max(0,$.outputTokens??0),cacheReadTokens:f.cacheReadTokens+Math.max(0,$.cacheReadTokens??0),cacheWriteTokens:f.cacheWriteTokens+Math.max(0,$.cacheWriteTokens??0),totalCost:f.totalCost+Math.max(0,$.totalCost??0)}}function jJ(f){let $=K0();for(let J of f)$=H0($,J);return $}function X2(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function A2(f){let $=K0();for(let J of f){let Q=J.metrics;if(!Q)continue;$=H0($,{inputTokens:X2(Q.inputTokens),outputTokens:X2(Q.outputTokens),cacheReadTokens:X2(Q.cacheReadTokens),cacheWriteTokens:X2(Q.cacheWriteTokens),totalCost:X2(Q.cost)})}return $}function BZ(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let Q=X2(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function EL(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function KZ(f){if(!f||typeof f!=="object")return{};let $=f;return{agentId:typeof $.agentId==="string"?$.agentId:void 0,conversationId:typeof $.conversationId==="string"?$.conversationId:void 0,parentAgentId:typeof $.parentAgentId==="string"?$.parentAgentId:void 0}}function cf(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,Q=f.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:$,agentKind:Z,conversationId:f.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:f.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:f.teamId?.trim()||void 0,teamName:f.teamName?.trim()||void 0,teamRole:Q,teamAgentId:f.teamAgentId?.trim()||void 0}}function hL(f){return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost}}function bL(f){let $=f.isPrimaryAgentEvent?[f.overrides?.agentId,f.eventMetadata.agentId,f.overrides?.teamAgentId]:[f.overrides?.teamAgentId,f.overrides?.agentId,f.eventMetadata.agentId,f.eventMetadata.conversationId];for(let J of $){let Q=J?.trim();if(Q)return Q}return f.isPrimaryAgentEvent?"root":"unknown"}function PZ(f,$,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=f,H=Z.telemetry,X=W?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,Y=KZ($),V=cf({agentId:J?.agentId??Y.agentId,conversationId:J?.conversationId??Y.conversationId,parentAgentId:J?.parentAgentId??Y.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??X?.getTeamId(),teamName:J?.teamName??X?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if($.type==="content_start"&&$.contentType==="tool"&&$.toolName==="skills"){let B=EL($.input);if(B)b4(H,{ulid:Q,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if($.type==="content_end"&&$.contentType==="tool"){let B=$.toolName??"unknown",K=!$.error;if(h4(H,{ulid:Q,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))k4(H,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:$.error,...V})}if($.type==="notice"&&$.reason==="api_error")j8(H,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:$.message,...V});if($.type==="error")j8(H,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:$.error?.message??"unknown error",...V});if($.type==="usage"&&W?.turnUsageBaseline){let B=hL($);if(A){W.turnPrimaryUsage=H0(W.turnPrimaryUsage??K0(),B);let P=H0(W.turnUsageBaseline,W.turnPrimaryUsage);f.usageBySession.set(Q,P),g1(H,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),S4(H,{ulid:Q,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:Z.modelId,...V})}else{let P=bL({isPrimaryAgentEvent:A,overrides:J,eventMetadata:Y}),R=W.turnUsageByAgent??new Map;W.turnUsageByAgent=R,R.set(P,H0(R.get(P)??K0(),B))}let K=H0(W.turnPrimaryUsage??K0(),jJ(W.turnUsageByAgent?.values()??[]));f.aggregateUsageBySession.set(Q,H0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,K))}if($.type==="iteration_end"&&A)f.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:IX($),ts:Date.now()}})}function U$(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as v_}from"@cline/shared";jf();import{existsSync as v6,readFileSync as OO,statSync as _O}from"node:fs";import{basename as TO,dirname as g6,join as c6,resolve as m6}from"node:path";import{discoverPluginModulePaths as zO,resolveConfiguredPluginModulePaths as HA,resolvePluginConfigSearchPaths as MO,SKILLS_CONFIG_DIRECTORY_NAME as NO}from"@cline/shared/storage";import{resolve as fO}from"node:path";import{normalizePluginManifest as $O}from"@cline/shared";import{existsSync as R0,readFileSync as V2}from"node:fs";import{builtinModules as kL,createRequire as RZ}from"node:module";import{dirname as R$,extname as XJ,isAbsolute as IL,resolve as l}from"node:path";import{fileURLToPath as uX}from"node:url";import{PLUGIN_FILE_EXTENSIONS as xL}from"@cline/shared";var dX=R$(uX(import.meta.url)),gL=RZ(import.meta.url),mL=l(dX,"..","..","..","..",".."),GZ=uL(mL),vL=["@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"],DZ=new Set(kL.flatMap((f)=>[f,f.replace(/^node:/,"")])),HJ=new Set(xL),cL=["development","node","import","require","default"];function uL(f){let $={},J={"@cline/sdk":l(f,"packages/sdk/src/index.ts"),"@cline/agents":l(f,"packages/agents/src/index.ts"),"@cline/core":l(f,"packages/core/src/index.ts"),"@cline/llms":l(f,"packages/llms/src/index.ts"),"@cline/shared":l(f,"packages/shared/src/index.ts"),"@cline/shared/storage":l(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":l(f,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(R0(Z))$[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=l(f,"packages",Q),W=l(Z,"package.json");if(!R0(W))continue;try{let j=JSON.parse(V2(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let H=l(Z,j.exports);if(R0(H))$[j.name]=H;continue}if(typeof j.exports!=="object")continue;for(let[H,X]of Object.entries(j.exports)){let A=dL(Z,X);if(!A)continue;let Y=H==="."?j.name:`${j.name}/${H.replace(/^\.\//,"")}`;$[Y]=A}}catch{}}return $}function dL(f,$){let J=LZ($);if(!J)return null;let Q=lX(f,J);for(let Z of Q)if(R0(Z))return Z;return null}function LZ(f,$=new Set){if(typeof f==="string")return f;if(!f||typeof f!=="object")return null;if($.has(f))return null;$.add(f);let J=f;for(let Q of cL){let Z=LZ(J[Q],$);if(Z)return Z}return null}function lX(f,$){let J=$.replace(/^\.\//,""),Q=[l(f,$)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[l(f,`${Z}.ts`),l(f,`${Z}.tsx`),l(f,`${Z}.mts`),l(f,`${Z}.cts`),...Q]}return Q}function lL(f){return Object.fromEntries(Object.entries(f).sort(([$],[J])=>J.length-$.length))}function b6(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function Y2(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function pL(f){let $=Y2(f);if(f===$)return".";return`.${f.slice($.length)}`}function pX(f){return Y2(f).startsWith("@cline/")}function FZ(f,$){let J=Y2($),Q=R$(f);while(!0){let Z=l(Q,"node_modules",J);if(R0(Z)||R0(l(Z,"package.json")))return!0;let W=l(Q,"..");if(W===Q)return!1;Q=W}}function cX(f){return UZ(f)!==null}function UZ(f){try{return gL.resolve(f)}catch{}return rL(f)}function rL(f){let $=Y2(f),J=rX($);if(!J)return null;let Q=l(J,"package.json");try{let Z=JSON.parse(V2(Q,"utf8")),W=pL(f),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,H=LZ(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!H)return null;let X=l(J,H),A=[X,...lX(J,H).filter((Y)=>Y!==X)];for(let Y of A)if(R0(Y))return Y;return null}catch{return null}}function iL(){let f=[dX],$=process.env.CLINE_WRAPPER_PATH?.trim();if($)f.push(R$(R$($)));let J=process.execPath?.trim();if(J)f.push(R$(J));return[...new Set(f.map((Q)=>l(Q)))]}function nL(f,$){let J=f;while(!0){let Q=l(J,"package.json");if(R0(Q))try{if(JSON.parse(V2(Q,"utf8")).name===$)return J}catch{}let Z=l(J,"node_modules",$,"package.json");if(R0(Z))return R$(Z);let W=l(J,"..");if(W===J)return null;J=W}}function rX(f){for(let $ of iL()){let J=nL($,f);if(J)return J}return null}function aL(f){let J=R$(f);for(let Q=0;Q<4;Q++){let Z=l(J,"package.json");if(R0(Z))try{let j=JSON.parse(V2(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 iX(f,$){let J=$.startsWith("file:")?uX($):IL($)?$:l(R$(f),$);if(R0(J)&&HJ.has(XJ(J)))return J;for(let Q of HJ){let Z=`${J}${Q}`;if(R0(Z))return Z}for(let Q of HJ){let Z=l(J,`index${Q}`);if(R0(Z))return Z}return null}function nX(f){let $=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of J)for(let Z of f.matchAll(Q)){let W=Z[1];if(W)$.add(W)}return[...$]}function tL(f){return XJ(f)!==".ts"}function aX(f,$,J=new Set){if(J.has(f)||!R0(f))return;if(J.add(f),!HJ.has(XJ(f)))return;let Q=V2(f,"utf8"),Z=tL(f);for(let W of nX(Q)){if(W.startsWith("node:")||DZ.has(W))continue;if(b6(W)){if(!Z)continue;if(Object.hasOwn(GZ,W)||Object.hasOwn(GZ,Y2(W))||FZ(f,W)||pX(W)&&cX(W)||$&&cX(W))continue;throw Error(`Cannot find module '${Y2(W)}'`)}let j=iX(f,W);if(j)aX(j,$,J)}}function tX(f,$=new Set,J=new Set){if($.has(f)||!R0(f))return J;if($.add(f),!HJ.has(XJ(f)))return J;let Q=V2(f,"utf8");for(let Z of nX(Q)){if(J.add(Z),b6(Z))continue;let W=iX(f,Z);if(W)tX(W,$,J)}return J}function sL(f,$){let J=RZ(f),Q={},Z=tX(f),W=new Set(vL);for(let[j,H]of Object.entries(GZ)){try{J.resolve(j);continue}catch{}Q[j]=H}for(let j of Z)if(b6(j)&&(pX(j)||$))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||FZ(f,j))continue;let H=UZ(j);if(H)Q[j]=H}if(!$)return Q;for(let j of Z){if(!b6(j)||Object.hasOwn(Q,j)||FZ(f,j)||j.startsWith("node:")||DZ.has(j))continue;let H=UZ(j);if(H)Q[j]=H}return Q}function oL(f){let $=XJ(f);return $===".ts"||$===".tsx"||$===".mts"||$===".cts"}var Z1;function eL(){if(Z1!==void 0)return Z1;let f=rX("jiti");if(!f)return Z1=null,null;let $=l(f,"dist","babel.cjs");if(!R0($))return Z1=null,null;try{let Q=RZ($)($);Z1=typeof Q==="function"?Q:null}catch{Z1=null}return Z1}async function sX(f,$={}){let J=!aL(f);aX(f,J);let Q=sL(f,J),Z=lL(Q),W=await import("jiti"),j=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!j)throw Error("Unable to load jiti");let H=Object.entries(Z).filter(([,V])=>oL(V)).map(([V])=>V),X=eL(),A=X?(V)=>X({...V,interopDefault:!0}):void 0;return await j(f,{alias:Z,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...DZ],transformModules:H,tryNative:!1,...A?{transform:A}:{}}).import(f,{})}function oX(f,$){if(!f)return!0;if(f.providerIds?.length){if(!$?.providerId||!f.providerIds.includes($.providerId))return!1}if(f.modelIds?.length){if(!$?.modelId||!f.modelIds.includes($.modelId))return!1}return!0}function eX(f){return typeof f==="object"&&f!==null}function OZ(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function JO(f,$){if(!eX(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!OZ(f.manifest.capabilities))throw Error(`Invalid plugin module at ${$}: manifest.capabilities must be a string array`);if(f.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${$}: manifest.capabilities cannot be empty`);if(Object.hasOwn(f.manifest,"providerIds")&&!OZ(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!OZ(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function QO(f,$){if(!eX(f))throw Error(`Invalid plugin module at ${$}: expected object export`);if(typeof f.name!=="string"||f.name.length===0)throw Error(`Invalid plugin module at ${$}: expected non-empty "name"`);if(!Object.hasOwn(f,"manifest"))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);JO(f,$)}async function AJ(f,$={}){let J=fO($.cwd??process.cwd(),f),Q=await sX(J,{useCache:$.useCache}),Z=$.exportName??"plugin",W=Q.default??Q[Z];QO(W,J);let j=W,H=j.setup,X=H?(A,Y)=>{let V={...$.session,...Y.session},B={...Y,session:Object.keys(V).length>0?V:void 0,client:$.client??Y.client,user:$.user??Y.user,workspaceInfo:$.workspaceInfo??Y.workspaceInfo,automation:$.automation??Y.automation,logger:$.logger??Y.logger,telemetry:$.telemetry??Y.telemetry};return H(A,B)}:void 0;return{...j,manifest:$O(j.manifest),setup:X}}async function k6(f,$={}){return(await W1(f,$)).plugins}async function W1(f,$={}){let J=[],Q=[],Z=new Map,W=0;for(let H of f)try{let X=await AJ(H,$);if(!oX(X.manifest,$))continue;let A=Z.get(X.name);if(A)Q.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:H,overriddenPluginPath:A.pluginPath,message:`Plugin "${X.name}" from ${H} overrides ${A.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:H,order:W++})}catch(X){let A=X instanceof Error?X.message:String(X);J.push({pluginPath:H,phase:"load",message:A,stack:X instanceof Error?X.stack:void 0})}let j=[...Z.values()].sort((H,X)=>H.order-X.order);return{plugins:j.map((H)=>H.plugin),pluginPaths:j.map((H)=>H.pluginPath),failures:J,warnings:Q}}import{existsSync as MZ}from"node:fs";import{createRequire as jA}from"node:module";import{dirname as I6,join as K2}from"node:path";import{fileURLToPath as XO}from"node:url";var ZA={};q(ZA,{resolveSubprocessRuntimeExecutable:()=>_Z,buildSubprocessSandboxCommand:()=>QA,SubprocessSandbox:()=>B2,CLINE_JS_RUNTIME_PATH_ENV:()=>JA});import{spawn as ZO}from"node:child_process";import{basename as WO}from"node:path";import{augmentNodeCommandForDebug as jO,withResolvedClineBuildEnv as HO}from"@cline/shared";function fA(f){if(f instanceof Error)return f;return Error(String(f))}var JA="CLINE_JS_RUNTIME_PATH";function $A(f){let $=f?.trim();if(!$)return!1;let J=WO($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function _Z(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[JA]?.trim();if(J)return J;let Q=f.execPath?.trim()||process.execPath;if($A(Q))return Q;for(let Z of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let W=Z?.trim();if(W&&$A(W))return W}return"node"}function QA(f,$={}){let J=_Z({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return jO([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class B2{options;process=null;requestCounter=0;pending=new Map;constructor(f){this.options=f}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest(f){let $=this.pending.get(f);if(!$)return;if(this.pending.delete(f),$.timeout)clearTimeout($.timeout);return $}start(){if(this.process&&this.process.exitCode===null)return;let f=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],$=QA(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=ZO($[0]??_Z(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:HO(process.env)});this.process=J;let Q="",Z=(W)=>{let j=Q+W;Q=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{Z(W)}),J.on("message",(W)=>{this.onMessage(W)}),J.on("error",(W)=>{this.failPending(Error(`${this.processLabel} process error: ${fA(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let H=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${H?`: ${H}`:""}`))})}async call(f,$,J={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,W={type:"call",id:Z,method:f,args:$};return await new Promise((j,H)=>{let X={resolve:(A)=>j(A),reject:H};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),H(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(Z,X),Q.send(W,(A)=>{if(!A)return;let Y=this.clearPendingRequest(Z);if(!Y)return;Y.reject(Error(`${this.processLabel} failed to send call "${f}": ${fA(A).message}`))})})}async shutdown(){let f=this.process;if(this.process=null,!f||f.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise(($)=>{let J=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}$()},300);f.once("exit",()=>{clearTimeout(J),$()});try{f.kill("SIGTERM")}catch{clearTimeout(J),$()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage(f){if(!f)return;if(f.type==="event"){if(typeof f.name==="string"&&f.name.length>0)this.options.onEvent?.({name:f.name,payload:f.payload});return}if(f.type!=="response"||!f.id)return;let $=this.clearPendingRequest(f.id);if(!$)return;if(f.ok){$.resolve(f.result);return}$.reject(Error(f.error?.message||`${this.processLabel} call failed`))}failPending(f){for(let[$,J]of this.pending.entries()){if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);J.reject(f)}}}function AO(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],rules:f.contributions?.rules??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function YJ(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function YO(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function VO(){let f=process.env.CLINE_WRAPPER_PATH?.trim();if(!f)return;try{let J=jA(f).resolve(`${YO()}/package.json`),Q=K2(I6(J),"extensions","plugin-sandbox-bootstrap.js");return MZ(Q)?Q:void 0}catch{return}}function BO(){let f=process.execPath?.trim();if(!f)return;let $=K2(I6(I6(f)),"extensions","plugin-sandbox-bootstrap.js");return MZ($)?$:void 0}function KO(){let f=I6(XO(import.meta.url)),$=jA(import.meta.url),J=[K2(f,"plugin-sandbox-bootstrap.js"),K2(f,"extensions","plugin-sandbox-bootstrap.js"),K2(f,"agents","plugin-sandbox-bootstrap.js"),VO(),BO()];for(let W of J.filter((j)=>typeof j==="string"))if(MZ(W))return{file:W};let Q=K2(f,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=$.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
454
+ `)}}var TZ=KO();function zZ(f,$,J){if(typeof f==="number"&&f>0)return f;if(J){let Q=process.env[J];if(Q){let Z=Number(Q);if(Number.isInteger(Z)&&Z>0)return Z}}return $}async function x6(f){let $=new B2({name:"plugin-sandbox",..."file"in TZ?{bootstrapFile:TZ.file}:{bootstrapScript:TZ.script},onEvent:f.onEvent}),J=zZ(f.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=zZ(f.hookTimeoutMs,3000),Z=zZ(f.contributionTimeoutMs,60000),W={pluginPaths:f.pluginPaths,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,loggerEnabled:Boolean(f.logger)},j,H=()=>{return j??=$.call("initialize",W,{timeoutMs:J}).finally(()=>{j=void 0}),j},X;try{X=await $.call("initialize",W,{timeoutMs:J})}catch(V){throw await $.shutdown().catch(()=>{}),V}let A=X.plugins.map(AO);return{extensions:A.map((V)=>{let B={name:V.name,__clinePluginPath:V.pluginPath,manifest:V.manifest,setup:(K)=>{PO(K,$,V,Z,H),GO(K,$,V,Z,H),FO(K,$,V,Z,H),RO(K,$,V,Z,H),UO(K,V)}};return B.hooks=LO($,V,Q,H),B}),failures:X.failures,pluginPaths:A.map((V)=>V.pluginPath),shutdown:async()=>{await $.shutdown()},warnings:X.warnings}}function PO(f,$,J,Q,Z){for(let W of J.contributions?.tools??[]){let j={name:W.name,description:W.description??"",inputSchema:W.inputSchema??{type:"object",properties:{}},timeoutMs:W.timeoutMs,retryable:W.retryable,execute:async(H,X)=>{try{return await $.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:H,context:X},{timeoutMs:Q})}catch(A){if(!YJ(A))throw A;return await Z(),await $.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:H,context:X},{timeoutMs:Q})}}};f.registerTool(j)}}function GO(f,$,J,Q,Z){for(let W of J.contributions?.commands??[])f.registerCommand({name:W.name,description:W.description,handler:async(j)=>{try{return await $.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}catch(H){if(!YJ(H))throw H;return await Z(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}}})}function FO(f,$,J,Q,Z){for(let W of J.contributions?.rules??[])f.registerRule({id:W.ruleId,source:W.source,content:W.hasContentHandler===!0?async()=>{try{return await $.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}catch(j){if(!YJ(j))throw j;return await Z(),await $.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}}:W.content??""})}function UO(f,$){for(let J of $.contributions?.providers??[])f.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of $.contributions?.automationEventTypes??[])f.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function RO(f,$,J,Q,Z){for(let W of J.contributions?.messageBuilders??[])f.registerMessageBuilder({name:W.name,async build(j){try{let H=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return WA(H)?H:j}catch(H){if(!YJ(H))throw H;await Z();let X=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return WA(X)?X:j}}})}function WA(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function DO(f,$,J,Q,Z){return async(W)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:W},{timeoutMs:Q})}catch(j){if(!YJ(j))throw j;return await Z(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:W},{timeoutMs:Q})}}}function LO(f,$,J,Q){let Z={};for(let W of $.hooks??[])Z[W]=DO(f,$.pluginId,W,J,Q);return Object.keys(Z).length>0?Z:void 0}var qZ="package.json",qO="package";function VJ(f){return MO(f)}function BJ(f){return zO(f)}function yO(f){try{return v6(f)&&_O(f).isDirectory()}catch{return!1}}function yZ(f){let $=[],J=new Set;for(let Q of f){let Z=m6(Q);if(J.has(Z))continue;J.add(Z),$.push(Z)}return $}function XA(f){let $=yZ(f);return i4($)}function AA(f){return VJ(f).flatMap(($)=>BJ($)).filter(($)=>v6($))}function wO(f,$){let J=[];for(let Q of f)try{J.push(...HA([Q],$))}catch{}return J}function NZ(f){return typeof f==="object"&&f!==null}function CO(f){try{let $=JSON.parse(OO(c6(f,qZ),"utf8"));if(!NZ($)||!NZ($.cline))return[];let J=$.cline.plugins;if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(typeof Z==="string"){Q.push(Z);continue}if(!NZ(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=m6($);return CO(f).some((Q)=>m6(f,Q)===J)}function SO(f,$){return TO(f)===qO&&v6(c6(g6(f),qZ))&&YA(g6(f),$)}function EO(f){let $=m6(f),J=[],Q=g6($);while(!0){if(SO(Q,$)){J.push(Q);break}if(v6(c6(Q,qZ))){if(YA(Q,$))J.push(Q);break}let Z=g6(Q);if(Z===Q)break;Q=Z}return yZ(J)}function j1(f={}){let $=f.cwd??process.cwd(),J=AA(f.workspacePath),Q=HA(f.pluginPaths??[],$);return XA([...Q,...J])}function hO(f={}){let $=f.cwd??process.cwd(),J=AA(f.workspacePath),Q=wO(f.pluginPaths??[],$);return XA([...Q,...J])}function H1(f){let $=[];for(let J of f)for(let Q of EO(J)){let Z=c6(Q,NO);if(yO(Z))$.push(Z)}return yZ($)}function VA(f={}){return H1(hO(f))}async function P2(f={}){let $=j1(f);if($.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if(f.mode==="in_process"){let Q=await W1($,{cwd:f.cwd,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,automation:f.automation,logger:f.logger,telemetry:f.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let J=await x6({pluginPaths:$,exportName:f.exportName,importTimeoutMs:f.importTimeoutMs,hookTimeoutMs:f.hookTimeoutMs,contributionTimeoutMs:f.contributionTimeoutMs,onEvent:f.onEvent,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,logger:f.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}import{execFile as bO}from"node:child_process";import{promisify as kO}from"node:util";var IO=kO(bO);function wZ(f,$){f?.log($,{severity:"warn"})}function xO(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!J.latest||!Array.isArray(J.history))return;let Q=J.latest,Z=J.history.filter((W)=>!!W&&typeof W==="object"&&typeof W.ref==="string"&&typeof W.createdAt==="number"&&typeof W.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:Z}}async function X1(f,$){let J=await IO("git",["-C",f,...$],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function CZ(f,$){if(!f)return;let J=`refs/cline/checkpoints/${$}/`;try{let{stdout:Q}=await X1(f,["for-each-ref","--format=%(refname)",J]),Z=Q.trim().split(`
455
+ `).filter(Boolean);await Promise.allSettled(Z.map((W)=>X1(f,["update-ref","-d",W])))}catch{}}async function BA(f,$,J){if(!f||J.length===0)return;await Promise.allSettled(J.map((Q)=>X1(f,["update-ref",`refs/cline/checkpoints/${$}/${Q.runCount}`,Q.ref])))}function gO(f,$){let J=f.findIndex((Q)=>Q.runCount===$.runCount);if(J<0)return[...f,$];return f.map((Q,Z)=>Z===J?$:Q)}function KA(f){let $=f.initialRunCount??0,J,Q=async()=>{if(J!==void 0)return J;try{J=(await X1(f.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if(f.createCheckpoint)return await f.createCheckpoint({cwd:f.cwd,sessionId:f.sessionId,runCount:$});if(!await Q())return;let W=async(A)=>{try{let V=(await X1(f.cwd,["rev-parse","HEAD"])).stdout.trim();if(!V)return;return{ref:V,createdAt:Date.now(),runCount:$,kind:"commit"}}catch(Y){wZ(f.logger,`${A}: ${Y instanceof Error?Y.message:String(Y)}`);return}},j=`cline checkpoint session=${f.sessionId} run=${$}`,H="";try{H=(await X1(f.cwd,["stash","create",j])).stdout.trim()}catch(A){return wZ(f.logger,`Checkpoint snapshot failed: ${A instanceof Error?A.message:String(A)}`),W("Checkpoint HEAD fallback failed")}if(!H)return W("Checkpoint HEAD fallback failed");let X=`refs/cline/checkpoints/${f.sessionId}/${$}`;try{await X1(f.cwd,["update-ref",X,H])}catch(A){wZ(f.logger,`Checkpoint store failed: ${A instanceof Error?A.message:String(A)}`);return}return{ref:H,createdAt:Date.now(),runCount:$,kind:"stash"}};return{beforeRun:async({snapshot:W})=>{if(W.parentAgentId!=null)return;$+=1;return},beforeModel:async({snapshot:W})=>{if(W.parentAgentId!=null||W.iteration!==1||$<1)return;let j=await Z();if(!j)return;let H=await f.readSessionMetadata(),X=xO(H);if(X?.latest.ref===j.ref)return;let A=gO(X?.history??[],j);await f.writeSessionMetadata({...H??{},checkpoint:{latest:j,history:A}});return}}}import{spawn as iO}from"node:child_process";import{appendFileSync as nO,readFileSync as aO}from"node:fs";import{join as tO}from"node:path";import{augmentNodeCommandForDebug as FA,withResolvedClineBuildEnv as hZ}from"@cline/shared";import{ensureHookLogDir as PA}from"@cline/shared/storage";function G2(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as mO,readdirSync as vO}from"node:fs";import{basename as cO,extname as uO,join as dO}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as u6,resolveHooksConfigSearchPaths as lO}from"@cline/shared/storage";function KJ(f){return lO(f)}var F2;((Y)=>{Y.TaskStart="TaskStart";Y.TaskResume="TaskResume";Y.TaskCancel="TaskCancel";Y.TaskComplete="TaskComplete";Y.TaskError="TaskError";Y.PreToolUse="PreToolUse";Y.PostToolUse="PostToolUse";Y.UserPromptSubmit="UserPromptSubmit";Y.PreCompact="PreCompact";Y.SessionShutdown="SessionShutdown"})(F2||={});var PJ={["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"},pO=new Map(Object.values(F2).map((f)=>[f.toLowerCase(),f])),rO=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function GJ(f){let $=uO(f).toLowerCase();if(!rO.has($))return;let J=cO(f,$).trim().toLowerCase();return pO.get(J)}function D$(f){let $=[],J=new Set,Q=KJ(f).filter((Z)=>mO(Z));for(let Z of Q)try{for(let W of vO(Z,{withFileTypes:!0})){if(!W.isFile())continue;let j=GJ(W.name);if(!j)continue;let H=dO(Z,W.name);if(J.has(H))continue;J.add(H),$.push({fileName:j,hookEventName:PJ[j],path:H})}}catch{}return $.sort((Z,W)=>Z.path.localeCompare(W.path))}function l6(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,Q]of Object.entries(f))$[J]=typeof Q==="string"?Q:JSON.stringify(Q);return $}function d6(f,$,J){let Q=J instanceof Error?`: ${J.message}`:"",Z=`${$}${Q}`;if(f){try{f.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function sO(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
456
+ `),Q=[...f.appendMessages??[],...$.appendMessages??[]];return{cancel:f.cancel===!0||$.cancel===!0?!0:void 0,review:f.review===!0||$.review===!0?!0:void 0,context:J||void 0,overrideInput:$.overrideInput!==void 0?$.overrideInput:f.overrideInput,systemPrompt:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function oO(f){if(!f||typeof f!=="object")return;let $=f,J=typeof $.context==="string"?$.context:typeof $.contextModification==="string"?$.contextModification:typeof $.errorMessage==="string"?$.errorMessage:void 0;return{cancel:typeof $.cancel==="boolean"?$.cancel:void 0,review:typeof $.review==="boolean"?$.review:void 0,context:J,overrideInput:Object.hasOwn($,"overrideInput")?$.overrideInput:void 0}}function SZ(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function D0(f,$){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:$.rootSessionId||f.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:Q,workspaceRoots:$.workspacePath?[$.workspacePath]:[],workspaceInfo:$.workspaceInfo,userId:J,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function eO(f){let $=f.trim();if(!$)return{};let Q=$.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]:$;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse hook stdout JSON"}}}async function f_(f,$){let J=f.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((Q,Z)=>{let W=!1,j=()=>{J.off("error",X),J.off("finish",A),f.off("close",Y)},H=(V)=>{if(W)return;if(W=!0,j(),V){let B=V.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){Q();return}Z(V);return}Q()},X=(V)=>H(V),A=()=>H(),Y=()=>H();J.on("error",X),J.once("finish",A),f.once("close",Y);try{J.end($)}catch(V){H(V)}})}async function UA(f,$){if($.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await GA(f,$)}catch(J){let Q=Q_($.command,process.platform,J);if(!Q)throw J;return await GA(f,{...$,command:Q})}}async function GA(f,$){let J=FA($.command,{env:$.env,debugRole:"hook"}),Q=iO(J[0],J.slice(1),{cwd:$.cwd,env:hZ($.env),stdio:$.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:$.detached}),Z=new Promise((B)=>{Q.once("spawn",()=>B())}),W=new Promise((B,K)=>{Q.once("error",(P)=>K(P))}),j=JSON.stringify(f);if(await Promise.race([Z,W]),await f_(Q,j),$.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let H="",X="",A=!1,Y;Q.stdout.on("data",(B)=>{H+=B.toString()}),Q.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if(($.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,Q.kill("SIGKILL")},$.timeoutMs);Q.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:P,parseError:R}=eO(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:P,parseError:R,timedOut:A})})});return await Promise.race([V,W])}function $_(f){try{let J=aO(f,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let Q=J.slice(2).trim();if(!Q)return;let Z=Q.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function J_(f){return!!(f&&typeof f==="object"&&("code"in f)&&f.code==="ENOENT")}function Q_(f,$=process.platform,J){if($!=="win32"||!J_(J))return;if(f[0]!=="py"||f[1]!=="-3")return;return["python",...f.slice(2)]}function RA(f){if(f.length===0)return;let[$,...J]=f,Q=$.replace(/\\/g,"/").toLowerCase(),Z=Q.split("/").at(-1)??Q;if(Z==="env")return RA(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return f}function Z_(f){let $=$_(f);if($&&$.length>0)return[...RA($)??$,f];let J=f.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",f];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return FA(["node",f],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",f];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",f]:["python3",f];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",f];return["bash",f]}function W_(f){let $={};for(let J of D$(f)){if(!J.hookEventName)continue;let Q=J.hookEventName,Z=$[Q]??[];Z.push(Z_(J.path)),$[Q]=Z}return $}async function j_(f){let $;for(let J of f.commands){let Q=J.join(" ");try{let Z=await UA(f.payload,{command:J,cwd:f.cwd,env:hZ(process.env),detached:!1,timeoutMs:f.timeoutMs});if(Z?.timedOut){d6(f.logger,`hook command timed out: ${Q}`);continue}if(Z?.parseError){d6(f.logger,`hook command returned invalid JSON control output: ${Q} (${Z.parseError})`);continue}$=sO($,oO(Z?.parsedJson))}catch(Z){d6(f.logger,`hook command failed: ${Q}`,Z)}}return $}function A1(f){for(let $ of f.commands){let J=$.join(" ");UA(f.payload,{command:$,cwd:f.cwd,env:hZ(process.env),detached:!0}).catch((Q)=>{d6(f.logger,`hook command failed: ${J}`,Q)})}}function L$(f){return{agentId:f.agentId,conversationId:f.conversationId??f.runId??f.agentId,parentAgentId:f.parentAgentId??null}}function EZ(f,$){return{...L$(f.snapshot),userMessage:$}}function DA(f){return{...L$(f.snapshot),iteration:f.snapshot.iteration,call:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input}}}function LA(f){return{...L$(f.snapshot),iteration:f.snapshot.iteration,record:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}}function OA(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function H_(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}function U2(f){let $={cwd:f.workspacePath,workspacePath:f.workspacePath,rootSessionId:f.rootSessionId,workspaceInfo:f.workspaceInfo},J=(Q)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
458
+ `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??tO(PA(),"hooks.jsonl");PA(j),nO(j,Z,"utf8")};return{beforeRun:async(Q)=>{let Z=EZ(Q,"");J({...D0(Z,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let Z=DA(Q);J({...D0(Z,$),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:l6(Z.call.input)}});return},afterTool:async(Q)=>{let Z=LA(Q);J({...D0(Z,$),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:l6(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({...D0(W,$),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||SZ(Z.error?.message)){J({...D0(W,$),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...D0(W,$),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let Z=EZ({snapshot:Q.snapshot},OA(Q.message.content));J({...D0(Z,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function FJ(f){let $=W_(f.workspacePath);if(!Object.values($).some((V)=>V.length>0))return;let Q=async(V,B)=>{let K=$[B]??[];if(K.length===0)return;A1({commands:K,cwd:f.cwd,logger:f.logger,payload:B==="agent_resume"?{...D0(V,f),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...D0(V,f),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=$.prompt_submit??[];if(B.length>0)A1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...D0(V,f),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},W=async(V)=>{let B=$.tool_call??[];if(B.length===0)return;return j_({commands:B,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...D0(V,f),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:l6(V.call.input)}}})},j=async(V)=>{let B=$.tool_result??[];if(B.length===0)return;A1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...D0(V,f),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:l6(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},H=async(V)=>{let B=$.agent_end??[];if(B.length===0)return;A1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...D0(V,f),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},X=async(V)=>{let B=$.agent_error??[];if(B.length===0)return;A1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...D0(V,f),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},A=async(V)=>{if(SZ(V.reason)){let K=$.agent_abort??[];if(K.length>0)A1({commands:K,cwd:f.cwd,logger:f.logger,payload:{...D0(V,f),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=$.session_shutdown??[];if(B.length===0)return;A1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...D0(V,f),hookName:"session_shutdown",reason:V.reason}})},Y={};if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0||($.prompt_submit?.length??0)>0){if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0)Y.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(L$(V.snapshot),B);return};if(($.prompt_submit?.length??0)>0)Y.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(EZ({snapshot:V.snapshot},OA(V.message.content)))}}if(($.tool_call?.length??0)>0)Y.beforeTool=async(V)=>{let B=await W(DA(V));return H_(B)};if(($.tool_result?.length??0)>0)Y.afterTool=async(V)=>{await j(LA(V));return};if(($.agent_end?.length??0)>0)Y.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await H({...L$(V),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if(($.agent_error?.length??0)>0||($.agent_abort?.length??0)>0||($.session_shutdown?.length??0)>0){let V=Y.afterRun;Y.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:P}=B;if(P.status==="aborted"||SZ(P.error?.message)){await A({...L$(K),reason:P.error?.message});return}if(P.error)await X({...L$(K),iteration:P.iterations,error:P.error})}}return Y}function R2(f){return G2("core.hook_config_files",FJ(f))}function Y1(f,$){let J=f.map((Q)=>Q[$]).filter((Q)=>typeof Q==="function");if(J.length===0)return;return async(Q)=>{let Z;for(let W of J){let j=await W(Q);if(!j||typeof j!=="object")continue;let H=j;Z={...Z??{},...H,stop:Z?.stop===!0||H.stop===!0?!0:H.stop,options:Z?.options||H.options?{...Z?.options??{},...H.options??{}}:void 0}}return Z}}function V1(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:Y1($,"beforeRun"),afterRun:Y1($,"afterRun"),beforeModel:Y1($,"beforeModel"),afterModel:Y1($,"afterModel"),beforeTool:Y1($,"beforeTool"),afterTool:Y1($,"afterTool"),onEvent:Y1($,"onEvent")}}var _A={};q(_A,{normalizeRuntimeCapabilities:()=>L0});function L0(...f){let $,J;for(let Z of f){if(!Z)continue;if(Z.toolExecutors)$={...$??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let Q=$&&Object.keys($).length>0;if(!Q&&!J)return;return{...Q?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}var SA={};q(SA,{toProviderConfig:()=>d0,emptyStoredProviderSettings:()=>T$,StoredProviderSettingsSchema:()=>O2,StoredProviderSettingsEntrySchema:()=>K5,ProviderSettingsSchemaTyped:()=>_J});import{z as _$}from"zod";var CA={};q(CA,{toProviderConfig:()=>d0,safeParseSettings:()=>B5,safeCreateProviderConfig:()=>dZ,parseSettings:()=>V5,normalizeProviderId:()=>L2,isBuiltInProviderId:()=>cZ,createProviderConfig:()=>uZ,SapSettingsSchema:()=>X5,ReasoningSettingsSchema:()=>Z5,ProviderSettingsSchema:()=>O$,ProviderProtocolSchema:()=>$5,ProviderIdSchema:()=>OJ,ProviderClientSchema:()=>J5,OcaSettingsSchema:()=>A5,ModelCatalogSettingsSchema:()=>Y5,GcpSettingsSchema:()=>j5,BUILT_IN_PROVIDER_IDS:()=>vZ,BUILT_IN_PROVIDER:()=>LJ,AzureSettingsSchema:()=>H5,AwsSettingsSchema:()=>W5,AuthSettingsSchema:()=>Q5});import*as u0 from"@cline/llms";import{z as N}from"zod";var wA={};q(wA,{resolveProviderConfig:()=>DJ,getProviderConfig:()=>f5,getLiveModelsCatalog:()=>D2,clearPublicModelsCatalogCache:()=>y_,clearPrivateModelsCatalogCache:()=>mZ,clearLiveModelsCatalogCache:()=>gZ,OPENAI_COMPATIBLE_PROVIDERS:()=>RJ,DEFAULT_MODELS_CATALOG_URL:()=>t6});import*as X0 from"@cline/llms";function bZ(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter(($)=>$.length>0)}function X_(f,$){let J=bZ(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let Q=f,Z=bZ(Q.data??Q.models);if(Z.length>0)return Z;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let j=Object.keys(Q.models).filter((H)=>H.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[$];if(W&&typeof W==="object"){let H=bZ(W.models??W);if(H.length>0)return H}return[]}async function p6(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return X_(await J.json(),$)}function TA(f){return f.replace(/\/+$/,"")}function r6(f,$,J){let Q=J?.trim();if(!Q)return;let Z=f?.trim();if(!Z||!$?.trim())return Q;try{let W=new URL(Q),j=new URL($),H=new URL(Z);if(W.origin!==j.origin)return Q;let X=TA(j.pathname),A=TA(H.pathname);if(X&&W.pathname.startsWith(`${X}/`)){let Y=W.pathname.slice(X.length);H.pathname=`${A}${Y}`}else H.pathname=W.pathname;return H.search=W.search,H.hash=W.hash,H.toString()}catch{return Q}}function A_(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function Y_(f){if(f.baseUrl.length===0)return!1;switch(f.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return f.protocol==="openai-chat"}}var V_=Object.values(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:A_(f.models),capabilities:f.provider.capabilities?[...f.provider.capabilities]:void 0,env:f.provider.env?[...f.provider.env]:void 0,client:f.provider.client,protocol:f.provider.protocol})),MA=Object.fromEntries(V_.map((f)=>[f.id,f]));function B_(f){return MA[f]}function K_(){return Object.fromEntries(Object.entries(MA).filter(([,f])=>Y_(f)))}function NA(f=[]){let $=f.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return $.length>0?$:void 0}var t6="https://models.dev/api.json",P_=600000,qA=300000,G_=5000,a6=new Map,UJ=new Map,kZ=new Map,i6=new Map;async function F_(){return X0.getGeneratedProviderModels()}async function U_(f,$={},J={},Q={},Z={},W={}){let j=await F_(),H=X0.resolveProviderModelCatalogKeys(f),X=Object.assign({},...H.map((V)=>j[V]??{})),A=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),Y=Object.keys(Z).length>0;if(A&&Y)return X0.sortModelsByReleaseDate({...Z,...W});if(f==="openai-codex")return X0.sortModelsByReleaseDate({...$,...X0.filterOpenAICodexModels(J),...Z,...W});return X0.sortModelsByReleaseDate({...X,...$,...J,...Q,...Z,...W})}function R_(f,$){let J=X0.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((Q)=>$[Q]??{}))}function s6(f){let $=f?.trim();return $&&$.length>0?$:""}function xZ(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function D_(f){let $=2166136261;for(let J=0;J<f.length;J+=1)$^=f.charCodeAt(J),$+=($<<1)+($<<4)+($<<7)+($<<8)+($<<24);return($>>>0).toString(16)}function L_(f,$){return`${f}:${s6($.baseUrl)}:${D_(xZ($)??"")}`}async function o6(f,$,J=G_){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch(f,{...$,signal:Q.signal})}finally{clearTimeout(Z)}}function B1(f,$,J){if(J&&!f.includes($))f.push($)}function e6(f,$){let J=["streaming","tools"];return B1(J,"images",Boolean($.supportsImages)),B1(J,"prompt-cache",Boolean($.supportsPromptCache)),B1(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxInputTokens:$.maxInputTokens,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}async function O_(f,$){let J=await o6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let H=j.id?.trim();if(!H)continue;if(H.includes("whisper")||H.includes("tts")||H.includes("embedding"))continue;let X=j.supported_features??[];W[H]=e6(H,{name:H,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return W}function zA(f){if(typeof f==="number")return Number.isFinite(f)?f:void 0;if(typeof f==="string"){let $=Number(f);return Number.isFinite($)?$:void 0}return}async function __(f,$){let J=await o6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":$}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let H=j.id?.trim();if(!H)continue;W[H]=e6(H,{name:H,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}async function T_(f,$){let Q=`${(s6(f.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await o6(Q,{method:"GET",headers:{Authorization:`Bearer ${$}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],H={};for(let X of j){let A=X.id?.trim();if(!A)continue;let Y=X.supported_features??[],V=X.supported_sampling_parameters??[],B=X.input_modalities??[],K=["streaming"];B1(K,"tools",Y.includes("tools")),B1(K,"reasoning",Y.includes("reasoning")),B1(K,"temperature",V.includes("temperature")),B1(K,"images",B.includes("image"));let P={input:zA(X.pricing?.prompt),output:zA(X.pricing?.completion)};H[A]={id:A,name:X.name??A,description:X.description,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,capabilities:K,pricing:P.input!==void 0||P.output!==void 0?P:void 0,status:"active"}}return H}function z_(f){let $=s6(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function M_(f,$){let Q=`${z_(f.baseUrl)}/v1/model/info`,Z=async(A)=>o6(Q,{method:"GET",headers:{accept:"application/json",...A}}),W=await Z({"x-litellm-api-key":$});if(!W.ok)W=await Z({Authorization:`Bearer ${$}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let H=(await W.json())?.data??[],X={};for(let A of H){let Y=A.model_name?.trim(),B=A.litellm_params?.model?.trim()||Y;if(!B)continue;let K=A.model_info,P=e6(B,{name:Y??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(X[B]=P,Y)X[Y]={...P,id:Y,name:Y}}return X}var yA={baseten:O_,hicap:__,litellm:M_,poolside:T_},IZ=new Map,n6=new Map;function N_(f,$){return`${f}:${s6($.baseUrl)}`}async function q_(f,$,J){let Q=X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=r6(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=$?.cacheTtlMs??qA,j=N_(f,J),H=Date.now(),X=IZ.get(j);if(X&&X.expiresAt>H)return X.data;let A=n6.get(j);if(A)return A;let Y=p6(Z,f).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,e6(K,{name:K})]));return IZ.set(j,{data:B,expiresAt:H+W}),B}).finally(()=>{n6.delete(j)});return n6.set(j,Y),Y}function y_(){IZ.clear(),n6.clear()}async function w_(f,$){let J=xZ($);if(!J)return{};let Q=yA[f];if(!Q)return{};return Q($,J)}function C_(f,$,J){if(!J)return!1;if(!yA[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(xZ(J))}async function S_(f,$,J){let Q=$?.cacheTtlMs??qA,Z=L_(f,J),W=Date.now(),j=kZ.get(Z);if(j&&j.expiresAt>W)return j.data;let H=i6.get(Z);if(H)return H;let X=w_(f,J).then((A)=>{return kZ.set(Z,{data:A,expiresAt:W+Q}),A}).finally(()=>{i6.delete(Z)});return i6.set(Z,X),X}async function E_(f){return X0.fetchModelsDevProviderModels(f,globalThis.fetch)}async function D2(f={}){let $=f.url??t6,J=f.cacheTtlMs??P_,Q=Date.now(),Z=a6.get($);if(Z&&Z.expiresAt>Q)return Z.data;let W=UJ.get($);if(W)return W;let j=E_($).then((H)=>{return a6.set($,{data:H,expiresAt:Q+J}),H}).finally(()=>{UJ.delete($)});return UJ.set($,j),j}function gZ(f){if(f){a6.delete(f),UJ.delete(f);return}a6.clear(),UJ.clear()}function mZ(){kZ.clear(),i6.clear()}function h_(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:NA(J.capabilities)}]))}var RJ=h_(K_());function f5(f){let $=B_(f);if(!$)return;return{baseUrl:$.baseUrl||void 0,modelId:$.modelId,knownModels:$.knownModels,capabilities:NA($.capabilities)}}async function DJ(f,$,J){let Q=f5(f);if(!Q)return;try{let Z=$?.loadLatestOnInit?await D2($):void 0,W=Z?R_(f,Z):{},j=J&&C_(f,$,J)?await S_(f,$,J):{},X=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,A=X?await q_(f,$,X).catch(()=>({})):{},Y=await U_(f,Q.knownModels,W,j,A,J?.knownModels);return{...Q,knownModels:Y}}catch(Z){if($?.failOnError)throw Z;return Q}}var LJ=u0.BUILT_IN_PROVIDER,vZ=u0.BUILT_IN_PROVIDER_IDS,cZ=u0.isBuiltInProviderId,L2=u0.normalizeProviderId,OJ=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),$5=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),J5=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),Q5=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),b_=N.enum(["none","low","medium","high","xhigh"]),Z5=N.object({enabled:N.boolean().optional(),effort:b_.optional(),budgetTokens:N.number().int().positive().optional()}),W5=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()}),j5=N.object({projectId:N.string().optional(),region:N.string().optional()}),H5=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),X5=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()}),A5=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),Y5=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:OJ,apiKey:N.string().optional(),auth:Q5.optional(),model:N.string().optional(),protocol:$5.optional(),client:J5.optional(),routingProviderId:OJ.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:Z5.optional(),aws:W5.optional(),gcp:j5.optional(),azure:H5.optional(),sap:X5.optional(),oca:A5.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:Y5.optional()});function V5(f){return O$.parse(f)}function B5(f){return O$.safeParse(f)}function k_(f){return f.protocol==="openai-responses"||f.client==="openai"}function d0(f,$={}){let J=f.provider,Q=L2(J),Z=$.includeKnownModels!==!1,W=f.reasoning?.effort||"none",j=W==="none"?void 0:W,H=RJ[Q],X=Object.assign({},...u0.resolveProviderModelCatalogKeys(Q).map((R)=>u0.getGeneratedModelsForProvider(R))),A=Object.keys(X)[0],Y=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,V=f.baseUrl??(Q==="oca"?f.oca?.mode==="internal"?V6:B6:H?.baseUrl),B=f.routingProviderId??(k_(f)&&Q!==LJ.OPENAI_NATIVE?LJ.OPENAI_NATIVE:void 0),K=Z?H?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,P={providerId:J,clientType:f.client,routingProviderId:B,modelId:f.model??H?.modelId??A??"default",...Z?{knownModels:K}:{},apiKey:Y,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:V,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxInputTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:f.reasoning?.budgetTokens,region:f.region??f.aws?.region??f.gcp?.region,apiLine:f.apiLine,useCrossRegionInference:f.aws?.useCrossRegionInference,useGlobalInference:f.aws?.useGlobalInference,aws:f.aws?{accessKey:f.aws.accessKey,secretKey:f.aws.secretKey,sessionToken:f.aws.sessionToken,authentication:f.aws.authentication,profile:f.aws.profile,usePromptCache:f.aws.usePromptCache,endpoint:f.aws.endpoint,customModelBaseId:f.aws.customModelBaseId}:void 0,gcp:f.gcp?{projectId:f.gcp.projectId,region:f.gcp.region}:void 0,azure:f.azure,sap:f.sap,oca:f.oca,capabilities:f.capabilities??H?.capabilities,modelCatalog:f.modelCatalog?{loadLatestOnInit:f.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:f.modelCatalog.loadPrivateOnAuth,url:f.modelCatalog.url,cacheTtlMs:f.modelCatalog.cacheTtlMs,failOnError:f.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(P).filter(([R,G])=>G!==void 0))}function uZ(f){let $=V5(f);return d0($)}function dZ(f){let $=B5(f);if($.success)return{success:!0,config:d0($.data)};return{success:!1,error:$.error}}var _J=O$;var K5=_$.object({settings:O$,updatedAt:_$.string().datetime(),tokenSource:_$.enum(["manual","oauth","migration"]).default("manual")}),O2=_$.object({version:_$.literal(1),lastUsedProvider:_$.string().min(1).optional(),providers:_$.record(_$.string(),K5)});function T$(){return{version:1,providers:{}}}jf();var EA={};q(EA,{InMemoryWorkspaceManager:()=>_2});import{upsertWorkspaceInfo as I_,WorkspaceManifestSchema as lZ}from"@cline/shared";class _2{manifest;listeners=new Set;constructor(f){this.manifest=lZ.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await I1(f);return this.manifest=I_(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=Mf(f),J=this.manifest.workspaces[$];if(J)return this.manifest=lZ.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath($);return this.manifest=lZ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}getCurrentWorkspace(){let f=this.manifest.currentWorkspacePath;if(!f)return;return this.manifest.workspaces[f]}getWorkspace(f){let $=Mf(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}O0();import{createHash as x_}from"node:crypto";var hA=new Set,bA=new Set;function g_(f){return x_("sha256").update(f).digest("hex")}function m_(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function kA(f){if(!f.telemetry)return;let $=g_(f.rootPath),J=f.rootCount??1;if(!hA.has($))hA.add($),q4(f.telemetry,{root_count:J,vcs_types:m_(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!bA.has($)){bA.add($);let Q=Error(f.initError.message);Q.name=f.initError.errorType||"Error",y4(f.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function c_(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function u_(f,$,J){if($.length>0)for(let W of $)J?.log(W.message,{severity:"warn"});if(f.length===0)return;let Q=f.slice(0,3).map(c_).join("; "),Z=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of f)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function d_(f,$){let J=typeof f.thinking==="boolean",Q=typeof f.reasoningEffort==="string";if(!J&&!Q)return $;return{...$??{},...J?{enabled:f.thinking}:{},...Q?{effort:f.reasoningEffort}:{}}}function IA(f,$){return v_(f,$)}function l_(f){let $=0;for(let J of f??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;$+=1}return $}function p_(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||r_(f.accessToken);if($.originator="cline",$.session_id=f.sessionId,$["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)$["ChatGPT-Account-Id"]=J;return $}function r_(f){let $=f?.trim();if(!$)return;let J=z0($),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 i_(f,$,J,Q,Z){let W=J.getProviderSettings(f.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,H=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0,X={...W??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.providerId==="openai-codex"?p_({sessionId:$,configHeaders:f.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:f.apiKey??W?.auth?.accessToken??W?.apiKey}):f.headers??W?.headers,reasoning:d_(f,W?.reasoning),modelCatalog:j},A={...d0(X),...H??{}};if(f.knownModels)A.knownModels=f.knownModels;if(f.extensionContext)A.extensionContext=f.extensionContext;let V=f.fetch??A.fetch??Z;if(V)A.fetch=V;return A}async function xA(f){let{input:$,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:H,onPluginEvent:X,onTeamEvent:A,createSubAgentLifecycleCallbacks:Y,createSpawnTool:V,localRuntime:B,readSessionMetadata:K,writeSessionMetadata:P}=f,R=U$($.config),{modelCatalogDefaults:G,userInstructionService:F,configExtensions:U,onTeamRestored:_,...M}=B??{},L=Object.keys(M).length>0?M:void 0,{workspaceInfo:D,workspaceMetadata:y,durationMs:b,vcsType:I,initError:o}=await E9(R),A0=L?.extensionContext,f0={...A0??{},workspace:{...D,...A0?.workspace??{}},session:{...A0?.session??{},sessionId:J},logger:A0?.logger??L?.logger,telemetry:A0?.telemetry??L?.telemetry??Z};kA({telemetry:f0.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:I,durationMs:b,initError:o,featureFlagEnabled:!0});let t=R2({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:L?.logger,workspaceInfo:D}),s0=kX(L?.hooks)?void 0:U2({rootSessionId:J,workspacePath:R,workspaceInfo:D}),E$=V1([L?.hooks,s0]),i;if(IA(U,"plugins"))try{i=await P2({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:X,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:D,session:f0.session,client:f0.client,user:f0.user,logger:f0.logger,telemetry:f0.telemetry,automation:f0.automation}),u_(i.failures,i.warnings,L?.logger)}catch(E1){let y9=E1 instanceof Error?E1.message:String(E1);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${y9})`)}let w=XZ(t?[t]:void 0,XZ(L?.extensions,n4(i?.extensions))),P0=IA(U,"plugins")?H1(i?.pluginPaths??[]):void 0,Q0={...$.config,...L??{},sessionId:J,hooks:E$,extensions:w,extensionContext:f0,telemetry:f0.telemetry},y0=i_(Q0,J,Q,G,H),C1=V1([Q0.hooks,Q0.checkpoint?.enabled===!0?KA({cwd:Q0.cwd,sessionId:J,logger:Q0.logger,createCheckpoint:Q0.checkpoint?.createCheckpoint,initialRunCount:l_($.initialMessages),readSessionMetadata:K,writeSessionMetadata:P}):void 0]),_f={...Q0,providerConfig:y0,workspaceMetadata:y,hooks:C1},Zf=$.toolPolicies??Q0.toolPolicies??j,t2=L0(W,$.capabilities),S1=t2?.requestToolApproval,R4=t2?.toolExecutors,Tf=Y?.(_f),D4=new _2({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:$,config:_f,providerConfig:y0,workspaceMetadata:y,workspaceInfo:D,extensions:w,hooks:C1,toolPolicies:Zf,requestToolApproval:S1,pluginSandboxShutdown:i?.shutdown,runtimeBuilderInput:{config:_f,hooks:C1,extensions:w,onTeamEvent:A,createSpawnTool:V,onTeamRestored:_,onSubAgentEvent:Tf?.onSubAgentEvent,onSubAgentStart:Tf?.onSubAgentStart,onSubAgentEnd:Tf?.onSubAgentEnd,userInstructionService:F,pluginSkillDirectories:P0,configExtensions:U,toolExecutors:R4,toolPolicies:Zf,workspaceManager:D4,logger:_f.logger,telemetry:_f.telemetry,requestToolApproval:S1}}}import{existsSync as G5,mkdirSync as n_,readdirSync as a_,rmdirSync as t_,rmSync as s_,unlinkSync as o_}from"node:fs";import{dirname as gA,join as P5}from"node:path";function s(){return new Date().toISOString()}function TJ(f){if(!f||!G5(f))return;try{o_(f)}catch{}}function e_(f){let $=H2(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=$J(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class pZ{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return P5(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!G5($))n_($,{recursive:!0});return $}sessionMessagesPath(f){return P5(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return P5(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!G5($)){$=gA($);continue}try{if(a_($).length>0)break;t_($)}catch{break}$=gA($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!G5(f))return;try{s_(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:Q,fileStem:Z}=e_(f),W=this.sessionArtifactsDir(Q);return{messagesPath:P5(W,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as fT}from"@cline/shared/storage";O0();function mA(f,$,J,Q,Z){if(J)C4(f.telemetry,{ulid:$,apiProvider:f.providerId,...Z});else w4(f.telemetry,{ulid:$,apiProvider:f.providerId,...Z});$T(f.telemetry,{workspacePath:Q})}function $T(f,$){let J=fT("Hooks"),Q=D$($.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",H=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))H.global+=1;else H.workspace+=1;Z.set(j,H)}for(let[W,j]of Z.entries())v4(f,W,j.global,j.workspace)}function vA(f,$){for(let J of $.mentions)g4(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)I4(f,"file",J.length);for(let J of $.ignoredMentions)x4(f,"file","not_found",J)}var rB={};q(rB,{ProviderSettingsManager:()=>Lf});import{chmodSync as oB,existsSync as b7,mkdirSync as AC,readFileSync as YC,writeFileSync as VC}from"node:fs";import{basename as eB,dirname as k7}from"node:path";import{resolveProviderSettingsPath as BC}from"@cline/shared/storage";var T={};q(T,{writeHubDiscovery:()=>o4,writeGlobalSettings:()=>Cf,withHubStartupLock:()=>e4,verifyHubConnection:()=>Af,updateMcpServerOAuthState:()=>U1,updateLocalProvider:()=>A9,uninstallPlugin:()=>J7,truncateNotificationBody:()=>V4,toggleDisabledTool:()=>r4,toTeamProgressLifecycleEvent:()=>k2,toProviderConfig:()=>d0,toHubHealthUrl:()=>t9,toHookConfigFileName:()=>GJ,summarizeUsageFromMessages:()=>A2,stopLocalHubServerGracefully:()=>XQ,startLocalOAuthServer:()=>ff,startHubWebSocketServer:()=>P4,startHubServer:()=>aB,startClineDeviceAuth:()=>RQ,splitCoreSessionConfig:()=>P8,spawnDetachedHubServerWithRetry:()=>l1,spawnDetachedHubServer:()=>JQ,setTelemetryOptOutGlobally:()=>b3,setMcpServerDisabled:()=>G1,setDisabledTools:()=>d9,setDisabledPlugin:()=>v3,setAutoUpdateEnabledGlobally:()=>I3,sendHubCommand:()=>Kj,saveProviderOAuthCredentials:()=>l$,saveLocalProviderSettings:()=>Y7,saveLocalProviderOAuthCredentials:()=>P7,sanitizeSessionToken:()=>J1,safeParseSettings:()=>B5,safeCreateProviderConfig:()=>dZ,runSubprocessEvent:()=>m2,runHook:()=>c2,reviveTeamStateDates:()=>y6,restartLocalHubIfIdleAfterStartupTimeout:()=>J6,resolveWorkspaceHubOwnerContext:()=>$j,resolveWorkflowsConfigSearchPaths:()=>bJ,resolveSkillsConfigSearchPaths:()=>EJ,resolveSharedHubOwnerContext:()=>F0,resolveSessionBackend:()=>xW,resolveRulesConfigSearchPaths:()=>hJ,resolveProviderConfig:()=>DJ,resolveProviderApiKeyFromSettings:()=>zQ,resolvePluginSkillDirectoriesFromPaths:()=>H1,resolvePluginConfigSearchPaths:()=>VJ,resolveMcpServerRegistrations:()=>Bf,resolveLocalClineAuthToken:()=>F7,resolveHubUrl:()=>AQ,resolveHubOwnerContext:()=>bf,resolveHubEndpointOptions:()=>Xf,resolveHubBuildId:()=>J$,resolveHooksConfigSearchPaths:()=>KJ,resolveDisabledToolNames:()=>Wf,resolveDisabledPluginPaths:()=>A8,resolveDefaultMcpSettingsPath:()=>M0,resolveDefaultHubPort:()=>d1,resolveDefaultHubPathname:()=>$Q,resolveDefaultHubHost:()=>fQ,resolveCoreSelectedToolIds:()=>C6,resolveCompatibleLocalHubUrl:()=>L8,resolveClineDir:()=>s3,resolveClineDataDir:()=>F8,resolveAndLoadAgentPlugins:()=>P2,resolveAgentPluginPaths:()=>j1,requestHubShutdown:()=>D8,requestDesktopToolApproval:()=>nW,rememberRecoverableLocalHubUrl:()=>Q$,registerRemoteConfigSessionBlobUpload:()=>s5,registerMcpServersFromSettingsFile:()=>R1,registerDisposable:()=>WC,refreshProviderModelsFromSource:()=>V7,refreshOpenAICodexToken:()=>Y6,refreshOcaToken:()=>P6,refreshClineToken:()=>X6,readSessionCheckpointHistory:()=>A4,readRemoteConfigSessionBlobUploadMetadata:()=>mW,readHubDiscovery:()=>V0,readGlobalSettings:()=>_0,probeHubServer:()=>Hf,probeHubConnection:()=>Bj,prewarmFileIndex:()=>O6,prewarmDetachedHubServer:()=>f6,prepareRemoteConfigCoreIntegration:()=>cW,parseWorkflowConfigFromMarkdown:()=>SJ,parseUserCommandEnvelope:()=>ZC,parseSkillConfigFromMarkdown:()=>wJ,parseSettings:()=>V5,parseRuleConfigFromMarkdown:()=>CJ,parseHookEventPayload:()=>v2,parseConfiguredAgentConfig:()=>oJ,normalizeWorkspacePath:()=>Mf,normalizeUserInput:()=>QC,normalizeSdkError:()=>JC,normalizeRuntimeCapabilities:()=>L0,normalizeProviderId:()=>L2,normalizeOAuthProvider:()=>B7,normalizeHubWebSocketUrl:()=>Z$,noopBasicLogger:()=>$C,migrateLegacyProviderSettings:()=>X4,mergeRulesForSystemPrompt:()=>k1,mergeAgentHooks:()=>V1,makeTeamTaskSubSessionId:()=>fJ,makeSubSessionId:()=>j2,loginOpenAICodex:()=>T8,loginOcaOAuth:()=>N8,loginLocalProvider:()=>K7,loginClineOAuth:()=>O8,loginAndSaveProviderOAuthCredentials:()=>y8,loginAndSaveLocalProviderOAuthCredentials:()=>G7,loadOpenTelemetryAdapter:()=>dw,loadMcpSettingsFile:()=>P1,loadLlmsConfigFromFile:()=>S7,loadConfiguredAgentConfigs:()=>E2,loadAgentPluginsFromPathsWithDiagnostics:()=>W1,loadAgentPluginsFromPaths:()=>k6,loadAgentPluginFromPath:()=>AJ,listSessionHistoryFromBackend:()=>UW,listPluginToolsWithDiagnostics:()=>h5,listPluginTools:()=>dJ,listMcpServerOAuthStatuses:()=>cJ,listLocalProviders:()=>X7,listHookConfigFiles:()=>D$,isToolDisabledGlobally:()=>x3,isTelemetryOptedOutGlobally:()=>p4,isSessionNotFoundError:()=>hf,isRuleEnabled:()=>O4,isPluginDisabledGlobally:()=>m3,isOAuthProvider:()=>d$,isHubReconnectableTransportError:()=>jQ,isHubCommandTimeoutError:()=>$6,isDiscoveryFilePresent:()=>e3,isClineAccountActionRequest:()=>F5,isBuiltInProviderId:()=>cZ,isAutoUpdateEnabledGlobally:()=>k3,identifyAccount:()=>wf,hasMcpSettingsFile:()=>df,getValidOpenAICodexCredentials:()=>z8,getValidOcaCredentials:()=>q8,getValidClineCredentials:()=>_8,getProviderOAuthCredentialsFromSettings:()=>w8,getProviderConfigFields:()=>U7,getProviderConfig:()=>f5,getProviderAuthStorageId:()=>TQ,getProviderAuthHandler:()=>B0,getPersistedProviderApiKey:()=>F6,getMcpServerOAuthState:()=>F1,getLocalProviderModels:()=>A7,getLiveModelsCatalog:()=>D2,getFileIndex:()=>gf,getCurrentContextSize:()=>BZ,getCoreHeadlessToolNames:()=>e8,getCoreDefaultEnabledToolIds:()=>w6,getCoreBuiltinToolCatalog:()=>f1,getCoreAcpToolNames:()=>S6,getClineDefaultSystemPrompt:()=>pw,generateWorkspaceInfoWithDiagnostics:()=>o2,generateWorkspaceInfo:()=>I1,formatRulesForSystemPrompt:()=>b1,formatProviderOAuthApiKey:()=>MQ,formatDisplayUserInput:()=>fC,filterExtensionToolRegistrations:()=>n4,filterDisabledTools:()=>x$,filterDisabledPluginPaths:()=>i4,fetchClineRecommendedModels:()=>w7,executeClineAccountAction:()=>U5,ensureHubWebSocketServer:()=>O9,ensureHubServer:()=>tB,ensureDetachedHubServer:()=>Qj,ensureCustomProvidersLoaded:()=>j9,ensureCompatibleLocalHubUrl:()=>c$,enrichPromptWithMentions:()=>e1,emptyWorkspaceManifest:()=>ew,emptyStoredProviderSettings:()=>T$,discoverPluginModulePaths:()=>BJ,deriveSubsessionStatus:()=>JJ,deleteLocalProvider:()=>Y9,defineLlmsConfig:()=>C7,createWorkflowsConfigDefinition:()=>xJ,createUserInstructionConfigService:()=>z$,createToolPoliciesWithPreset:()=>T6,createTool:()=>ow,createTeamName:()=>f9,createSubprocessHooks:()=>n5,createSpawnAgentTool:()=>G$,createSkillsConfigDefinition:()=>kJ,createSessionHost:()=>g2,createRuntimeHost:()=>g2,createRulesConfigDefinition:()=>IJ,createRemoteConfigSessionMessagesArtifactUploader:()=>vW,createProviderConfig:()=>uZ,createOpenTelemetryTelemetryService:()=>K8,createOAuthClientCallbacks:()=>T2,createMcpTools:()=>y2,createLocalHubScheduleRuntimeHandlers:()=>nB,createLlmsSdk:()=>h7,createInitialAccumulatedUsage:()=>K0,createInMemoryHubOwnerContext:()=>o3,createHubServerUrl:()=>o0,createHubAuthToken:()=>s4,createHookConfigFileHooks:()=>FJ,createHookConfigFileExtension:()=>R2,createHookAuditHooks:()=>U2,createDisabledMcpToolPolicy:()=>uJ,createDisabledMcpToolPolicies:()=>E5,createDelegatedAgentConfigProvider:()=>K$,createDelegatedAgent:()=>P$,createDefaultToolsWithPreset:()=>z6,createDefaultTools:()=>Y$,createDefaultMcpServerClientFactory:()=>q2,createDefaultExecutors:()=>f2,createCoreSettingsService:()=>L1,createCoreSessionSnapshot:()=>Pf,createContributionRegistry:()=>sw,createContextCompactionPrepareTurn:()=>k8,createConfiguredTelemetryService:()=>Sf,createConfiguredTelemetryHandle:()=>u1,createConfiguredAgentTools:()=>h2,createClineTelemetryServiceMetadata:()=>tw,createClineTelemetryServiceConfig:()=>aw,createBuiltinTools:()=>$1,createAgentTeamsTools:()=>e$,createAgentRuntime:()=>XC,createAgentHooksExtension:()=>G2,connectToHub:()=>Q6,completeClineDeviceAuth:()=>DQ,clearPrivateModelsCatalogCache:()=>mZ,clearLiveModelsCatalogCache:()=>gZ,clearHubDiscovery:()=>x0,captureWorkspacePathResolved:()=>y3,captureWorkspaceInitialized:()=>q4,captureWorkspaceInitError:()=>y4,captureToolUsage:()=>h4,captureTokenUsage:()=>S4,captureTaskRestarted:()=>C4,captureTaskCreated:()=>w4,captureTaskCompleted:()=>W8,captureSubagentExecution:()=>H8,captureSkillUsed:()=>b4,captureSdkError:()=>nw,captureProviderConfigured:()=>w3,captureProviderApiError:()=>j8,captureModeSwitch:()=>E4,captureMentionUsed:()=>I4,captureMentionSearchResults:()=>g4,captureMentionFailed:()=>x4,captureHookDiscovery:()=>v4,captureExtensionActivated:()=>q3,captureDiffEditFailure:()=>k4,captureConversationTurnEvent:()=>g1,captureCompactionSkipped:()=>u4,captureCompactionExecuted:()=>c4,captureAuthSucceeded:()=>qf,captureAuthStarted:()=>Nf,captureAuthLoggedOut:()=>f$,captureAuthFailed:()=>yf,captureAgentTeamCreated:()=>m4,captureAgentCreated:()=>$$,buildWorkspaceMetadata:()=>e2,buildTeamProgressSummary:()=>b2,buildSdkErrorProperties:()=>rw,buildRemoteConfigSessionBlobUploadMetadata:()=>a5,buildDelegatedAgentConfig:()=>s$,buildConfiguredAgentToolName:()=>eJ,buildConfiguredAgentToolDescriptors:()=>f4,bootstrapAgentTeams:()=>W2,authorizeMcpServerOAuth:()=>w5,addLocalProvider:()=>H7,accumulateUsageTotals:()=>H0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>yJ,UnifiedConfigFileWatcher:()=>K1,ToolPresets:()=>c0,TelemetryService:()=>v1,TelemetryLoggerSink:()=>B8,TEAM_TOOL_NAMES:()=>Z2,SubprocessSandbox:()=>B2,StoredProviderSettingsSchema:()=>O2,StoredProviderSettingsEntrySchema:()=>K5,SqliteTeamStore:()=>M1,SqliteSessionStore:()=>Ff,SessionVersioningService:()=>C$,SessionVersioningError:()=>h0,SessionSource:()=>U0,SessionNotFoundError:()=>Ef,SapSettingsSchema:()=>X5,SKILLS_CONFIG_DIRECTORY_NAME:()=>qJ,SESSION_STATUSES:()=>QJ,SESSION_NOT_FOUND_ERROR_CODE:()=>m$,SDK_ERROR_TELEMETRY_EVENT:()=>jC,RpcClineAccountService:()=>MJ,RemoteRuntimeHost:()=>S2,ReasoningSettingsSchema:()=>Z5,RULES_CONFIG_DIRECTORY_NAME:()=>z5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>t5,ProviderSettingsSchema:()=>O$,ProviderSettingsManager:()=>Lf,ProviderProtocolSchema:()=>$5,ProviderIdSchema:()=>OJ,ProviderClientSchema:()=>J5,OpenTelemetryProvider:()=>c1,OcaSettingsSchema:()=>A5,OPENAI_COMPATIBLE_PROVIDERS:()=>RJ,NodeHubClient:()=>e0,NativeHubTransportAdapter:()=>K4,ModelCatalogSettingsSchema:()=>Y5,LocalRuntimeHost:()=>Df,Llms:()=>lw,InMemoryWorkspaceManager:()=>_2,InMemoryMcpManager:()=>D1,HubUIClient:()=>BQ,HubTransportError:()=>T0,HubSessionClient:()=>VQ,HubServerTransport:()=>a2,HubScheduleService:()=>x1,HubScheduleCommandService:()=>h1,HubRuntimeHost:()=>lf,HubCommandError:()=>p1,HookEventPayloadSchema:()=>i5,HookEventNameSchema:()=>r5,HookConfigFileName:()=>F2,HOOK_CONFIG_FILE_EVENT_MAP:()=>PJ,HOOKS_CONFIG_DIRECTORY_NAME:()=>u6,GlobalSettingsSchema:()=>X8,GcpSettingsSchema:()=>j5,FileTeamPersistenceStore:()=>P9,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>L9,DefaultToolNames:()=>Y0,DefaultRuntimeBuilder:()=>l2,DefaultLlmsSdk:()=>Y4,DEFAULT_MODELS_CATALOG_URL:()=>t6,DEFAULT_HUB_PORT:()=>o9,DEFAULT_HUB_PATHNAME:()=>e9,DEFAULT_HUB_HOST:()=>s9,CoreSettingsService:()=>M$,CoreSessionService:()=>Rf,ContributionRegistry:()=>iw,ClineCore:()=>W4,ClineAccountService:()=>zJ,ChatViewStateSchema:()=>q7,ChatSummarySchema:()=>D9,ChatSessionStatusSchema:()=>F9,ChatSessionConfigSchema:()=>G9,ChatMessageSchema:()=>R9,ChatMessageRoleSchema:()=>U9,CORE_TELEMETRY_EVENTS:()=>m,CORE_BUILD_VERSION:()=>y7,BrowserWebSocketHubAdapter:()=>B4,BUILT_IN_PROVIDER_IDS:()=>vZ,BUILT_IN_PROVIDER:()=>LJ,AzureSettingsSchema:()=>H5,AwsSettingsSchema:()=>W5,AuthSettingsSchema:()=>Q5,AgentTeamsRuntime:()=>_1,AgentTeam:()=>x2,Agent:()=>HC,ALL_DEFAULT_TOOL_NAMES:()=>sf});z(T,kd);import*as lw from"@cline/llms";import{buildClineSystemPrompt as pw,buildSdkErrorProperties as rw,ContributionRegistry as iw,captureSdkError as nw,createClineTelemetryServiceConfig as aw,createClineTelemetryServiceMetadata as tw,createContributionRegistry as sw,createTool as ow,emptyWorkspaceManifest as ew,formatDisplayUserInput as fC,noopBasicLogger as $C,normalizeSdkError as JC,normalizeUserInput as QC,parseUserCommandEnvelope as ZC,registerDisposable as WC,SDK_ERROR_TELEMETRY_EVENT as jC}from"@cline/shared";import"@cline/shared/storage";var uA={};q(uA,{isClineAccountActionRequest:()=>F5,executeClineAccountAction:()=>U5,RpcClineAccountService:()=>MJ,ClineAccountService:()=>zJ});function JT(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function cA(f,$,J){let Q=JT(J);if(Q)return Q;let Z=$.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${f}: ${W}`}return`Cline account request failed with status ${f}`}class zJ{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(f){let $=f.apiBaseUrl.trim();if(!$)throw Error("apiBaseUrl is required");this.apiBaseUrl=$,this.getAuthTokenFn=f.getAuthToken,this.getCurrentUserIdFn=f.getCurrentUserId,this.getOrganizationMemberIdFn=f.getOrganizationMemberId,this.getHeadersFn=f.getHeaders,this.requestTimeoutMs=f.requestTimeoutMs??30000,this.fetchImpl=f.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance(f){let $=await this.resolveUserId(f);return this.request(`/api/v1/users/${encodeURIComponent($)}/balance`)}async fetchUsageTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/usages`)).items??[]}async fetchPaymentTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}`)}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}/balance`)}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId($,f.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent($)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount(f){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:f?.trim()||null},expectNoContent:!0})}async resolveUserId(f){let $=f?.trim();if($)return $;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId(f,$){let J=$?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((H)=>H.organizationId===f)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);return j}async request(f,$){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,W=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:Z.signal});if(j.status===204||$?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let H=await j.text(),X;if(H.trim())try{X=JSON.parse(H)}catch{if(!j.ok)throw Error(cA(j.status,H,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(cA(j.status,H,X));if(typeof X==="object"&&X!==null){let A=X;if(typeof A.success==="boolean"){if(!A.success)throw Error(A.error||"Cline account request failed");if(A.data!==void 0)return A.data}}if(X===void 0||X===null)throw Error("Cline account response payload was empty");return X}finally{clearTimeout(W)}}}function F5(f){return f.action==="clineAccount"}async function U5(f,$){switch(f.operation){case"fetchMe":return $.fetchMe();case"fetchBalance":return $.fetchBalance(f.userId);case"fetchUsageTransactions":return $.fetchUsageTransactions(f.userId);case"fetchPaymentTransactions":return $.fetchPaymentTransactions(f.userId);case"fetchUserOrganizations":return $.fetchUserOrganizations();case"fetchOrganizationBalance":return $.fetchOrganizationBalance(f.organizationId);case"fetchOrganizationUsageTransactions":return $.fetchOrganizationUsageTransactions({organizationId:f.organizationId,memberId:f.memberId});case"switchAccount":return await $.switchAccount(f.organizationId),{updated:!0};case"fetchFeaturebaseToken":return $.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String(f)}`)}}class MJ{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}var dA={};q(dA,{createOAuthClientCallbacks:()=>T2});function T2(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((Q)=>{f.onOpenUrlError?.({url:$,error:Q})})}catch(Q){f.onOpenUrlError?.({url:$,error:Q})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}var mV={};q(mV,{ClineCore:()=>W4});function lA(f){if(f===!0)return{};if(!f)return;return f}function pA(f){if(f==="user")return"global";return f}class rZ{getService;constructor(f){this.getService=f}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent(f){let $=this.getService().ingestEvent(f);return{event:$.event,duplicate:$.duplicate,matchedSpecIds:$.matchedSpecs.map((J)=>J.specId),queuedRuns:$.queuedRuns,suppressions:$.suppressions}}listEvents(f){return this.getService().listEventLogs(f)}getEvent(f){return this.getService().getEventLog(f)}listSpecs(f){return this.getService().listSpecs(f)}listRuns(f){return this.getService().listRuns(f)}}function rA(f){let{host:$}=f;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await $.startSession({source:J.source?.trim()||U0.CLI,interactive:!1,config:{providerId:L2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:WT(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:f.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await $.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content),delivery:Q.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:ZT(Z)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function R5(f){let $=QT(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),Q=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),Z=f.context?.logger??f.logger,W=f.context?.telemetry??f.telemetry;if(!$&&!J&&!Q&&!Z&&!W)return f.context;return{...f.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...$?{automation:$}:{}}}function QT(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function ZT(f){return{text:f.text,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost},inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function WT(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}var EY={};q(EY,{createCoreSettingsService:()=>L1,CoreSettingsService:()=>M$});import{existsSync as b5}from"node:fs";import{basename as wY,isAbsolute as Nz,relative as qz}from"node:path";var WY={};q(WY,{resolveWorkflowsConfigSearchPaths:()=>bJ,resolveSkillsConfigSearchPaths:()=>EJ,resolveRulesConfigSearchPaths:()=>hJ,parseWorkflowConfigFromMarkdown:()=>SJ,parseSkillConfigFromMarkdown:()=>wJ,parseRuleConfigFromMarkdown:()=>CJ,createWorkflowsConfigDefinition:()=>xJ,createUserInstructionConfigService:()=>z$,createSkillsConfigDefinition:()=>kJ,createRulesConfigDefinition:()=>IJ,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>yJ,UnifiedConfigFileWatcher:()=>K1,SKILLS_CONFIG_DIRECTORY_NAME:()=>qJ,RULES_CONFIG_DIRECTORY_NAME:()=>z5});import{createHash as jT}from"node:crypto";import{watch as HT}from"node:fs";import{readdir as XT,readFile as AT}from"node:fs/promises";import{join as YT}from"node:path";function VT(f){return jT("sha1").update(f).digest("hex")}function aA(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function iA(f){return aA(f)&&f.code==="ENOENT"}function nA(f){return aA(f)&&(f.code==="EACCES"||f.code==="EPERM")}class K1{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(f,$){if(f.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=f,this.debounceMs=$?.debounceMs??75,this.emitParseErrors=$?.emitParseErrors??!1;for(let J of f){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let Q of J.directories){let Z=this.baseTypesByDirectory.get(Q);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(Q,new Set([J.type]))}}}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let f of this.watchersByDirectory.values())f.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let f of this.definitions)await this.refreshTypeInternal(f)})}async refreshType(f){let $=this.definitionsByType.get(f);if(!$)throw Error(`Unknown unified config type '${f}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal($)})}getSnapshot(f){let $=this.recordsByType.get(f);return new Map([...$?.entries()??[]].map(([J,Q])=>[J,{...Q}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));return f}emit(f){for(let $ of this.listeners)$(f)}enqueueRefresh(f){return this.refreshQueue=this.refreshQueue.then(f,f),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let f=this.buildDesiredTypesByDirectory();for(let[$,J]of this.watchersByDirectory.entries()){if(f.has($))continue;J.close(),this.watchersByDirectory.delete($)}this.watchedTypesByDirectory=f;for(let $ of f.keys()){if(this.watchersByDirectory.has($))continue;try{let J=HT($,()=>{let Q=this.watchedTypesByDirectory.get($);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get($);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:$})})}catch(J){if(!iA(J)&&!nA(J)){let Q=f.get($);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,error:J,filePath:$})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let f=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let $ of f){let J=this.definitionsByType.get($);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal(f){let{records:$,discoveredDirectories:J}=await this.loadDefinition(f),Q=this.recordsByType.get(f.type)??new Map;for(let[Z,W]of Q.entries()){if($.has(Z))continue;this.emit({kind:"remove",type:f.type,id:Z,filePath:W.filePath})}for(let[Z,W]of $.entries()){let j=Q.get(Z);if(j&&j.filePath===W.filePath&&j.fingerprint===W.fingerprint)continue;this.emit({kind:"upsert",record:{type:W.type,id:Z,item:W.item,filePath:W.filePath}})}if(this.recordsByType.set(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let Q of f.directories){J.add(Q);let Z=f.discoverFiles?await f.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:H}=W;if(J.add(W.directoryPath),f.includeFile&&!f.includeFile(j,H))continue;try{let X=await AT(H,"utf8"),A={type:f.type,directoryPath:W.directoryPath,fileName:j,filePath:H,content:X},Y=f.parseFile(A),V=f.resolveId(Y,A).trim();if(!V)continue;$.set(V,{type:f.type,id:V,item:Y,filePath:H,fingerprint:VT(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:X,filePath:H})}}}return{records:$,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let f=new Map;for(let[$,J]of this.baseTypesByDirectory.entries())f.set($,new Set(J));for(let[$,J]of this.discoveredDirectoriesByType.entries())for(let Q of J){let Z=f.get(Q);if(Z)Z.add($);else f.set(Q,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await XT(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:YT(f,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch($){if(iA($)||nA($))return[];throw $}}}import{readdir as nZ,readFile as BT,stat as iZ}from"node:fs/promises";import{basename as uf,dirname as KT,extname as L5,join as S0,resolve as NJ}from"node:path";import{AGENTS_RULES_FILE_NAME as tA,RULES_CONFIG_DIRECTORY_NAME as z5,resolveGlobalAgentsRulesPath as PT,resolveRulesConfigSearchPaths as GT,resolveSkillsConfigSearchPaths as FT,resolveWorkflowsConfigSearchPaths as UT,SKILLS_CONFIG_DIRECTORY_NAME as qJ,WORKFLOWS_CONFIG_DIRECTORY_NAME as yJ}from"@cline/shared/storage";import RT from"yaml";var D5="SKILL.md",DT="managed.json",LT=new Set([".md",".markdown",".txt"]);function aZ(f){return f.trim().toLowerCase()}function z2(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"||$?.code==="ELOOP"}function O5(f){return LT.has(L5(f).toLowerCase())}function sA(f){let $=[],J=new Set;for(let Q of f){let Z=NJ(Q);if(J.has(Z))continue;J.add(Z),$.push(Q)}return $}function OT(f){let $=[...f?.directories??EJ(f?.workspacePath)];if(f?.pluginSkillDirectories)$.push(...f.pluginSkillDirectories);else if(f?.includePluginSkills)$.push(...VA({pluginPaths:f.pluginPaths,workspacePath:f.workspacePath,cwd:f.cwd??f.workspacePath}));return sA($)}async function tZ(f){try{let $=await nZ(f,{withFileTypes:!0}),J=[];for(let Q of $){if(!Q.isDirectory())continue;let Z=S0(f,Q.name),W=S0(Z,DT);try{let j=await BT(W,"utf8"),H=JSON.parse(j);if(H&&typeof H==="object")J.push(Z)}catch(j){if(z2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch($){if(z2($))return[];throw $}}function sZ(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=RT.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}catch(W){let j=W instanceof Error?W.message:String(W);return{data:{},body:f,hadFrontmatter:!0,parseError:j}}}function _5(f,$,J){if(f===void 0||f===null){if(J)throw Error(`Missing required frontmatter field '${$}'.`);return}if(typeof f!=="string")throw Error(`Frontmatter field '${$}' must be a string.`);let Q=f.trim();if(!Q&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return Q||void 0}function M2(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function _T(f,$){if(uf(f.filePath).toLowerCase()!==tA.toLowerCase())return uf(f.filePath,L5(f.filePath));if($&&NJ(f.filePath)===NJ($,tA))return"Workspace AGENTS.md";if(NJ(f.filePath)===NJ(PT()))return"Global AGENTS.md";return uf(f.filePath,L5(f.filePath))}function wJ(f,$){let{data:J,body:Q,parseError:Z}=sZ(f);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in skill file.");let H=_5(J.name,"name",!1)??$.trim();if(!H)throw Error("Missing skill name.");return{name:H,description:_5(J.description,"description",!1),disabled:M2(J.disabled,"disabled")??(M2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function CJ(f,$){let{data:J,body:Q,parseError:Z}=sZ(f);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in rule file.");let j=_5(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:M2(J.disabled,"disabled")??(M2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function SJ(f,$){let{data:J,body:Q,parseError:Z}=sZ(f);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in workflow file.");let j=_5(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:M2(J.disabled,"disabled")??(M2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function EJ(f){return FT(f)}function hJ(f){return GT(f)}function bJ(f){return UT(f)}async function oA(f){if(uf(f)===".cline"){let $=await tZ(f);return(await Promise.all($.map((Q)=>oA(S0(Q,qJ))))).flat()}try{let $=await nZ(f,{withFileTypes:!0}),J=[];for(let Q of $){if(Q.isFile()&&Q.name===D5){J.push({directoryPath:f,fileName:Q.name,filePath:S0(f,Q.name)});continue}let Z=S0(f,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await iZ(Z).then((j)=>j.isDirectory()).catch((j)=>{if(z2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:D5,filePath:S0(Z,D5)})}return J}catch($){if(z2($))return[];throw $}}async function T5(f){if(uf(f)===".cline"){let $=await tZ(f);return(await Promise.all($.map((Q)=>T5(S0(Q,"rules.md"))))).flat()}try{if((await iZ(f)).isFile())return[{directoryPath:KT(f),fileName:uf(f),filePath:f}]}catch($){if(!z2($))throw $}try{let J=(await nZ(f,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&O5(Z.name)).map((Z)=>({directoryPath:f,fileName:Z.name,filePath:S0(f,Z.name)})),Q=S0(f,"AGENTS.md");try{if((await iZ(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch($){if(z2($))return[];throw $}}async function TT(f){if(uf(f)===".cline"){let $=await tZ(f);return(await Promise.all($.map((Q)=>T5(S0(Q,yJ))))).flat()}return T5(f)}function kJ(f){let $=OT(f),J=f?.workspacePath?S0(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?sA([...$,J]):$,discoverFiles:oA,includeFile:(Q)=>Q===D5,parseFile:(Q)=>wJ(Q.content,uf(Q.directoryPath)),resolveId:(Q)=>aZ(Q.name)}}function IJ(f){let $=f?.directories??hJ(f?.workspacePath),J=f?.workspacePath?S0(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:T5,includeFile:(Q,Z)=>Q===".clinerules"||O5(Q)||O5(Z),parseFile:(Q)=>CJ(Q.content,_T(Q,f?.workspacePath)),resolveId:(Q)=>aZ(Q.name)}}function xJ(f){let $=f?.directories??bJ(f?.workspacePath),J=f?.workspacePath?S0(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:TT,includeFile:(Q)=>O5(Q),parseFile:(Q)=>SJ(Q.content,uf(Q.filePath,L5(Q.filePath))),resolveId:(Q)=>aZ(Q.name)}}function eA(f){let $=[kJ(f?.skills),IJ(f?.rules),xJ(f?.workflows)];return new K1($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as fY}from"@cline/shared";function zT(f,$){if(f.description?.trim())return fY(f.description,".");if($==="workflow")return;return fY(f.instructions,".")}function MT(f){return f.disabled!==!0}function $Y(f,$){return[...f.getSnapshot($).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>MT(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:zT(Q.item,$),kind:$})).sort((J,Q)=>J.name.localeCompare(Q.name))}function gJ(f){let $=new Map;for(let J of[...$Y(f,"workflow"),...$Y(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function JY(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let Q=J[1];if(!Q)return f;let Z=Q.length+1,W=f.slice(Z),j=gJ($).find((H)=>H.name===Q);return j?`${j.instructions}${W}`:f}function M5(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function NT(f){if(!f||f.length===0)return;let $=f.map(M5).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function qT(f,$,J){if(!J)return!0;let Q=M5(f),Z=M5($),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 mJ(f,$){let J=NT($);return[...f.getSnapshot("skill").entries()].map(([Z,W])=>{let j=W.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>qT(Z.id,Z.name,J))}function yT(f,$){return mJ(f,$).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,Q)=>J.localeCompare(Q))}function wT(f,$,J){let Q=M5($);if(!Q)return{error:"Missing skill name."};let Z=mJ(f,J),W=Z.find((Y)=>Y.id===Q);if(W){let{skill:Y}=W;if(Y.disabled===!0)return{error:`Skill "${Y.name}" is configured but disabled.`};return{id:W.id,skill:Y}}let j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,H=Z.filter(({id:Y})=>{if(Y===j)return!0;return Y.endsWith(`:${j}`)}),X=H.filter(({skill:Y})=>Y.disabled!==!0);if(X.length===1){let{id:Y,skill:V}=X[0];return{id:Y,skill:V}}if(X.length>1)return{error:`Skill "${$}" is ambiguous. Use one of: ${X.map(({id:Y})=>Y).join(", ")}`};if(H.length===1){let{skill:Y}=H[0];return{error:`Skill "${Y.name}" is configured but disabled.`}}if(H.length>1)return{error:`Skill "${$}" is ambiguous, and all matches are disabled: ${H.map(({id:Y})=>Y).join(", ")}`};let A=yT(f,J);return{error:A.length>0?`Skill "${$}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function oZ(f,$=Promise.resolve(),J){let Q=new Set,Z=async(W,j)=>{await $;let H=wT(f,W,J);if("error"in H)return H.error;let{id:X,skill:A}=H;if(Q.has(X))return`Skill "${A.name}" is already running.`;Q.add(X);try{let Y=j?.trim(),V=Y?`
459
459
  <command-args>${Y}</command-args>`:"",B=A.description?.trim()?`Description: ${A.description.trim()}
460
460
 
461
461
  `:"";return`<command-name>${A.name}</command-name>${V}
462
462
  <command-instructions>
463
463
  ${B}${A.instructions}
464
- </command-instructions>`}finally{W.delete(X)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>CJ($,J).map(({skill:Q,...j})=>j),enumerable:!0,configurable:!1}),Z}function mA($){let f=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((W)=>Boolean(W))},async setup(W){if(await f,$.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>KW($.watcher)});if($.registerSkillsTool)W.registerTool(x1(nz($.watcher,f,$.allowedSkillNames)));for(let Z of hJ($.watcher).filter((Q)=>Q.kind==="skill"&&$.includeSkills||Q.kind==="workflow"&&$.includeWorkflows))W.registerCommand({name:Z.name,description:Z.description,handler:(Q)=>{let j=Q.trim();return j?`${Z.instructions}
464
+ </command-instructions>`}finally{Q.delete(X)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>mJ(f,J).map(({skill:W,...j})=>j),enumerable:!0,configurable:!1}),Z}function QY(f){let $=f.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await $,f.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>S9(f.watcher)});if(f.registerSkillsTool)Q.registerTool(i$(oZ(f.watcher,$,f.allowedSkillNames)));for(let Z of gJ(f.watcher).filter((W)=>W.kind==="skill"&&f.includeSkills||W.kind==="workflow"&&f.includeWorkflows))Q.registerCommand({name:Z.name,description:Z.description,handler:(W)=>{let j=W.trim();return j?`${Z.instructions}
465
465
 
466
- ${j}`:Z.instructions}})}}}class gA{watcher;ready;stopped=!1;constructor($){this.watcher=bA($)}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 hJ(this.watcher)}resolveRuntimeSlashCommand($){return xA($,this.watcher)}hasConfiguredSkills($){return CJ(this.watcher,$).some((f)=>!f.disabled)}createExtension($){return mA({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function U1($){return new gA($)}import{readFile as az,writeFile as tz}from"node:fs/promises";import cA from"yaml";function sz($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J,Q=cA.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}function uA($,f){return`---
467
- ${cA.stringify($).trimEnd()}
466
+ ${j}`:Z.instructions}})}}}class ZY{watcher;ready;stopped=!1;constructor(f){this.watcher=eA(f)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType(f){await this.start(),await this.watcher.refreshType(f)}listRecords(f){return[...this.watcher.getSnapshot(f).entries()].map(([$,J])=>({type:f,id:$,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return gJ(this.watcher)}resolveRuntimeSlashCommand(f){return JY(f,this.watcher)}hasConfiguredSkills(f){return mJ(this.watcher,f).some(($)=>!$.disabled)}createSkillsExecutor(f){return oZ(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),f)}createExtension(f){return QY({...f,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function z$(f){return new ZY(f)}import{readFile as CT,writeFile as ST}from"node:fs/promises";import HY from"yaml";function ET(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,Q,Z]=J,W=HY.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}function jY(f,$){return`---
467
+ ${HY.stringify(f).trimEnd()}
468
468
  ---
469
- ${f}`}function oz($,f){let{data:J,body:W,hadFrontmatter:Z}=sz($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return W;return uA(J,W)}return J.disabled=!0,uA(J,W)}async function dA({filePath:$,enabled:f}){let J=await az($,"utf8"),W=oz(J,f);return await tz($,W),{filePath:$,enabled:f,disabled:!f}}var HY={};w(HY,{updateMcpServerOAuthState:()=>Af,setMcpServerDisabled:()=>Hf,resolveMcpServerRegistrations:()=>Y$,resolveDefaultMcpSettingsPath:()=>T0,registerMcpServersFromSettingsFile:()=>Yf,loadMcpSettingsFile:()=>jf,listMcpServerOAuthStatuses:()=>bJ,hasMcpSettingsFile:()=>m$,getMcpServerOAuthState:()=>Xf,createMcpTools:()=>_2,createDisabledMcpToolPolicy:()=>kJ,createDisabledMcpToolPolicies:()=>U5,createDefaultMcpServerClientFactory:()=>z2,authorizeMcpServerOAuth:()=>K5,InMemoryMcpManager:()=>Vf});import{spawn as N_}from"node:child_process";import{StringDecoder as JY}from"node:string_decoder";import{UnauthorizedError as oA}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as M_}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as P_}from"node:crypto";import{UnauthorizedError as U_}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as F_}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as R_}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as D_}from"@modelcontextprotocol/sdk/client/streamableHttp.js";Y5();var L_="/mcp/oauth/callback",O_=[1456,1457,1458],z_=300000;function __($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function T_($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function B5($){let f={};try{f=Xf($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,W,Z=async(j)=>{let H=O2(j(f))??{};try{f=Af($.serverName,()=>H,{filePath:$.settingsPath})}catch{f=H}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return T_(f.redirectUrl??$.redirectUrl)},state:()=>{return W=P_(),W},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((H)=>({...H,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((H)=>({...H,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((H)=>({...H,codeVerifier:j,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!f.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return f.codeVerifier},invalidateCredentials:async(j)=>{await Z((H)=>{if(j==="all")return{lastError:H.lastError,redirectUrl:H.redirectUrl};return{...H,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((H)=>({...H,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>W,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((H)=>({...H,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function V5($){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 R_(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new D_(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function sA($){return new F_({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function K5($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (Y5(),tA)),W=J({filePath:$.filePath}).find((X)=>X.name===f);if(!W)throw Error(`MCP server "${f}" is not configured.`);if(W.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(W.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await $$({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:O_,callbackPath:$.callbackPath??L_,timeoutMs:$.timeoutMs??z_,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let Q=B5({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(X)=>{await $.openUrl?.(X)}});await Q.resetInteractiveState();let j=sA($),H;try{let X=V5({registration:W,oauthProvider:Q.provider,fetch:$.fetch});try{return await j.connect(X),await j.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(A){if(!(A instanceof U_))throw A;if(!Q.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let V=await Z.waitForCallback();if(!V)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(V.error)throw Error(`OAuth authorization failed: ${V.error}`);if(!V.code)throw Error("OAuth callback did not include an authorization code.");let B=Q.getLastOAuthState();if(!B)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(V.state!==B)throw Error("OAuth authorization failed: state mismatch.");await X.finishAuth(V.code),H=sA($);let K=V5({registration:W,oauthProvider:Q.provider,fetch:$.fetch});return await H.connect(K),await H.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(X){let A=__(X);throw await Q.markError(A),Error(A)}finally{await j.close().catch(()=>{return}),await H?.close().catch(()=>{return}),Z.close()}}var y_="2024-11-05",q_=5000,w_=1500,eA="http://127.0.0.1:1456/mcp/oauth/callback";function G5($){return $ instanceof Error?$.message:String($)}function $Y($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
469
+ ${$}`}function hT(f,$){let{data:J,body:Q,hadFrontmatter:Z}=ET(f);if(!Z&&$)return f;if($){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return Q;return jY(J,Q)}return J.disabled=!0,jY(J,Q)}async function XY({filePath:f,enabled:$}){let J=await CT(f,"utf8"),Q=hT(J,$);return await ST(f,Q),{filePath:f,enabled:$,disabled:!$}}var NY={};q(NY,{updateMcpServerOAuthState:()=>U1,setMcpServerDisabled:()=>G1,resolveMcpServerRegistrations:()=>Bf,resolveDefaultMcpSettingsPath:()=>M0,registerMcpServersFromSettingsFile:()=>R1,loadMcpSettingsFile:()=>P1,listMcpServerOAuthStatuses:()=>cJ,hasMcpSettingsFile:()=>df,getMcpServerOAuthState:()=>F1,createMcpTools:()=>y2,createDisabledMcpToolPolicy:()=>uJ,createDisabledMcpToolPolicies:()=>E5,createDefaultMcpServerClientFactory:()=>q2,authorizeMcpServerOAuth:()=>w5,InMemoryMcpManager:()=>D1});import{spawn as jz}from"node:child_process";import{StringDecoder as OY}from"node:string_decoder";import{UnauthorizedError as UY}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as Hz}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as tT}from"node:crypto";import{UnauthorizedError as sT}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as oT}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as eT}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as fz}from"@modelcontextprotocol/sdk/client/streamableHttp.js";N5();var $z="/mcp/oauth/callback",Jz=[1456,1457,1458],Qz=300000;function Zz(f){if(f instanceof Error){let $=f.message.trim();if($.length>0)return $}return String(f)}function Wz(f){return{client_name:"Cline",redirect_uris:[f],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function y5(f){let $={};try{$=F1(f.serverName,{filePath:f.settingsPath})??{}}catch{$={}}let J,Q,Z=async(j)=>{let H=N2(j($))??{};try{$=U1(f.serverName,()=>H,{filePath:f.settingsPath})}catch{$=H}};return{provider:{get redirectUrl(){return $.redirectUrl??f.redirectUrl},get clientMetadata(){return Wz($.redirectUrl??f.redirectUrl)},state:()=>{return Q=tT(),Q},clientInformation:()=>$.clientInformation,saveClientInformation:async(j)=>{await Z((H)=>({...H,clientInformation:j,redirectUrl:f.redirectUrl,lastError:void 0}))},tokens:()=>$.tokens,saveTokens:async(j)=>{await Z((H)=>({...H,tokens:j,redirectUrl:f.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await f.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((H)=>({...H,codeVerifier:j,redirectUrl:f.redirectUrl}))},codeVerifier:()=>{if(!$.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${f.serverName}".`);return $.codeVerifier},invalidateCredentials:async(j)=>{await Z((H)=>{if(j==="all")return{lastError:H.lastError,redirectUrl:H.redirectUrl};return{...H,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((H)=>({...H,discoveryState:j}))},discoveryState:()=>$.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:f.redirectUrl}))},markError:async(j)=>{await Z((H)=>({...H,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function q5(f){let $=f.registration.transport;if($.type==="stdio")throw Error(`MCP server "${f.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=$.headers?{headers:$.headers}:void 0;if($.type==="sse")return new eT(new URL($.url),{authProvider:f.oauthProvider,requestInit:J,fetch:f.fetch});return new fz(new URL($.url),{authProvider:f.oauthProvider,requestInit:J,fetch:f.fetch})}function FY(f){return new oT({name:f.clientName?.trim()||"@cline/core",version:f.clientVersion?.trim()||"0.0.0"})}async function w5(f){let $=f.serverName.trim();if(!$)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (N5(),GY)),Q=J({filePath:f.filePath}).find((X)=>X.name===$);if(!Q)throw Error(`MCP server "${$}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${$}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${$}" uses stdio transport and does not support OAuth browser flow.`);let Z=await ff({host:f.callbackHost,ports:f.callbackPorts?.length?f.callbackPorts:Jz,callbackPath:f.callbackPath??$z,timeoutMs:f.timeoutMs??Qz,successHtml:f.successHtml,onListening:f.onServerListening,onClose:f.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let W=y5({settingsPath:f.filePath,serverName:$,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(X)=>{await f.openUrl?.(X)}});await W.resetInteractiveState();let j=FY(f),H;try{let X=q5({registration:Q,oauthProvider:W.provider,fetch:f.fetch});try{return await j.connect(X),await j.listTools(),await W.clearError(),{serverName:$,authorized:!0,message:`MCP server "${$}" is already authorized.`}}catch(A){if(!(A instanceof sT))throw A;if(!W.getLastAuthorizationUrl())throw Error(`MCP server "${$}" did not provide an authorization URL.`);let V=await Z.waitForCallback();if(!V)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(V.error)throw Error(`OAuth authorization failed: ${V.error}`);if(!V.code)throw Error("OAuth callback did not include an authorization code.");let B=W.getLastOAuthState();if(!B)throw Error(`MCP server "${$}" did not start an OAuth stateful authorization flow.`);if(V.state!==B)throw Error("OAuth authorization failed: state mismatch.");await X.finishAuth(V.code),H=FY(f);let K=q5({registration:Q,oauthProvider:W.provider,fetch:f.fetch});return await H.connect(K),await H.listTools(),await W.clearError(),{serverName:$,authorized:!0,message:`MCP server "${$}" OAuth authorization completed.`}}}catch(X){let A=Zz(X);throw await W.markError(A),Error(A)}finally{await j.close().catch(()=>{return}),await H?.close().catch(()=>{return}),Z.close()}}var Xz="2024-11-05",Az=5000,Yz=1500,RY="http://127.0.0.1:1456/mcp/oauth/callback";function C5(f){return f instanceof Error?f.message:String(f)}function DY(f){let $=Buffer.from(JSON.stringify(f),"utf8"),J=Buffer.from(`Content-Length: ${$.byteLength}\r
470
470
  \r
471
- `,"utf8");return Buffer.concat([J,f])}function fY($){return Buffer.from(`${JSON.stringify($)}
472
- `,"utf8")}class g9{buffer="";decoder=new JY("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
471
+ `,"utf8");return Buffer.concat([J,$])}function LY(f){return Buffer.from(`${JSON.stringify(f)}
472
+ `,"utf8")}class JW{buffer="";decoder=new OY("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`\r
473
473
  \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 Q=Number.parseInt(Z[1],10),j=J+4,H=j+Q;if(this.buffer.length<H)break;f.push(this.buffer.slice(j,H)),this.buffer=this.buffer.slice(H)}return f}}class v9{buffer="";decoder=new JY("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
475
- `);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)f.push(W)}return f}}class WY{registration;process;nextRequestId=1;pending=new Map;framedParser=new g9;newlineParser=new v9;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:y_,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},w_),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){f=W instanceof Error?W:Error(String(W))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new g9,this.newlineParser=new v9,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=N_(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(Z)=>this.handleStdout(Z)),W.stderr.on("data",(Z)=>{if(this.process!==W)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(Z)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${G5(Z)}`))}),W.once("exit",(Z,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${Q??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let Z=this.pending.get(W.id);if(!Z)continue;if(this.pending.delete(W.id),clearTimeout(Z.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;Z.reject(Error(Q));continue}Z.resolve(W.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${G5($)}.${J}`)),f.kill()}async request($,f,J=q_){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,Q={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((H,X)=>{let A=setTimeout(()=>{this.pending.delete(Z),X(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:H,reject:X,timeout:A})});try{W.stdin.write(this.protocolMode==="framed"?$Y(Q):fY(Q))}catch(H){let X=this.pending.get(Z);if(X)clearTimeout(X.timeout),this.pending.delete(Z);throw H}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?$Y(W):fY(W))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class ZY{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 $=B5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??eA});this.authContext=$;try{let f=new M_({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=V5({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof oA?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):G5(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??B5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??eA}),J=$ instanceof oA?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):G5($);throw await f.markError(J),Error(J)}}function z2($={}){return(f)=>f.transport.type==="stdio"?new WY(f):new ZY(f,$)}Y5();function u0(){return Date.now()}function S_($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class Vf{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:u0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=u0(),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=u0(),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&&u0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),W=await(await this.ensureConnectedClient(f)).listTools(),Z=S_(W);return f.toolCache=Z,f.toolCacheUpdatedAt=u0(),f.updatedAt=u0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=u0(),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=u0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=u0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=u0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=u0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=u0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),W,Z=new Promise((j)=>{W=j}),Q=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,Q),await J.catch(()=>{return});try{return await f()}finally{if(W?.(),this.operationLocks.get($)===Q)this.operationLocks.delete($)}}}import{createHash as h_}from"node:crypto";var QY=128,C_=/[^a-zA-Z0-9_-]+/g,jY=8,E_=1,b_="mcp_tool";function k_($){return h_("sha1").update($).digest("hex").slice(0,jY)}function I_($){return $.replace(C_,"_")}var P5=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,W=I_(J);if(W===J&&J.length<=QY)return J;let Z=k_(J),Q=QY-E_-jY;return`${W.slice(0,Q)||b_}_${Z}`};function kJ($){return{[($.nameTransform??P5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function U5($){let f={};for(let J of $.toolNames)Object.assign(f,kJ({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as x_}from"@cline/shared";function m_($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function _2($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??P5;return f.map((W)=>{let Z=J({serverName:$.serverName,toolName:W.name});return x_({name:Z,description:m_($.serverName,W),inputSchema:W.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(Q,j)=>$.provider.callTool({serverName:$.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:j})})})}Z$();var AY={};w(AY,{listPluginToolsWithDiagnostics:()=>F5,listPluginTools:()=>IJ});import{stat as g_}from"node:fs/promises";Z$();var v_=32,T2=new Map;function u_($,f){if(!T2.has($)&&T2.size>=v_){let J=T2.keys().next().value;if(J)T2.delete(J)}T2.set($,f)}async function c_($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let W=await g_(J);return`${J}:${W.mtimeMs}:${W.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function XY($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function d_($){return $.sort((f,J)=>{let W=f.name.localeCompare(J.name);if(W!==0)return W;return f.path.localeCompare(J.path)})}function l_($,f){if(!$.setup)return[];let J=[],W={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(W,{workspaceInfo:f}),J}async function F5($){let f=o1({workspacePath:$.workspacePath,cwd:$.cwd}),J=W$($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let W=await c_({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=T2.get(W);if(Z)return{tools:XY(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let Q=[],j=[],H=[],X;try{X=await P6({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...X.failures],H=[...X.warnings];for(let V of X.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of l_(V,{rootPath:$.workspacePath}))Q.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=f.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await X?.shutdown().catch(()=>{})}let A=d_(Q);return u_(W,{tools:A,failures:j,warnings:H}),{tools:XY(A,J),failures:j,warnings:H}}async function IJ($){return(await F5($)).tools}function D5($,f){if(!f)return"global";let J=r_(f,$);return!J.startsWith("..")&&!p_(J)?"workspace":"global"}function xJ($){return[...$].sort((f,J)=>{let W=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return W(f.source)-W(J.source);return f.name.localeCompare(J.name)})}function BY($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function VY($,f){if($.userInstructionService)return await f($.userInstructionService);let J=BY($);if(!J)return await f(void 0);let W=$.cwd?.trim()||J,Z=U1({skills:{workspacePath:J,includePluginSkills:!0,cwd:W},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await f(Z)}finally{Z.stop()}}function i_($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let W=J.find((Z)=>Z.id===f.id);if(W)return W}for(let W of J)if(W.filePath===f.path||W.item.name===f.name||W.id===f.name)return W;return}class F1{async list($={}){return await VY($,async(f)=>{let J=BY($),W=[],Z=[],Q=[],j=[],H=[];if(f){for(let A of f.listRecords("workflow")){let Y=A.item;W.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"workflow",source:D5(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of f.listRecords("rule")){let Y=A.item;Z.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"rule",source:D5(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of f.listRecords("skill")){let Y=A.item;Q.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"skill",source:D5(A.filePath,J),description:Y.description,toggleable:!0})}}if(J)try{for(let A of await IJ({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${A.pluginName}:${A.name}:${A.path}`,name:A.name,path:A.path,enabled:A.enabled,kind:"tool",source:A.source,description:A.description,toggleable:!0})}catch{}let X=T0();if(m$({filePath:X}))try{for(let A of Y$({filePath:X}))H.push({id:A.name,name:A.name,path:X,enabled:A.disabled!==!0,kind:"mcp",source:D5(X,J),description:A.transport.type,toggleable:!0})}catch{}return{workflows:xJ(W.filter((A)=>R5(A.path))),rules:xJ(Z.filter((A)=>R5(A.path))),skills:xJ(Q.filter((A)=>R5(A.path))),tools:xJ(j),mcp:xJ(H.filter((A)=>R5(A.path)))}})}async toggle($){if($.type==="skills")return await VY($,async(f)=>{let J=i_(f,$),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${$.id??$.name??YY($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=$.enabled??(Z!==void 0?!Z:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??YY($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await dA({filePath:W,enabled:Q}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)b4($.name);else D3($.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(),W=$.enabled;if(W===void 0){let Z=Y$({filePath:J}).find((Q)=>Q.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);W=Z.disabled===!0}return Hf({filePath:J,name:f,disabled:!W}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function Bf(){return new F1}function GY($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await Bf().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await Bf().toggle(f)}}}function PY($){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 UY($){let f=$.config;return"providerId"in f?{...$,config:{...f,...n_($.localRuntime)},localRuntime:$.localRuntime}:$}function u9($,f={}){let J=X8($.config),W=R0(f.defaultCapabilities,$.capabilities),Z=a_(J.localRuntime,$.localRuntime),Q=f.withExtensionContext?.(Z?.extensionContext);if(Q)Z={...Z??{},extensionContext:Q};return{...$,...J,...Z?{localRuntime:Z}:{},...W?{capabilities:W}:{}}}function n_($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:W,onTeamRestored:Z,...Q}=$;return Q}function a_(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}L0();function FY($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??P0.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 mJ($){return!!$&&typeof $==="object"&&!Array.isArray($)}function c9($){let f=$?.trim();return f?f:void 0}function t_($,f){let J=$?.trim();if(!J)return f;let W=Date.parse(J);if(!Number.isFinite(W))return f;return new Date(W).toISOString()}function RY($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function DY($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function s_($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function o_($,f){let J=$.eventId.trim(),W=$.eventType.trim(),Z=$.source.trim(),Q=c9($.subject),j=c9($.dedupeKey)??`${W}:${Z}:${Q??J}`;return{eventId:J,eventType:W,source:Z,subject:Q,occurredAt:t_($.occurredAt,f),workspaceRoot:c9($.workspaceRoot),payload:mJ($.payload)?$.payload:void 0,attributes:mJ($.attributes)?$.attributes:void 0,dedupeKey:j}}function d9($,f){if(!f)return;let J=f.split("."),W=$;for(let Z of J){if(!mJ(W))return;W=W[Z]}return W}function e_($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},W=d9(J,f);if(W!==void 0)return W;if($.attributes){let Z=d9($.attributes,f);if(Z!==void 0)return Z}if($.payload)return d9($.payload,f);return}function L5($,f){if(Array.isArray(f))return f.some((J)=>L5($,J));if(Array.isArray($))return $.some((J)=>L5(J,f));if(mJ(f)){if(!mJ($))return!1;return Object.entries(f).every(([J,W])=>L5($[J],W))}return Object.is($,f)}function $T($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,W])=>L5(e_($,J),W))}class l9{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=o_($,f),W=this.store.insertEventLog(J,{receivedAtIso:f});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),Q=[],j=[],H=[];for(let Y of Z){if(!$T(J,Y.filters)){Q.push({specId:Y.specId,externalId:Y.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(Y);let V=this.materializeForSpec(Y,J,W.record.receivedAt);if(V.run)H.push(V.run);else Q.push({specId:Y.specId,externalId:Y.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let X=j.length===0?"unmatched":H.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:X,matchedSpecCount:j.length,queuedRunCount:H.length,suppressedCount:Q.filter((Y)=>Y.reason!=="filter_mismatch").length});let A=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:X,matchedSpecCount:j.length,queuedRunCount:H.length}),{event:A??W.record,duplicate:!1,matchedSpecs:j,queuedRuns:H,suppressions:Q}}catch(Z){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let W=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let X=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:W});if(X){let A=s_(X.scheduledFor,RY(J,Z)),Y=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:f.eventId,scheduledFor:A});if(Y)return{run:Y,reason:"dedupe_window"}}}let Q=$.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:W,sinceIso:DY(J,Q)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:DY(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?RY(J,Z):J}),reason:"dedupe_window"}}}import{existsSync as UT,readdirSync as FT,readFileSync as RT,statSync as DT}from"node:fs";import{relative as LT}from"node:path";import{resolveCronSpecsDir as OT}from"@cline/shared/storage";import{createHash as fT}from"node:crypto";import JT from"yaml";function WT($){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 ZT($){let f=$.replace(/\r\n/g,`
476
- `);if(!f.startsWith(`---
477
- `))return{frontmatter:void 0,body:$};let J=f.slice(4),W=J.indexOf(`
478
- ---`);if(W===-1)return{frontmatter:void 0,body:$};let Z=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
479
- `))Q=Q.slice(1);return{frontmatter:Z,body:Q}}function c0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function QT($){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 i9($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function jT($){let f=i9($);if(!f)return;let J=c0(f.providerId),W=c0(f.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function HT($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function OY($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let W=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return W;return W.length>0?W:void 0}var XT=new Set(p$);function AT($){let f=OY($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!XT.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var YT=new Set(["rules","skills","plugins"]);function VT($){let f=OY($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!YT.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function p9($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function r9($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function n9($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>n9(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${f.map(([J,W])=>`${JSON.stringify(J)}:${n9(W)}`).join(",")}}`}function zY($,f){let J=fT("sha256");return J.update(n9($)),J.update(`
480
- `),J.update(f),J.digest("hex")}function BT($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var KT=["schedule","timezone"],GT=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],PT=["cwd"];function LY($,f,J,W,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:zY(W,J),error:Z}}function V$($,f,J,W,Z,Q){return{externalId:$,relativePath:f,triggerKind:J,body:W,contentHash:Z,error:Q}}function _Y($){let f=$.relativePath.replace(/\\/g,"/"),J=WT(f),{frontmatter:W,body:Z}=ZT($.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let F=JT.parse(W);if(F&&typeof F==="object"&&!Array.isArray(F))Q=F;else if(F!==null&&F!==void 0)return LY(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(F){return LY(f,J,Z,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let j=zY(Q,Z),H=c0(Q.id),X=H??f;if(J!=="schedule"){for(let F of KT)if(Q[F]!==void 0)return V$(X,f,J,Z,j,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of PT)if(Q[F]!==void 0)return V$(X,f,J,Z,j,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let F of GT)if(Q[F]!==void 0)return V$(X,f,J,Z,j,`field "${F}" is only allowed on .event.md specs`)}let A=c0(Q.prompt),Y=Z.trim(),V=A??(Y.length>0?Y:void 0);if(!V)return V$(X,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=c0(Q.workspaceRoot);if(!B)return V$(X,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=AT(Q.tools),G=VT(Q.extensions)}catch(F){return V$(X,f,J,Z,j,F instanceof Error?F.message:String(F))}let R=HT(Q.mode);if(Q.mode!==void 0&&R===void 0)return V$(X,f,J,Z,j,"mode must be one of: act, plan, yolo");let P={id:H,title:c0(Q.title)??H??BT(f),prompt:V,workspaceRoot:B,mode:R??"yolo",systemPrompt:c0(Q.systemPrompt),modelSelection:jT(Q.modelSelection),maxIterations:p9(Q.maxIterations),timeoutSeconds:p9(Q.timeoutSeconds),tools:K,notesDirectory:c0(Q.notesDirectory),extensions:G,source:c0(Q.source)??"user",tags:QT(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:i9(Q.metadata)},U;if(J==="schedule"){let F=c0(Q.schedule);if(!F)return V$(X,f,J,Z,j,"schedule is required for *.cron.md specs");let z=c0(Q.timezone);try{e7(F,z)}catch(D){return V$(X,f,J,Z,j,D instanceof Error?D.message:String(D))}U={...P,triggerKind:"schedule",schedule:F,timezone:z}}else if(J==="event"){let F=c0(Q.event);if(!F)return V$(X,f,J,Z,j,"event is required for .event.md specs");U={...P,triggerKind:"event",event:F,filters:i9(Q.filters),debounceSeconds:r9(Q.debounceSeconds),dedupeWindowSeconds:r9(Q.dedupeWindowSeconds),cooldownSeconds:r9(Q.cooldownSeconds),maxParallel:p9(Q.maxParallel)}}else U={...P,triggerKind:"one_off"};return{externalId:X,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:U}}function zT($,f){return LT($,f).replace(/\\/g,"/")}function _T($){if(!UT($))return[];let f=[],J=[$];while(J.length>0){let W=J.pop();if(!W)continue;let Z;try{Z=FT(W,{withFileTypes:!0})}catch{continue}for(let Q of Z){let j=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(j);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;f.push(j)}}return f}class a9{store;cronDir;constructor($){this.store=$.store,this.cronDir=OT($.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=_T(this.cronDir),J=new Set;for(let Z of f){let Q=zT(this.cronDir,Z);J.add(Q),$.scanned+=1;let j=await this.reconcileFile(Q,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of W)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),W,Z;try{W=RT(f,"utf8"),Z=DT(f).mtimeMs}catch{return}let j=_Y({relativePath:$,raw:W}),H=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&H.record.enabled)this.applyScheduleNextRunAt(H.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==H.record.scheduleExpr||J.timezone!==H.record.timezone});return{relativePath:$,result:H,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),W=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=q1($.scheduleExpr,W,$.timezone),Q=new Date(Z).toISOString();if($.nextRunAt!==Q)this.store.updateSpecNextRunAt($.specId,Q)}catch{}}}import{existsSync as TT,mkdirSync as NT,watch as MT}from"node:fs";import{relative as yT,resolve as qT}from"node:path";var wT=250;class t9{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??wT),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{NT($,{recursive:!0}),this.watcher=MT($,{recursive:!0},(f,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=qT(this.reconciler.getCronDir(),$);if(!TT(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=yT(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}class gJ{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new o2({dbPath:$.dbPath});let f=$.specs;this.reconciler=new a9({store:this.store,specs:f}),this.materializer=new p2({store:this.store}),this.eventIngress=new l9({store:this.store,logger:$.logger}),this.runner=new n2({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new t9({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=$.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var CY={};w(CY,{manifestToSessionRecord:()=>z5,listSessionHistoryFromBackend:()=>$Q,listSessionHistory:()=>_5,hydrateSessionHistory:()=>hY});import{readdir as ET,readFile as qY}from"node:fs/promises";import{join as wY}from"node:path";import{formatDisplayUserInput as bT,normalizeUserInput as kT}from"@cline/shared";import{resolveSessionDataDir as SY}from"@cline/shared/storage";import{existsSync as ST}from"node:fs";import{readFile as hT}from"node:fs/promises";import{formatDisplayUserInput as TY}from"@cline/shared";class vJ{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 R1($){let f=$?.trim();if(!f||!ST(f))return[];try{let J=(await hT(f,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return NY(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let Z=W.messages;if(Array.isArray(Z))return NY(Z)}return[]}catch{return[]}}function CT($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:TY($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:TY(f.text)}})}}function NY($){return $.map(CT)}function s9($){return $?{...$}:void 0}async function MY($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let W=await f.upsertSubagentSessionFromHook($);if(!W)return;await f.appendSubagentHookAudit(W,$),await f.applySubagentStatus(W,$)}function uJ($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function d0($){let f=uJ($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function O5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function IT($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function e9($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function xT($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function mT($){return $.isSubagent!==!0&&!uJ($.parentSessionId)}function gT($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let W of f){let Z=Number.parseInt(W,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function z5($){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 vT($){let f=e9($);if(f===0)return[];let J=SY(),Z=(await ET(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:gT(j.name.trim())})).sort((j,H)=>H.recency-j.recency||H.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let H=j.name.trim();if(!H)return;let X=wY(J,H,`${H}.json`),A=await qY(X,"utf8").catch(()=>{return});if(!A)return;let Y;try{Y=JSON.parse(A)}catch{return}let V=y0.safeParse(Y);if(!V.success)return;return z5(V.data)}))).filter((j)=>Boolean(j)).sort((j,H)=>H.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function uT($,f,J){let W=e9(f);if(W===0)return await $.listSessions(0),[];let Z=J.includeSubagents?W:xT(W),Q=await $.listSessions(Z);return(J.includeSubagents?Q:Q.filter(mT)).slice(0,W)}function cT($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let Z=W.text?.trim();if(Z)f.push(Z)}return f.join(`
481
- `).trim()}function yY($){return $.replace(/\s+/g," ").trim()}function dT($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function lT($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let W=yY(cT(J.content));if(!W)continue;let Z=f==="user"?yY(bT(W)):W,Q=kT(Z.split(`
482
- `)[0]??Z);return dT(Q,50)}return}function pT($){let f=0;for(let J of $)f+=O5(J.metrics?.cost)??0;return f}function rT($){let f,J;for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(!f)f=d0(Z.modelInfo?.provider);if(!J)J=d0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function iT($){return d0($?.provider)??d0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function nT($){return d0($?.model)??d0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function o9($,f){let J=IT($.metadata),W=uJ(f?.title)??uJ(J?.title),Z=O5(f?.totalCost)??O5(J?.totalCost),Q=J||W!==void 0||Z!==void 0?{...J??{},...W!==void 0?{title:W}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:d0(f?.provider)??d0($.provider)??iT(J)??"",model:d0(f?.model)??d0($.model)??nT(J)??"",metadata:Q}}function aT($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function tT($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!aT(J)}async function sT($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let W=await $.readSessionMessages(J.sessionId);return tT(J,W)?{...J,status:"idle"}:J}))}async function hY($,f){return await Promise.all(f.map(async(J)=>{let W=o9(J),Z=Boolean(uJ(W.metadata?.title)),Q=Boolean(d0(W.provider)),j=Boolean(d0(W.model)),H=O5(W.metadata?.totalCost),X=H!==void 0&&H>0;if(Z&&Q&&j&&X)return W;let A=await $.readSessionMessages(J.sessionId);if(A.length===0)return W;let Y=rT(A),V=pT(A);return o9(J,{title:Z?void 0:lT(A),provider:Q?void 0:Y.provider,model:j?void 0:Y.model,totalCost:X||V<=0?void 0:V})}))}async function _5($,f={}){let J=e9(f.limit),W=f.includeSubagents===!0,Z=await uT($,J,{includeSubagents:W}),Q=f.includeManifestFallback===!0&&Z.length<J?await vT(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let A of[...Z,...Q]){if(j.has(A.sessionId))continue;j.set(A.sessionId,A)}let H=Q.length===0?Z:Array.from(j.values()).sort((A,Y)=>Y.startedAt.localeCompare(A.startedAt)).slice(0,J),X=await sT($,H);if(f.hydrate===!1)return X.map((A)=>o9(A));return await hY($,X)}async function oT($){let f=$.trim();if(!f)return;let J=wY(SY(),f,`${f}.json`),W=await qY(J,"utf8").catch(()=>{return});if(!W)return;try{let Z=y0.safeParse(JSON.parse(W));return Z.success?Z.data.messages_path:void 0}catch{return}}async function $Q($,f={}){let J=new Map;return await _5({listSessions:async(Z)=>{let Q=await $.listSessions(Z);J.clear();for(let j of Q)J.set(j.sessionId,j);return Q.map(d8)},readSessionMessages:async(Z)=>{let Q=J.get(Z)?.messagesPath??await oT(Z);return await R1(Q)}},f)}var GV={};w(GV,{resolveSessionBackend:()=>DQ,createRuntimeHost:()=>h2});import{captureSdkError as BV}from"@cline/shared";var pY={};w(pY,{HubRuntimeHost:()=>g$});import{captureSdkError as bY,createSessionId as kY,HUB_CHECKPOINT_CAPABILITY as JN,HUB_COMPACTION_CAPABILITY as WN,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ZN,HUB_HOOK_CAPABILITY_PREFIX as QN,HUB_MISTAKE_LIMIT_CAPABILITY as jN,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as HN,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as XN,isHubToolExecutorName as AN}from"@cline/shared";var EY={};w(EY,{createCoreSessionSnapshot:()=>B$,coreSessionSnapshotToRecord:()=>T5});function eT($){return $?JSON.parse(JSON.stringify($)):void 0}function $N($){return $?JSON.parse(JSON.stringify($)):void 0}function fN($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,W=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let H=typeof j.ref==="string"?j.ref.trim():"",X=Number(j.createdAt),A=Number(j.runCount);if(!H||!Number.isFinite(X)||!Number.isInteger(A))return[];return[{ref:H,createdAt:X,runCount:A,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=W.at(-1),Q=$?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...Z?{latest:Z}:{},history:W}}function B$($){let{session:f}=$,J=eT(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:$N($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let W=fN(J);return W?{checkpoint:W}:{}})()}}function T5($){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 N2($){if(!$)return;return JSON.parse(JSON.stringify($))}var YN=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function IY($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function xY($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function mY($){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 Kf($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function gY($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(AN)){let Q=f.toolExecutors?.[Z];if(typeof Q!=="function")continue;Kf(J,{kind:"toolExecutor",executor:Z,capabilityName:`${HN}${Z}`},async({payload:j,abortSignal:H})=>{let X=Array.isArray(j.args)?[...j.args]:[],A={...mY(j.context),signal:H};return{result:await Q(...X,A)}})}for(let Z of $?.extraTools??[])Kf(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:N2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:N2(Z.lifecycle)}:{},capabilityName:`${ZN}${Z.name}`},async({payload:Q,abortSignal:j,progress:H})=>{let X={...mY(Q.context),signal:j};return{result:await Z.execute(Q.input,{...X,emitUpdate:(Y)=>{H({update:Y})}})}});let W=$?.hooks;if(W)for(let Z of YN){let Q=W[Z];if(typeof Q!=="function")continue;Kf(J,{kind:"hook",name:Z,capabilityName:`${QN}${Z}`},async({payload:j})=>({control:await Q(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;Kf(J,{kind:"compaction",capabilityName:WN,config:IY($.compaction)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;Kf(J,{kind:"checkpoint",capabilityName:JN,config:IY($.checkpoint)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;Kf(J,{kind:"mistakeLimit",capabilityName:jN},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;Kf(J,{kind:"userInstructionService",capabilityName:XN},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 dY($){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 VN($){return dY($)??"Capability request was cancelled."}function BN($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function KN($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function GN($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,W=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function vY($){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 fQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function D1($,f){return fQ($?.[f])??0}function PN($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,W=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=W?.teamRole==="teammate"||W?.teamRole==="lead"?W.teamRole:void 0;return{event:{type:"usage",agentId:typeof W?.agentId==="string"?W.agentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,inputTokens:D1(f,"inputTokens"),outputTokens:D1(f,"outputTokens"),cacheReadTokens:D1(f,"cacheReadTokens"),cacheWriteTokens:D1(f,"cacheWriteTokens"),cost:fQ(f?.totalCost),totalInputTokens:D1(J,"inputTokens"),totalOutputTokens:D1(J,"outputTokens"),totalCacheReadTokens:D1(J,"cacheReadTokens"),totalCacheWriteTokens:D1(J,"cacheWriteTokens"),totalCost:fQ(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:Z}}function UN($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,W=KN(J)?J:J==="failed"?"error":"completed",Z=GN($?.usage??f?.usage);return{type:"done",reason:W,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function N5($,f){return $.error?.message??`hub command failed: ${f}`}function cJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function lY($){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:P0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:cJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:cJ($.status)==="completed"?0:cJ($.status)==="failed"?1:void 0,status:cJ($.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 L1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function FN($){let f=L1($?.snapshot);if(f)return T5(f);let J=$?.session;return J?lY(J):void 0}function uY($,f,J){let W=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return y0.parse({version:1,session_id:$,source:f.source??P0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:cJ(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:W,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function cY($,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 g${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new vJ;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=R0($.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 s0({...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(!d4($,"session.create"))return!1;let f=await l4({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=gY($.localRuntime,f),W=$.config.sessionId?.trim()||kY(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:N2({...$.config,sessionId:W}),metadata:{...$.sessionMetadata??{},source:$.source??P0.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:N2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(W,f,J.handlers);let Q;try{Q=await Z()}catch(A){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(W,f,J.handlers);try{Q=await Z()}catch(Y){throw this.cleanupPlannedSession(W),Y}}else throw A}let j=L1(Q.payload?.snapshot),H=Q.payload?.session,X=(j?.sessionId??H?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(X!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(X,f,J.handlers);return{sessionId:X,manifest:j?cY(j,$):uY(X,$,H),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let W=$.start,Z=W?this.resolveCapabilities(W):void 0,Q=W?gY(W.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=W?W.config.sessionId?.trim()||kY():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(j,Q.handlers),this.ensureSessionSubscription(j);let H;try{H=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??$.cwd,sessionConfig:N2({...W.config,sessionId:j}),metadata:{...W.sessionMetadata??{},source:W.source??P0.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:N2(W.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!H.ok){let K=typeof H.payload?.error==="string"?H.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let X=L1(H.payload?.snapshot),A=H.payload?.session,Y=(X?.sessionId??A?.sessionId)?.trim();if(J&&!Y){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(Y&&j&&Y!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(Y&&Z)this.sessionCapabilities.set(Y,Z);if(Y&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Y,Q.handlers);if(Y)this.ensureSessionSubscription(Y);let V=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,B=H.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:Y,startResult:Y?{sessionId:Y,manifest:X?cY(X,W??{}):uY(Y,W??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=L1(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,H=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||H?{usage:j,aggregateUsage:H}:void 0}let W=f.payload?.session,Z=vY(W?.usage),Q=vY(W?.aggregateUsage);return Z||Q?{usage:Z,aggregateUsage:Q}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:dY(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(q$(J))return;throw J}return FN(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let Q=L1(Z);return Q?[T5(Q)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(lY)}async listSettings($){let f=await this.client.command("settings.list",xY($));if(!f.ok)throw Error(N5(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",xY($));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 bY(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 W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return R0(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:UN($.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=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",W=$.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=PN($.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=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=L1($.payload?.snapshot),W=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:W}}),J?.interactive===!0&&W0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:W,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{bY(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},H=new AbortController;this.activeCapabilityAbortControllers.set(W,H);let X=(A)=>{this.client.command("capability.progress",{requestId:W,payload:A},f).catch((Y)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",Y,$)})};try{let A=await Q({payload:j,abortSignal:H.signal,progress:X});if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:A},f)}catch(A){if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:A instanceof Error?A.message:String(A)},f)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(VN($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",Q=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!W||!Z||!Q)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},H=BN($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:Q,toolInput:H});let X=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:Q,input:H,policy:j})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:W,approved:X.approved,reason:X.reason},f).catch(()=>{})}}var rY={};w(rY,{RemoteRuntimeHost:()=>M2});class M2 extends g${constructor($){super({url:o$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var iY={};w(iY,{SqliteSessionStore:()=>G$});import{existsSync as RN,mkdirSync as DN}from"node:fs";import{join as LN}from"node:path";import{asBool as dJ,asOptionalString as K$,asString as v$,ensureSessionSchema as ON,loadSqliteDb as zN,nowIso as M5,toBoolInt as lJ}from"@cline/shared/db";import{resolveDbDataDir as _N}from"@cline/shared/storage";class G${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??_N()}init(){this.getRawDb()}ensureSessionsDir(){if(!RN(this.sessionsDirPath))DN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return LN(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=zN(this.sessionDbPath());return ON($,{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=M5();this.run(`INSERT OR REPLACE INTO sessions (
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,H=j+W;if(this.buffer.length<H)break;$.push(this.buffer.slice(j,H)),this.buffer=this.buffer.slice(H)}return $}}class QW{buffer="";decoder=new OY("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];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)$.push(Q)}return $}}class _Y{registration;process;nextRequestId=1;pending=new Map;framedParser=new JW;newlineParser=new QW;stderrBuffer="";connected=!1;protocolMode="newline";constructor(f){this.registration=f}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=["newline","framed"],$;for(let J of f){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:Xz,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Yz),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){$=Q instanceof Error?Q:Error(String(Q))}}throw $??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let f=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!f)return;f.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter(($)=>typeof $?.name==="string"&&typeof $.inputSchema==="object"&&$.inputSchema!==null).map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}async callTool(f){return this.request("tools/call",{name:f.name,arguments:f.arguments??{}})}spawnProcess(f){let $=this.registration.transport;if($.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${$.type}`);this.framedParser=new JW,this.newlineParser=new QW,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=jz($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=Q,Q.stdout.on("data",(Z)=>this.handleStdout(Z)),Q.stderr.on("data",(Z)=>{if(this.process!==Q)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(Z)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${C5(Z)}`))}),Q.once("exit",(Z,W)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${W??"null"}).${j}`))})}handleStdout(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){let Q=JSON.parse(J);if(typeof Q.id!=="number")continue;let Z=this.pending.get(Q.id);if(!Z)continue;if(this.pending.delete(Q.id),clearTimeout(Z.timeout),Q.error){let W=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;Z.reject(Error(W));continue}Z.resolve(Q.result)}}catch($){this.handleProtocolFailure($)}}handleProtocolFailure(f){let $=this.process;if(!$)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${C5(f)}.${J}`)),$.kill()}async request(f,$,J=Az){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,W={jsonrpc:"2.0",id:Z,method:f,...$?{params:$}:{}},j=new Promise((H,X)=>{let A=setTimeout(()=>{this.pending.delete(Z),X(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(Z,{resolve:H,reject:X,timeout:A})});try{Q.stdin.write(this.protocolMode==="framed"?DY(W):LY(W))}catch(H){let X=this.pending.get(Z);if(X)clearTimeout(X.timeout),this.pending.delete(Z);throw H}return j}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?DY(Q):LY(Q))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}class TY{registration;options;client;authContext;constructor(f,$){this.registration=f;this.options=$}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=y5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??RY});this.authContext=f;try{let $=new Hz({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=q5({registration:this.registration,oauthProvider:f.provider,fetch:this.options.fetch});await $.connect(J),await f.clearError(),this.client=$}catch($){let J=$ instanceof UY?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):C5($);throw await f.markError(J),Error(J)}}async disconnect(){let f=this.client;this.client=void 0,await f?.close()}async listTools(){let f=await this.ensureConnectedClient();try{return(await f.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch($){return await this.handleOperationError($)}}async callTool(f){let $=await this.ensureConnectedClient();try{return await $.callTool({name:f.name,arguments:f.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage(f){let $=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!f)return`${$} Run authorizeMcpServerOAuth for this server.`;return`${$} Run authorizeMcpServerOAuth for this server and complete this URL: ${f}`}async handleOperationError(f){let $=this.authContext??y5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??RY}),J=f instanceof UY?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):C5(f);throw await $.markError(J),Error(J)}}function q2(f={}){return($)=>$.transport.type==="stdio"?new _Y($):new TY($,f)}N5();function l0(){return Date.now()}function Vz(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class D1{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(f){this.clientFactory=f.clientFactory,this.toolsCacheTtlMs=f.toolsCacheTtlMs??5000}async registerServer(f){await this.runExclusive(f.name,async()=>{let $=this.servers.get(f.name);if(!$){this.servers.set(f.name,{registration:{...f},status:"disconnected",updatedAt:l0()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=l0(),J)await this.disconnectState($),$.client=void 0,$.toolCache=void 0,$.toolCacheUpdatedAt=void 0})}async unregisterServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($),this.servers.delete(f)})}async connectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.connectState($)})}async disconnectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($)})}async setServerDisabled(f,$){await this.runExclusive(f,async()=>{let J=this.requireServer(f);if(J.registration={...J.registration,disabled:$},J.updatedAt=l0(),$)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map((f)=>({name:f.registration.name,status:f.status,disabled:f.registration.disabled===!0,lastError:f.lastError,toolCount:f.toolCache?.length??0,updatedAt:f.updatedAt,metadata:f.registration.metadata})).sort((f,$)=>f.name.localeCompare($.name))}async listTools(f){let $=this.requireServer(f),J=$.toolCacheUpdatedAt??0;if($.toolCache&&l0()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),Q=await(await this.ensureConnectedClient($)).listTools(),Z=Vz(Q);return $.toolCache=Z,$.toolCacheUpdatedAt=l0(),$.updatedAt=l0(),Z})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=l0(),J.callTool({name:f.toolName,arguments:f.arguments,context:f.context})})}async dispose(){let f=[...this.servers.keys()];for(let $ of f)await this.unregisterServer($)}async ensureConnectedClient(f){if(await this.connectState(f),!f.client)throw Error(`MCP server "${f.registration.name}" does not have an initialized client.`);return f.client}async connectState(f){if(f.registration.disabled)throw Error(`MCP server "${f.registration.name}" is disabled and cannot be connected.`);if(f.status==="connected"&&f.client)return;f.status="connecting",f.updatedAt=l0();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=l0()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=l0(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=l0();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=l0()}}requireServer(f){let $=this.servers.get(f);if(!$)throw Error(`Unknown MCP server: ${f}`);return $}async runExclusive(f,$){let J=this.operationLocks.get(f)??Promise.resolve(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set(f,W),await J.catch(()=>{return});try{return await $()}finally{if(Q?.(),this.operationLocks.get(f)===W)this.operationLocks.delete(f)}}}import{createHash as Bz}from"node:crypto";var zY=128,Kz=/[^a-zA-Z0-9_-]+/g,MY=8,Pz=1,Gz="mcp_tool";function Fz(f){return Bz("sha1").update(f).digest("hex").slice(0,MY)}function Uz(f){return f.replace(Kz,"_")}var S5=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,Q=Uz(J);if(Q===J&&J.length<=zY)return J;let Z=Fz(J),W=zY-Pz-MY;return`${Q.slice(0,W)||Gz}_${Z}`};function uJ(f){return{[(f.nameTransform??S5)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function E5(f){let $={};for(let J of f.toolNames)Object.assign($,uJ({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as Rz}from"@cline/shared";function Dz(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function y2(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??S5;return $.map((Q)=>{let Z=J({serverName:f.serverName,toolName:Q.name});return Rz({name:Z,description:Dz(f.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(W,j)=>f.provider.callTool({serverName:f.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}jf();var yY={};q(yY,{listPluginToolsWithDiagnostics:()=>h5,listPluginTools:()=>dJ});import{stat as Lz}from"node:fs/promises";jf();var Oz=32,w2=new Map;function _z(f,$){if(!w2.has(f)&&w2.size>=Oz){let J=w2.keys().next().value;if(J)w2.delete(J)}w2.set(f,$)}async function Tz(f){let $=await Promise.all(f.pluginPaths.map(async(J)=>{try{let Q=await Lz(J);return`${J}:${Q.mtimeMs}:${Q.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:f.workspacePath,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId,pathStats:$})}function qY(f,$){return f.map((J)=>({...J,enabled:!$.has(J.name)}))}function zz(f){return f.sort(($,J)=>{let Q=$.name.localeCompare(J.name);if(Q!==0)return Q;return $.path.localeCompare(J.path)})}function Mz(f,$){if(!f.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(Q,{workspaceInfo:$}),J}async function h5(f){let $=j1({workspacePath:f.workspacePath,cwd:f.cwd}),J=Wf(f.disabledToolNames);if($.length===0)return{tools:[],failures:[],warnings:[]};let Q=await Tz({pluginPaths:$,workspacePath:f.workspacePath,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId}),Z=w2.get(Q);if(Z)return{tools:qY(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let W=[],j=[],H=[],X;try{X=await x6({pluginPaths:$,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId,workspaceInfo:{rootPath:f.workspacePath}}),j=[...X.failures],H=[...X.warnings];for(let V of X.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of Mz(V,{rootPath:f.workspacePath}))W.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=$.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await X?.shutdown().catch(()=>{})}let A=zz(W);return _z(Q,{tools:A,failures:j,warnings:H}),{tools:qY(A,J),failures:j,warnings:H}}async function dJ(f){return(await h5(f)).tools}function k5(f,$){if(!$)return"global";let J=qz($,f);return!J.startsWith("..")&&!Nz(J)?"workspace":"global"}function lJ(f){return[...f].sort(($,J)=>{let Q=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if($.source!==J.source)return Q($.source)-Q(J.source);return $.name.localeCompare(J.name)})}function SY(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function CY(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=SY(f);if(!J)return await $(void 0);let Q=f.cwd?.trim()||J,Z=z$({skills:{workspacePath:J,includePluginSkills:!0,cwd:Q},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await $(Z)}finally{Z.stop()}}function yz(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let Q=J.find((Z)=>Z.id===$.id);if(Q)return Q}for(let Q of J)if(Q.filePath===$.path||Q.item.name===$.name||Q.id===$.name)return Q;return}class M${async list(f={}){return await CY(f,async($)=>{let J=SY(f),Q=[],Z=[],W=[],j=[],H=[];if($){for(let A of $.listRecords("workflow")){let Y=A.item;Q.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"workflow",source:k5(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of $.listRecords("rule")){let Y=A.item;Z.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"rule",source:k5(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of $.listRecords("skill")){let Y=A.item;W.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"skill",source:k5(A.filePath,J),description:Y.description,toggleable:!0})}}if(J)try{for(let A of await dJ({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))j.push({id:`${A.pluginName}:${A.name}:${A.path}`,name:A.name,path:A.path,enabled:A.enabled,kind:"tool",source:A.source,description:A.description,toggleable:!0})}catch{}let X=M0();if(df({filePath:X}))try{for(let A of Bf({filePath:X}))H.push({id:A.name,name:A.name,path:X,enabled:A.disabled!==!0,kind:"mcp",source:k5(X,J),description:A.transport.type,toggleable:!0})}catch{}return{workflows:lJ(Q.filter((A)=>b5(A.path))),rules:lJ(Z.filter((A)=>b5(A.path))),skills:lJ(W.filter((A)=>b5(A.path))),tools:lJ(j),mcp:lJ(H.filter((A)=>b5(A.path)))}})}async toggle(f){if(f.type==="skills")return await CY(f,async($)=>{let J=yz($,f),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${f.id??f.name??wY(f.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=f.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??wY(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await XY({filePath:Q,enabled:W}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)r4(f.name);else g3(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}if(f.type==="mcp"){let $=f.name?.trim()||f.id?.trim();if(!$)throw Error("MCP server settings toggle requires a server name.");let J=f.path?.trim()||M0(),Q=f.enabled;if(Q===void 0){let Z=Bf({filePath:J}).find((W)=>W.name===$);if(!Z)throw Error(`Unknown MCP server: ${$}`);Q=Z.disabled===!0}return G1({filePath:J,name:$,disabled:!Q}),{snapshot:await this.list(f),changedTypes:["mcp"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function L1(){return new M$}function hY(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await L1().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await L1().toggle($)}}}function bY(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}function kY(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...wz(f.localRuntime)},localRuntime:f.localRuntime}:f}function ZW(f,$={}){let J=P8(f.config),Q=L0($.defaultCapabilities,f.capabilities),Z=Cz(J.localRuntime,f.localRuntime),W=$.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...f,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function wz(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=f;return W}function Cz(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}O0();function IY(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:m.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??U0.CORE,providerId:f.input.config.providerId,modelId:f.input.config.modelId,enableTools:f.input.config.enableTools,enableSpawnAgent:f.input.config.enableSpawnAgent,enableAgentTeams:f.input.config.enableAgentTeams,clientName:f.clientName,runtimeAddress:f.runtimeAddress}})}function pJ(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function WW(f){let $=f?.trim();return $?$:void 0}function Sz(f,$){let J=f?.trim();if(!J)return $;let Q=Date.parse(J);if(!Number.isFinite(Q))return $;return new Date(Q).toISOString()}function xY(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function gY(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function Ez(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function hz(f,$){let J=f.eventId.trim(),Q=f.eventType.trim(),Z=f.source.trim(),W=WW(f.subject),j=WW(f.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:Sz(f.occurredAt,$),workspaceRoot:WW(f.workspaceRoot),payload:pJ(f.payload)?f.payload:void 0,attributes:pJ(f.attributes)?f.attributes:void 0,dedupeKey:j}}function jW(f,$){if(!$)return;let J=$.split("."),Q=f;for(let Z of J){if(!pJ(Q))return;Q=Q[Z]}return Q}function bz(f,$){if(f.attributes&&Object.hasOwn(f.attributes,$))return f.attributes[$];if(f.payload&&Object.hasOwn(f.payload,$))return f.payload[$];let J={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload},Q=jW(J,$);if(Q!==void 0)return Q;if(f.attributes){let Z=jW(f.attributes,$);if(Z!==void 0)return Z}if(f.payload)return jW(f.payload,$);return}function I5(f,$){if(Array.isArray($))return $.some((J)=>I5(f,J));if(Array.isArray(f))return f.some((J)=>I5(J,$));if(pJ($)){if(!pJ(f))return!1;return Object.entries($).every(([J,Q])=>I5(f[J],Q))}return Object.is(f,$)}function kz(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,Q])=>I5(bz(f,J),Q))}class HW{store;nowFn;logger;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now()),this.logger=f.logger}ingestEvent(f){let $=new Date(this.nowFn()).toISOString(),J=hz(f,$),Q=this.store.insertEventLog(J,{receivedAtIso:$});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),W=[],j=[],H=[];for(let Y of Z){if(!kz(J,Y.filters)){W.push({specId:Y.specId,externalId:Y.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(Y);let V=this.materializeForSpec(Y,J,Q.record.receivedAt);if(V.run)H.push(V.run);else W.push({specId:Y.specId,externalId:Y.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let X=j.length===0?"unmatched":H.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:X,matchedSpecCount:j.length,queuedRunCount:H.length,suppressedCount:W.filter((Y)=>Y.reason!=="filter_mismatch").length});let A=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:X,matchedSpecCount:j.length,queuedRunCount:H.length}),{event:A??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:H,suppressions:W}}catch(Z){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:Z});throw Z}}materializeForSpec(f,$,J){let Q=$.dedupeKey??$.eventId,Z=f.debounceSeconds??0;if(Z>0){let X=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:Q});if(X){let A=Ez(X.scheduledFor,xY(J,Z)),Y=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:$.eventId,scheduledFor:A});if(Y)return{run:Y,reason:"dedupe_window"}}}let W=f.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:Q,sinceIso:gY(J,W)}))return{reason:"dedupe_window"};let j=f.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:gY(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:Z>0?xY(J,Z):J}),reason:"dedupe_window"}}}import{existsSync as sz,readdirSync as oz,readFileSync as ez,statSync as fM}from"node:fs";import{relative as $M}from"node:path";import{resolveCronSpecsDir as JM}from"@cline/shared/storage";import{createHash as Iz}from"node:crypto";import xz from"yaml";function gz(f){let $=f.replace(/\\/g,"/");if($.startsWith("events/")&&$.endsWith(".event.md"))return"event";if($.endsWith(".cron.md"))return"schedule";return"one_off"}function mz(f){let $=f.replace(/\r\n/g,`
476
+ `);if(!$.startsWith(`---
477
+ `))return{frontmatter:void 0,body:f};let J=$.slice(4),Q=J.indexOf(`
478
+ ---`);if(Q===-1)return{frontmatter:void 0,body:f};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 p0(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function vz(f){if(!Array.isArray(f))return;let $=f.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return $.length>0?$:void 0}function YW(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return f}function cz(f){let $=YW(f);if(!$)return;let J=p0($.providerId),Q=p0($.modelId);if(J===void 0&&Q===void 0)return;return{providerId:J,modelId:Q}}function uz(f){if(typeof f!=="string")return;let $=f.trim().toLowerCase();if($==="act"||$==="plan"||$==="yolo")return $;return}function vY(f,$={}){let J=Array.isArray(f)?f:typeof f==="string"?f.split(","):void 0;if(!J)return;let Q=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray(f)&&$.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var dz=new Set(sf);function lz(f){let $=vY(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((Q)=>!dz.has(Q));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return $}var pz=new Set(["rules","skills","plugins"]);function rz(f){let $=vY(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((Q)=>!pz.has(Q));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return $}function XW(f){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return;return Math.floor(f)}function AW(f){if(typeof f!=="number"||!Number.isFinite(f)||f<0)return;return Math.floor(f)}function VW(f){if(f===null||typeof f!=="object")return JSON.stringify(f??null);if(Array.isArray(f))return`[${f.map((J)=>VW(J)).join(",")}]`;let $=Object.entries(f).filter(([,J])=>J!==void 0);return $.sort(([J],[Q])=>J<Q?-1:J>Q?1:0),`{${$.map(([J,Q])=>`${JSON.stringify(J)}:${VW(Q)}`).join(",")}}`}function cY(f,$){let J=Iz("sha256");return J.update(VW(f)),J.update(`
480
+ `),J.update($),J.digest("hex")}function iz(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var nz=["schedule","timezone"],az=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],tz=["cwd"];function mY(f,$,J,Q,Z){return{externalId:f,relativePath:f,triggerKind:$,body:J,contentHash:cY(Q,J),error:Z}}function Kf(f,$,J,Q,Z,W){return{externalId:f,relativePath:$,triggerKind:J,body:Q,contentHash:Z,error:W}}function uY(f){let $=f.relativePath.replace(/\\/g,"/"),J=gz($),{frontmatter:Q,body:Z}=mz(f.raw),W={};if(Q!==void 0&&Q.trim().length>0)try{let U=xz.parse(Q);if(U&&typeof U==="object"&&!Array.isArray(U))W=U;else if(U!==null&&U!==void 0)return mY($,J,Z,{},"frontmatter must be a YAML mapping")}catch(U){return mY($,J,Z,{},U instanceof Error?`failed to parse frontmatter: ${U.message}`:"failed to parse frontmatter")}let j=cY(W,Z),H=p0(W.id),X=H??$;if(J!=="schedule"){for(let U of nz)if(W[U]!==void 0)return Kf(X,$,J,Z,j,`field "${U}" is only allowed on *.cron.md specs`)}for(let U of tz)if(W[U]!==void 0)return Kf(X,$,J,Z,j,`field "${U}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let U of az)if(W[U]!==void 0)return Kf(X,$,J,Z,j,`field "${U}" is only allowed on .event.md specs`)}let A=p0(W.prompt),Y=Z.trim(),V=A??(Y.length>0?Y:void 0);if(!V)return Kf(X,$,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=p0(W.workspaceRoot);if(!B)return Kf(X,$,J,Z,j,"workspaceRoot is required");let K,P;try{K=lz(W.tools),P=rz(W.extensions)}catch(U){return Kf(X,$,J,Z,j,U instanceof Error?U.message:String(U))}let R=uz(W.mode);if(W.mode!==void 0&&R===void 0)return Kf(X,$,J,Z,j,"mode must be one of: act, plan, yolo");let G={id:H,title:p0(W.title)??H??iz($),prompt:V,workspaceRoot:B,mode:R??"yolo",systemPrompt:p0(W.systemPrompt),modelSelection:cz(W.modelSelection),maxIterations:XW(W.maxIterations),timeoutSeconds:XW(W.timeoutSeconds),tools:K,notesDirectory:p0(W.notesDirectory),extensions:P,source:p0(W.source)??"user",tags:vz(W.tags),enabled:typeof W.enabled==="boolean"?W.enabled:!0,metadata:YW(W.metadata)},F;if(J==="schedule"){let U=p0(W.schedule);if(!U)return Kf(X,$,J,Z,j,"schedule is required for *.cron.md specs");let _=p0(W.timezone);try{R3(U,_)}catch(L){return Kf(X,$,J,Z,j,L instanceof Error?L.message:String(L))}F={...G,triggerKind:"schedule",schedule:U,timezone:_}}else if(J==="event"){let U=p0(W.event);if(!U)return Kf(X,$,J,Z,j,"event is required for .event.md specs");F={...G,triggerKind:"event",event:U,filters:YW(W.filters),debounceSeconds:AW(W.debounceSeconds),dedupeWindowSeconds:AW(W.dedupeWindowSeconds),cooldownSeconds:AW(W.cooldownSeconds),maxParallel:XW(W.maxParallel)}}else F={...G,triggerKind:"one_off"};return{externalId:X,relativePath:$,triggerKind:J,body:Z,contentHash:j,spec:F}}function QM(f,$){return $M(f,$).replace(/\\/g,"/")}function ZM(f){if(!sz(f))return[];let $=[],J=[f];while(J.length>0){let Q=J.pop();if(!Q)continue;let Z;try{Z=oz(Q,{withFileTypes:!0})}catch{continue}for(let W of Z){let j=`${Q}/${W.name}`;if(W.isDirectory()){if(W.name==="reports")continue;J.push(j);continue}if(!W.isFile())continue;if(!W.name.endsWith(".md"))continue;$.push(j)}}return $}class BW{store;cronDir;constructor(f){this.store=f.store,this.cronDir=JM(f.specs??(f.workspaceRoot?{scope:"workspace",workspaceRoot:f.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let f={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},$=ZM(this.cronDir),J=new Set;for(let Z of $){let W=QM(this.cronDir,Z);J.add(W),f.scanned+=1;let j=await this.reconcileFile(W,Z);if(j){if(f.changes.push(j),f.upserted+=1,j.parse.error)f.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of Q)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),f.removed+=1;return this.refreshScheduleNextRunAt(),f}async reconcileFile(f,$){let J=this.store.getSpecBySourcePath(f),Q,Z;try{Q=ez($,"utf8"),Z=fM($).mtimeMs}catch{return}let j=uY({relativePath:f,raw:Q}),H=this.store.upsertSpec({externalId:j.externalId,sourcePath:f,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&H.record.enabled)this.applyScheduleNextRunAt(H.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==H.record.scheduleExpr||J.timezone!==H.record.timezone});return{relativePath:f,result:H,parse:j}}handleFileDeleted(f){this.store.markSpecRemoved(f.specId),this.store.cancelQueuedRunsForSpec(f.specId)}refreshScheduleNextRunAt(){let f=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let $ of f)this.applyScheduleNextRunAt($,{forceReset:!1})}applyScheduleNextRunAt(f,$){if(!f.scheduleExpr)return;if(!$.forceReset&&f.nextRunAt)return;try{let J=Date.now(),Q=f.lastRunAt?Math.max(J,new Date(f.lastRunAt).getTime()):J,Z=k$(f.scheduleExpr,Q,f.timezone),W=new Date(Z).toISOString();if(f.nextRunAt!==W)this.store.updateSpecNextRunAt(f.specId,W)}catch{}}}import{existsSync as WM,mkdirSync as jM,watch as HM}from"node:fs";import{relative as XM,resolve as AM}from"node:path";var YM=250;class KW{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor(f){this.reconciler=f.reconciler,this.debounceMs=Math.max(0,f.debounceMs??YM),this.onError=f.onError??(()=>{}),this.onReconciled=f.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let f=this.reconciler.getCronDir();try{jM(f,{recursive:!0}),this.watcher=HM(f,{recursive:!0},($,J)=>{if(!J)return;let Q=String(J).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch($){this.onError($)}}stop(){for(let f of this.pending.values())clearTimeout(f);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile(f){let $=this.pending.get(f);if($)clearTimeout($);let J=setTimeout(()=>{this.pending.delete(f),this.reconcileNow(f)},this.debounceMs);this.pending.set(f,J)}async reconcileNow(f){try{let $=AM(this.reconciler.getCronDir(),f);if(!WM($)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=XM(this.reconciler.getCronDir(),$).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,$),await this.onReconciled()}catch($){this.onError($)}}}class rJ{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new Z8({dbPath:f.dbPath});let $=f.specs;this.reconciler=new BW({store:this.store,specs:$}),this.materializer=new s2({store:this.store}),this.eventIngress=new HW({store:this.store,logger:f.logger}),this.runner=new f8({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:f.workspaceRoot,specs:$,logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency}),this.watcher=new KW({reconciler:this.reconciler,debounceMs:f.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=f.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:J});else Q.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs(f){return this.store.listSpecs(f)}getSpec(f){return this.store.getSpec(f)}listRuns(f){return this.store.listRuns(f)}getRun(f){return this.store.getRun(f)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns(f=20){return this.store.listRuns({status:"queued",limit:f})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent(f){return this.eventIngress.ingestEvent(f)}listEventLogs(f){return this.store.listEventLogs(f)}getEventLog(f){return this.store.getEventLog(f)}}var sY={};q(sY,{manifestToSessionRecord:()=>g5,listSessionHistoryFromBackend:()=>UW,listSessionHistory:()=>m5,hydrateSessionHistory:()=>tY});import{readdir as PM,readFile as iY}from"node:fs/promises";import{join as nY}from"node:path";import{formatDisplayUserInput as GM,normalizeUserInput as FM}from"@cline/shared";import{resolveSessionDataDir as aY}from"@cline/shared/storage";import{existsSync as VM}from"node:fs";import{readFile as BM}from"node:fs/promises";import{formatDisplayUserInput as dY}from"@cline/shared";class iJ{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function N$(f){let $=f?.trim();if(!$||!VM($))return[];try{let J=(await BM($,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return lY(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return lY(Z)}return[]}catch{return[]}}function KM(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:dY(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:dY($.text)}})}}function lY(f){return f.map(KM)}function PW(f){return f?{...f}:void 0}async function pY(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let Q=await $.upsertSubagentSessionFromHook(f);if(!Q)return;await $.appendSubagentHookAudit(Q,f),await $.applySubagentStatus(Q,f)}function nJ(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function r0(f){let $=nJ(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function x5(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function UM(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function FW(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function RM(f){if(f===0)return 0;return Math.min(Math.max(f*2,20),2000)}function DM(f){return f.isSubagent!==!0&&!nJ(f.parentSessionId)}function LM(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let Q of $){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function g5(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function OM(f){let $=FW(f);if($===0)return[];let J=aY(),Z=(await PM(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:LM(j.name.trim())})).sort((j,H)=>H.recency-j.recency||H.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let H=j.name.trim();if(!H)return;let X=nY(J,H,`${H}.json`),A=await iY(X,"utf8").catch(()=>{return});if(!A)return;let Y;try{Y=JSON.parse(A)}catch{return}let V=C0.safeParse(Y);if(!V.success)return;return g5(V.data)}))).filter((j)=>Boolean(j)).sort((j,H)=>H.startedAt.localeCompare(j.startedAt)).slice(0,$)}async function _M(f,$,J){let Q=FW($);if(Q===0)return await f.listSessions(0),[];let Z=J.includeSubagents?Q:RM(Q),W=await f.listSessions(Z);return(J.includeSubagents?W:W.filter(DM)).slice(0,Q)}function TM(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)$.push(Z)}return $.join(`
481
+ `).trim()}function rY(f){return f.replace(/\s+/g," ").trim()}function zM(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function MM(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let Q=rY(TM(J.content));if(!Q)continue;let Z=$==="user"?rY(GM(Q)):Q,W=FM(Z.split(`
482
+ `)[0]??Z);return zM(W,50)}return}function NM(f){let $=0;for(let J of f)$+=x5(J.metrics?.cost)??0;return $}function qM(f){let $,J;for(let Q=f.length-1;Q>=0;Q-=1){let Z=f[Q];if(!$)$=r0(Z.modelInfo?.provider);if(!J)J=r0(Z.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function yM(f){return r0(f?.provider)??r0(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function wM(f){return r0(f?.model)??r0(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function GW(f,$){let J=UM(f.metadata),Q=nJ($?.title)??nJ(J?.title),Z=x5($?.totalCost)??x5(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...f,provider:r0($?.provider)??r0(f.provider)??yM(J)??"",model:r0($?.model)??r0(f.model)??wM(J)??"",metadata:W}}function CM(f){let $=f.content;if(!Array.isArray($))return!1;return $.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function SM(f,$){if(f.status!=="running"||f.interactive!==!0)return!1;let J=$.at(-1);return J?.role==="assistant"&&!CM(J)}async function EM(f,$){return await Promise.all($.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let Q=await f.readSessionMessages(J.sessionId);return SM(J,Q)?{...J,status:"idle"}:J}))}async function tY(f,$){return await Promise.all($.map(async(J)=>{let Q=GW(J),Z=Boolean(nJ(Q.metadata?.title)),W=Boolean(r0(Q.provider)),j=Boolean(r0(Q.model)),H=x5(Q.metadata?.totalCost),X=H!==void 0&&H>0;if(Z&&W&&j&&X)return Q;let A=await f.readSessionMessages(J.sessionId);if(A.length===0)return Q;let Y=qM(A),V=NM(A);return GW(J,{title:Z?void 0:MM(A),provider:W?void 0:Y.provider,model:j?void 0:Y.model,totalCost:X||V<=0?void 0:V})}))}async function m5(f,$={}){let J=FW($.limit),Q=$.includeSubagents===!0,Z=await _M(f,J,{includeSubagents:Q}),W=$.includeManifestFallback===!0&&Z.length<J?await OM(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let A of[...Z,...W]){if(j.has(A.sessionId))continue;j.set(A.sessionId,A)}let H=W.length===0?Z:Array.from(j.values()).sort((A,Y)=>Y.startedAt.localeCompare(A.startedAt)).slice(0,J),X=await EM(f,H);if($.hydrate===!1)return X.map((A)=>GW(A));return await tY(f,X)}async function hM(f){let $=f.trim();if(!$)return;let J=nY(aY(),$,`${$}.json`),Q=await iY(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=C0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function UW(f,$={}){let J=new Map;return await m5({listSessions:async(Z)=>{let W=await f.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map(ZJ)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await hM(Z);return await N$(W)}},$)}var gV={};q(gV,{resolveSessionBackend:()=>xW,createRuntimeHost:()=>g2});import{captureSdkError as IV}from"@cline/shared";var YV={};q(YV,{HubRuntimeHost:()=>lf});import{captureSdkError as eY,createSessionId as fV,HUB_CHECKPOINT_CAPABILITY as xM,HUB_COMPACTION_CAPABILITY as gM,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as mM,HUB_HOOK_CAPABILITY_PREFIX as vM,HUB_MISTAKE_LIMIT_CAPABILITY as cM,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as uM,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as dM,isHubToolExecutorName as lM}from"@cline/shared";var oY={};q(oY,{createCoreSessionSnapshot:()=>Pf,coreSessionSnapshotToRecord:()=>v5});function bM(f){return f?JSON.parse(JSON.stringify(f)):void 0}function kM(f){return f?JSON.parse(JSON.stringify(f)):void 0}function IM(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,Q=(Array.isArray($?.history)?$.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let H=typeof j.ref==="string"?j.ref.trim():"",X=Number(j.createdAt),A=Number(j.runCount);if(!H||!Number.isFinite(X)||!Number.isInteger(A))return[];return[{ref:H,createdAt:X,runCount:A,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=f?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function Pf(f){let{session:$}=f,J=bM($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:kM(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...f.aggregateUsage?{aggregateUsage:{...f.aggregateUsage}}:{},...(()=>{let Q=IM(J);return Q?{checkpoint:Q}:{}})()}}function v5(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function C2(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var pM=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function $V(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function JV(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function QV(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function O1(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function ZV(f,$){let J={manifest:[],handlers:new Map};for(let Z of Object.keys($.toolExecutors??{}).filter(lM)){let W=$.toolExecutors?.[Z];if(typeof W!=="function")continue;O1(J,{kind:"toolExecutor",executor:Z,capabilityName:`${uM}${Z}`},async({payload:j,abortSignal:H})=>{let X=Array.isArray(j.args)?[...j.args]:[],A={...QV(j.context),signal:H};return{result:await W(...X,A)}})}for(let Z of f?.extraTools??[])O1(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:C2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:C2(Z.lifecycle)}:{},capabilityName:`${mM}${Z.name}`},async({payload:W,abortSignal:j,progress:H})=>{let X={...QV(W.context),signal:j};return{result:await Z.execute(W.input,{...X,emitUpdate:(Y)=>{H({update:Y})}})}});let Q=f?.hooks;if(Q)for(let Z of pM){let W=Q[Z];if(typeof W!=="function")continue;O1(J,{kind:"hook",name:Z,capabilityName:`${vM}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if(f?.compaction?.compact){let Z=f.compaction.compact;O1(J,{kind:"compaction",capabilityName:gM,config:$V(f.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if(f?.checkpoint?.createCheckpoint){let Z=f.checkpoint.createCheckpoint;O1(J,{kind:"checkpoint",capabilityName:xM,config:$V(f.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if(f?.onConsecutiveMistakeLimitReached){let Z=f.onConsecutiveMistakeLimitReached;O1(J,{kind:"mistakeLimit",capabilityName:cM},async({payload:W})=>({result:await Z(W.context)}))}if(f?.userInstructionService){let Z=f.userInstructionService;O1(J,{kind:"userInstructionService",capabilityName:dM},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 XV(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message.trim()||void 0;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return}function rM(f){return XV(f)??"Capability request was cancelled."}function iM(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function nM(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function aM(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,Q=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function WV(f){if(!f)return;return{inputTokens:typeof f.inputTokens==="number"?f.inputTokens:0,outputTokens:typeof f.outputTokens==="number"?f.outputTokens:0,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function RW(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function q$(f,$){return RW(f?.[$])??0}function tM(f){let $=f?.delta&&typeof f.delta==="object"?f.delta:void 0,J=f?.totals&&typeof f.totals==="object"?f.totals:void 0,Q=f?.agent&&typeof f.agent==="object"?f.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:q$($,"inputTokens"),outputTokens:q$($,"outputTokens"),cacheReadTokens:q$($,"cacheReadTokens"),cacheWriteTokens:q$($,"cacheWriteTokens"),cost:RW($?.totalCost),totalInputTokens:q$(J,"inputTokens"),totalOutputTokens:q$(J,"outputTokens"),totalCacheReadTokens:q$(J,"cacheReadTokens"),totalCacheWriteTokens:q$(J,"cacheWriteTokens"),totalCost:RW(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function sM(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,Q=nM(J)?J:J==="failed"?"error":"completed",Z=aM(f?.usage??$?.usage);return{type:"done",reason:Q,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:Z}}function c5(f,$){return f.error?.message??`hub command failed: ${$}`}function aJ(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function AV(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:U0.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:aJ(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:aJ(f.status)==="completed"?0:aJ(f.status)==="failed"?1:void 0,status:aJ(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function y$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function oM(f){let $=y$(f?.snapshot);if($)return v5($);let J=f?.session;return J?AV(J):void 0}function jV(f,$,J){let Q=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return C0.parse({version:1,session_id:f,source:$.source??U0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:aJ(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:Q,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function HV(f,$){return C0.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class lf{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new iJ;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=L0(f.capabilities)??{},this.telemetry=f.telemetry,this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new e0({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!$6(f,"session.create"))return!1;let $=await J6({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=ZV(f.localRuntime,$),Q=f.config.sessionId?.trim()||fV(),Z=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:C2({...f.config,sessionId:Q}),metadata:{...f.sessionMetadata??{},source:f.source??U0.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:C2(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(Q,$,J.handlers);let W;try{W=await Z()}catch(A){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(Q,$,J.handlers);try{W=await Z()}catch(Y){throw this.cleanupPlannedSession(Q),Y}}else throw A}let j=y$(W.payload?.snapshot),H=W.payload?.session,X=(j?.sessionId??H?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(X!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(X,$,J.handlers);return{sessionId:X,manifest:j?HV(j,f):jV(X,f,H),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let Q=f.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?ZV(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||fV():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let H;try{H=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??f.cwd,sessionConfig:C2({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??U0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:C2(Q.toolPolicies)}:{}},$)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!H.ok){let K=typeof H.payload?.error==="string"?H.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let X=y$(H.payload?.snapshot),A=H.payload?.session,Y=(X?.sessionId??A?.sessionId)?.trim();if(J&&!Y){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(Y&&j&&Y!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(Y&&Z)this.sessionCapabilities.set(Y,Z);if(Y&&W.handlers.size>0)this.sessionClientContributionHandlers.set(Y,W.handlers);if(Y)this.ensureSessionSubscription(Y);let V=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,B=H.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:Y,startResult:Y?{sessionId:Y,manifest:X?HV(X,Q??{}):jV(Y,Q??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,mode:f.mode,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=y$($.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,H=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||H?{usage:j,aggregateUsage:H}:void 0}let Q=$.payload?.session,Z=WV(Q?.usage),W=WV(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:XV($)},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $;try{$=await this.client.command("session.get",void 0,f)}catch(J){if(hf(J))return;throw J}return oM($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((Z)=>{let W=y$(Z);return W?[v5(W)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(AV)}async listSettings(f){let $=await this.client.command("settings.list",JV(f));if(!$.ok)throw Error(c5($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",JV(f));if(!$.ok)throw Error(c5($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw eY(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(c5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:$,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(c5(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return L0(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:sM(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,f)});return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,f)});return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=y$(f.payload?.snapshot),Q=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",Q=f.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"usage.updated":{let J=tM(f.payload);this.events.emit({type:"agent_event",payload:{sessionId:$,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=y$(f.payload?.snapshot),Q=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=y$(f.payload?.snapshot),Q=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:Q}}),J?.interactive===!0&&J0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:$,reason:Q,ts:f.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError(f,$,J){try{eY(this.telemetry,{component:"core",operation:f,error:$,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof f.payload?.requestId==="string"?f.payload.requestId:"",Z=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get($)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${$}.`},$).catch(()=>{});return}let j=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},H=new AbortController;this.activeCapabilityAbortControllers.set(Q,H);let X=(A)=>{this.client.command("capability.progress",{requestId:Q,payload:A},$).catch((Y)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",Y,f)})};try{let A=await W({payload:j,abortSignal:H.signal,progress:X});if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:A},$)}catch(A){if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:A instanceof Error?A.message:String(A)},$)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(rM(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",Z=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",W=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!Q||!Z||!W)return;let j=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},H=iM(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:$,toolCallId:Z,toolName:W,toolInput:H});let X=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:Z,toolName:W,input:H,policy:j})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:X.approved,reason:X.reason},$).catch(()=>{})}}var VV={};q(VV,{RemoteRuntimeHost:()=>S2});class S2 extends lf{constructor(f){super({url:Z$(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}var BV={};q(BV,{SqliteSessionStore:()=>Ff});import{existsSync as eM,mkdirSync as fN}from"node:fs";import{join as $N}from"node:path";import{asBool as tJ,asOptionalString as Gf,asString as pf,ensureSessionSchema as JN,loadSqliteDb as QN,nowIso as u5,toBoolInt as sJ}from"@cline/shared/db";import{resolveDbDataDir as ZN}from"@cline/shared/storage";class Ff{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??ZN()}init(){this.getRawDb()}ensureSessionsDir(){if(!eM(this.sessionsDirPath))fN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return $N(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=QN(this.sessionDbPath());return JN(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=u5();this.run(`INSERT OR REPLACE INTO sessions (
483
483
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
484
484
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
485
485
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
486
486
  metadata_json, transcript_path, hook_path, messages_path, updated_at
487
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,lJ($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,lJ($.enableTools),lJ($.enableSpawn),lJ($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,lJ($.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(M5()),J.push($.sessionId),this.run(`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`,J)}updateStatus($,f,J){this.update({sessionId:$,status:f,endedAt:W0(f)?null:M5(),exitCode:W0(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,
487
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,sJ(f.interactive),f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,sJ(f.enableTools),sJ(f.enableSpawn),sJ(f.enableTeams),f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,sJ(f.isSubagent),f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"",f.hookPath??"",f.messagesPath??null,$])}update(f){let $=[],J=[];if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(f.metadata?JSON.stringify(f.metadata):null);if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId);if($.length===0)return;$.push("updated_at = ?"),J.push(u5()),J.push(f.sessionId),this.run(`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`,J)}updateStatus(f,$,J){this.update({sessionId:f,status:$,endedAt:J0($)?null:u5(),exitCode:J0($)?null:J??($==="failed"?1:0)})}get(f){let $=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
488
488
  provider, model, cwd, workspace_root, team_name,
489
489
  enable_tools, enable_spawn, enable_teams,
490
490
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
491
491
  prompt, metadata_json, hook_path, messages_path, updated_at
492
- FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:v$(f.session_id),source:v$(f.source),pid:Number(f.pid??0),startedAt:v$(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:v$(f.status),interactive:dJ(f.interactive),provider:v$(f.provider),model:v$(f.model),cwd:v$(f.cwd),workspaceRoot:v$(f.workspace_root),teamName:K$(f.team_name),enableTools:dJ(f.enable_tools),enableSpawn:dJ(f.enable_spawn),enableTeams:dJ(f.enable_teams),parentSessionId:K$(f.parent_session_id),parentAgentId:K$(f.parent_agent_id),agentId:K$(f.agent_id),conversationId:K$(f.conversation_id),isSubagent:dJ(f.is_subagent),prompt:K$(f.prompt),metadata:(()=>{let J=K$(f.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:K$(f.hook_path),messagesPath:K$(f.messages_path),updatedAt:K$(f.updated_at)??M5()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let W of f){let Z=this.get(v$(W.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}x4();import{existsSync as KQ,mkdirSync as cN,readFileSync as ZV,renameSync as dN,writeFileSync as lN}from"node:fs";import{join as QV}from"node:path";import{resolveSessionDataDir as pN}from"@cline/shared/storage";import{dirname as vN}from"node:path";import{nanoid as uN}from"nanoid";import{appendFileSync as TN,existsSync as NN,mkdirSync as nY,readFileSync as MN,writeFileSync as aY}from"node:fs";import{dirname as tY,join as yN}from"node:path";import{ensureHookLogDir as qN}from"@cline/shared/storage";class JQ{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new R9(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){lH(f,J,EZ($))}writeSessionManifest($,f){nY(tY($),{recursive:!0}),aY($,`${JSON.stringify(y0.parse(f),null,2)}
493
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!NN(f))return{path:f};try{return{path:f,manifest:y0.parse(JSON.parse(MN(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let W=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=bZ({updatedAt:s(),context:EZ($),messages:f,systemPrompt:J}),Q=`${JSON.stringify(Z,null,2)}
494
- `;if(nY(tY(W),{recursive:!0}),aY(W,Q,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:W,contents:Q,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,W,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??yN(qN(),"hooks.jsonl");TN(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:W,sessionId:f,pid:J,source:Z})}
495
- `,"utf8")}}import{appendFileSync as wN}from"node:fs";import{join as SN}from"node:path";import{resolveRootSessionId as sY}from"@cline/shared";import{ensureHookLogDir as hN}from"@cline/shared/storage";import{z as WQ}from"zod";var CN="subagent",EN=WQ.looseObject({task:WQ.string().optional(),systemPrompt:WQ.string().optional()});class y5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,W){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:CN,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:l8({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=sY($.sessionContext);if(!f)return;let J=EN.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let W=af(f,$.agentId),Z=await this.adapter.getSession(W),Q=s(),j=this.manifestStore.artifacts.subagentArtifactPaths(W,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),H=$.prompt??Z?.prompt??void 0;if(!H)H=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:H,startedAt:Q,...j})),this.manifestStore.initializeMessagesFile(W,j.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??H??null,metadata:l8({metadata:Z.metadata??void 0,prompt:Z.prompt??H??null}),expectedStatusLock:Z.statusLock}),W}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=sY($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=af(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($,u8(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let W=W0(f)?null:s(),Z=W0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:W,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,f)}async onTeamTaskStart($,f,J){let W=await this.adapter.getSession($);if(!W)return;let Z=g8($,f),Q=s(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:Q,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,Q);let H=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(H)??[];X.push(Z),this.teamTaskSessionsByAgent.set(H,X)}async onTeamTaskEnd($,f,J,W,Z,Q){let j=this.teamTaskQueueKey($,f),H=this.teamTaskSessionsByAgent.get(j);if(!H||H.length===0)return;let X=H.shift();if(H.length===0)this.teamTaskSessionsByAgent.delete(j);if(!X)return;let A=Z?.messages??Q,Y=this.toPersistedMessages(A,Z,Q);if(Y)await this.manifestStore.persistSessionMessages(X,Y);await this.applySubagentStatusBySessionId(X,J),this.teamTaskLastHeartbeatBySession.delete(X),this.teamTaskLastProgressLineBySession.delete(X)}async onTeamTaskProgress($,f,J,W){let Z=this.teamTaskQueueKey($,f),Q=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!Q)return;let j=J.trim();if(!j)return;let H=W?.kind??"progress";if(H==="heartbeat"){let A=Date.now(),Y=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(A-Y<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,A)}let X=H==="heartbeat"?"[progress] heartbeat":H==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(Q)===X)return;this.teamTaskLastProgressLineBySession.set(Q,X)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(W)await this.manifestStore.persistSessionMessages(J,W);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??SN(hN(),"hooks.jsonl");wN(J,`${JSON.stringify({ts:s(),...$})}
496
- `,"utf8")}}import{formatUserInputBlock as gN}from"@cline/shared";var WV={};w(WV,{toTeamProgressLifecycleEvent:()=>q2,sanitizeTeamName:()=>bH,reviveTeamStateDates:()=>Z6,createWorkerReviewerTeam:()=>JV,createSpawnAgentTool:()=>Q1,createDelegatedAgentConfigProvider:()=>lf,createDelegatedAgent:()=>pf,createAgentTeamsTools:()=>d1,createAgentTeam:()=>QQ,buildTeamProgressSummary:()=>y2,buildDelegatedAgentConfig:()=>u1,bootstrapAgentTeams:()=>nf,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>S2});function P$(){return new Date().toISOString()}function oY($,f){if(f<=0)return 0;return Math.round($/f*100)}function bN($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let W=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let Q of Z.requiredSections)if(!J.has(`${Z.id}:${Q}`))W.add(`${Z.id}:${Q}`)}return[...W].sort((Z,Q)=>Z.localeCompare(Q))}function y2($,f){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},H=0,X=0;for(let P of f.members)if(J[P.status]+=1,P.role==="lead")H+=1;else X+=1;let A=[],Y=[],V=f.tasks.filter((P)=>P.status==="completed").length,B=new Map(f.tasks.map((P)=>[P.id,P]));for(let P of f.tasks){if(W[P.status]+=1,P.status==="blocked"){A.push(P.id);continue}if(P.status!=="pending")continue;if(P.dependsOn.every((F)=>{return B.get(F)?.status==="completed"}))Y.push(P.id)}let K=[],G,R=0;for(let P of f.runs){if(Z[P.status]+=1,P.status==="queued"||P.status==="running")K.push(P.id);let U=P.startedAt.getTime();if(U>=R)R=U,G=P.id}for(let P of f.outcomes)Q[P.status]+=1;for(let P of f.outcomeFragments)j[P.status]+=1;return{teamName:$,updatedAt:P$(),members:{total:f.members.length,byStatus:J,leadCount:H,teammateCount:X},tasks:{total:f.tasks.length,byStatus:W,blockedTaskIds:A,readyTaskIds:Y,completionPct:oY(V,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:Q,finalizedPct:oY(Q.finalized,f.outcomes.length),missingRequiredSections:bN(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function q2($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),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:P$(),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:P$(),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:P$(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),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:P$(),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:P$(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$()}}import{sanitizeFileName as kN,TeamMessageType as b}from"@cline/shared";import{nanoid as IN}from"nanoid";import{TeamMessageType as fv}from"@cline/shared";function ZQ($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function eY($,f){return $?.status==="stopped"&&ZQ(f)}var xN=600000,$V="recovered_queued";function mN($){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.
492
+ FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:pf($.session_id),source:pf($.source),pid:Number($.pid??0),startedAt:pf($.started_at),endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:pf($.status),interactive:tJ($.interactive),provider:pf($.provider),model:pf($.model),cwd:pf($.cwd),workspaceRoot:pf($.workspace_root),teamName:Gf($.team_name),enableTools:tJ($.enable_tools),enableSpawn:tJ($.enable_spawn),enableTeams:tJ($.enable_teams),parentSessionId:Gf($.parent_session_id),parentAgentId:Gf($.parent_agent_id),agentId:Gf($.agent_id),conversationId:Gf($.conversation_id),isSubagent:tJ($.is_subagent),prompt:Gf($.prompt),metadata:(()=>{let J=Gf($.metadata_json);if(!J)return;try{let Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:Gf($.hook_path),messagesPath:Gf($.messages_path),updatedAt:Gf($.updated_at)??u5()}}list(f=200){let $=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[f]),J=[];for(let Q of $){let Z=this.get(pf(Q.session_id));if(Z)J.push(Z)}return J}delete(f,$=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}}a4();import{existsSync as SW,mkdirSync as gN,readFileSync as yV,renameSync as mN,writeFileSync as vN}from"node:fs";import{join as wV}from"node:path";import{resolveSessionDataDir as cN}from"@cline/shared/storage";import{dirname as IN}from"node:path";import{nanoid as xN}from"nanoid";import{appendFileSync as WN,existsSync as jN,mkdirSync as KV,readFileSync as HN,writeFileSync as PV}from"node:fs";import{dirname as GV,join as XN}from"node:path";import{ensureHookLogDir as AN}from"@cline/shared/storage";class DW{adapter;messagesArtifactUploader;logger;artifacts;constructor(f,$,J){this.adapter=f;this.messagesArtifactUploader=$;this.logger=J;this.artifacts=new pZ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile(f,$,J){xX($,J,YZ(f))}writeSessionManifest(f,$){KV(GV(f),{recursive:!0}),PV(f,`${JSON.stringify(C0.parse($),null,2)}
493
+ `,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!jN($))return{path:$};try{return{path:$,manifest:C0.parse(JSON.parse(HN($,"utf8")))}}catch{return{path:$}}}async resolveArtifactPath(f,$,J){let Z=(await this.adapter.getSession(f))?.[$];return typeof Z==="string"&&Z.trim().length>0?Z:J(f)}async persistSessionMessages(f,$,J){let Q=await this.resolveArtifactPath(f,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=VZ({updatedAt:s(),context:YZ(f),messages:$,systemPrompt:J}),W=`${JSON.stringify(Z,null,2)}
494
+ `;if(KV(GV(Q),{recursive:!0}),PV(Q,W,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession(f);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:f,path:Q,contents:W,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:f,error:j})}}appendStaleSessionHookLog(f,$,J,Q,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??XN(AN(),"hooks.jsonl");WN(j,`${JSON.stringify({ts:f,hookName:"session_shutdown",reason:Q,sessionId:$,pid:J,source:Z})}
495
+ `,"utf8")}}import{appendFileSync as YN}from"node:fs";import{join as VN}from"node:path";import{resolveRootSessionId as FV}from"@cline/shared";import{ensureHookLogDir as BN}from"@cline/shared/storage";import{z as LW}from"zod";var KN="subagent",PN=LW.looseObject({task:LW.string().optional(),systemPrompt:LW.string().optional()});class d5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(f,$,J,Q){this.adapter=f;this.manifestStore=$;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey(f,$){return`${f}::${$}`}activeTeamTaskSessionId(f,$){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey(f,$))?.at(-1)}buildSubsessionRow(f,$){return{sessionId:$.sessionId,source:KN,pid:process.ppid,startedAt:$.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId??null,isSubagent:!0,prompt:$.prompt,metadata:WJ({prompt:$.prompt}),hookPath:"",messagesPath:$.messagesPath,updatedAt:$.startedAt}}async queueSpawnRequest(f){if(f.hookName!=="tool_call"||f.parent_agent_id!==null)return;if(f.tool_call?.name!=="spawn_agent")return;let $=FV(f.sessionContext);if(!$)return;let J=PN.safeParse(f.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:$,parentAgentId:f.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession(f){let $=f.rootSessionId;if(!$)return;let J=await this.adapter.getSession($);if(!J)return;let Q=j2($,f.agentId),Z=await this.adapter.getSession(Q),W=s(),j=this.manifestStore.artifacts.subagentArtifactPaths(Q,f.agentId,this.activeTeamTaskSessionId($,f.parentAgentId)),H=f.prompt??Z?.prompt??void 0;if(!H)H=await this.adapter.claimSpawnRequest($,f.parentAgentId)??`Subagent run by ${f.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:Q,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:H,startedAt:W,...j})),this.manifestStore.initializeMessagesFile(Q,j.messagesPath,W),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:Z.prompt??H??null,metadata:WJ({metadata:Z.metadata??void 0,prompt:Z.prompt??H??null}),expectedStatusLock:Z.statusLock}),Q}async upsertSubagentSessionFromHook(f){if(!f.parent_agent_id)return;let $=FV(f.sessionContext);if(!$)return;if(f.hookName==="session_shutdown"){let J=j2($,f.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:f.agent_id,parentAgentId:f.parent_agent_id,conversationId:f.taskId,rootSessionId:$})}async applySubagentStatus(f,$){await this.applySubagentStatusBySessionId(f,JJ($))}async applySubagentStatusBySessionId(f,$){let J=await this.adapter.getSession(f);if(!J)return;let Q=J0($)?null:s(),Z=J0($)?null:$==="failed"?1:0;await this.adapter.updateSession({sessionId:f,status:$,endedAt:Q,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions(f,$){if(!f)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:f,status:"running"});for(let Q of J)await this.applySubagentStatusBySessionId(Q.sessionId,$)}async onTeamTaskStart(f,$,J){let Q=await this.adapter.getSession(f);if(!Q)return;let Z=fJ(f,$),W=s(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,$);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:f,parentAgentId:"lead",agentId:$,prompt:J||`Team task for ${$}`,startedAt:W,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,W);let H=this.teamTaskQueueKey(f,$),X=this.teamTaskSessionsByAgent.get(H)??[];X.push(Z),this.teamTaskSessionsByAgent.set(H,X)}async onTeamTaskEnd(f,$,J,Q,Z,W){let j=this.teamTaskQueueKey(f,$),H=this.teamTaskSessionsByAgent.get(j);if(!H||H.length===0)return;let X=H.shift();if(H.length===0)this.teamTaskSessionsByAgent.delete(j);if(!X)return;let A=Z?.messages??W,Y=this.toPersistedMessages(A,Z,W);if(Y)await this.manifestStore.persistSessionMessages(X,Y);await this.applySubagentStatusBySessionId(X,J),this.teamTaskLastHeartbeatBySession.delete(X),this.teamTaskLastProgressLineBySession.delete(X)}async onTeamTaskProgress(f,$,J,Q){let Z=this.teamTaskQueueKey(f,$),W=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!W)return;let j=J.trim();if(!j)return;let H=Q?.kind??"progress";if(H==="heartbeat"){let A=Date.now(),Y=this.teamTaskLastHeartbeatBySession.get(W)??0;if(A-Y<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(W,A)}let X=H==="heartbeat"?"[progress] heartbeat":H==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(W)===X)return;this.teamTaskLastProgressLineBySession.set(W,X)}async handleSubAgentStart(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;if($.error){await this.applySubagentStatusBySessionId(J,"failed");return}let Q=this.toPersistedMessages($.agentResult?.messages,$.agentResult);if(Q)await this.manifestStore.persistSessionMessages(J,Q);let Z=$.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(f){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??VN(BN(),"hooks.jsonl");YN(J,`${JSON.stringify({ts:s(),...f})}
496
+ `,"utf8")}}import{formatUserInputBlock as kN}from"@cline/shared";var qV={};q(qV,{toTeamProgressLifecycleEvent:()=>k2,sanitizeTeamName:()=>qX,reviveTeamStateDates:()=>y6,parseConfiguredAgentConfig:()=>oJ,loadConfiguredAgentConfigs:()=>E2,createWorkerReviewerTeam:()=>NV,createSpawnAgentTool:()=>G$,createDelegatedAgentConfigProvider:()=>K$,createDelegatedAgent:()=>P$,createConfiguredAgentTools:()=>h2,createAgentTeamsTools:()=>e$,createAgentTeam:()=>TW,buildTeamProgressSummary:()=>b2,buildDelegatedAgentConfig:()=>s$,buildConfiguredAgentToolName:()=>eJ,buildConfiguredAgentToolDescriptors:()=>f4,bootstrapAgentTeams:()=>W2,AgentTeamsRuntime:()=>_1,AgentTeam:()=>x2});import{existsSync as GN,readdirSync as FN,readFileSync as UN}from"node:fs";import{basename as UV,extname as RN,join as DN}from"node:path";import{resolveAgentConfigSearchPaths as LN}from"@cline/shared/storage";import DV from"yaml";import{z as N0}from"zod";var LV=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 ON(f){let $=f.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!$)throw Error("Missing YAML frontmatter block in agent config file.");let J=$[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=J;let Z,W=Array.from(f.matchAll(Q)).filter((j)=>j.index>=J);for(let j of W){let H=j.index,X=f.slice(J,H);try{let A=DV.parse(X);if(!A||typeof A!=="object"||Array.isArray(A))continue;LV.parse(A);let Y=f.slice(H+j[0].length);Z={frontmatter:X,body:Y}}catch{}}if(Z)return Z;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function RV(f){if(f===void 0)return;let $=Array.isArray(f)?f:f.split(",");return Array.from(new Set($.map((J)=>J.trim()).filter((J)=>J.length>0)))}function _N(f){return f.trim().toLowerCase()}function TN(f){let $=RN(f).toLowerCase();return $===".yml"||$===".yaml"}function oJ(f,$={}){let{frontmatter:J,body:Q}=ON(f),Z=DV.parse(J);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Agent config frontmatter must be a YAML mapping.");let W=LV.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:RV(W.tools),skills:RV(W.skills),providerId:W.providerId,modelId:W.modelId,maxIterations:W.maxIterations,systemPrompt:j,path:$.path}}function E2(f){let $=f.searchPaths??LN(f.workspaceRoot),J=new Map,Q=[];for(let W of $.filter(Boolean)){if(!GN(W))continue;let j;try{j=FN(W,{withFileTypes:!0})}catch(H){Q.push({path:W,error:H instanceof Error?H:Error(String(H))});continue}for(let H of j){if(!H.isFile()||!TN(H.name))continue;let X=DN(W,H.name);try{let A=UN(X,"utf8"),Y=oJ(A,{path:X}),V=_N(Y.name);if(!J.has(V))J.set(V,Y)}catch(A){Q.push({path:X,error:A instanceof Error?A:Error(String(A))})}}}return{configs:Array.from(J.values()).sort((W,j)=>(W.path?UV(W.path):W.name).localeCompare(j.path?UV(j.path):j.name)),errors:Q}}import{createTool as zN,zodToJsonSchema as MN}from"@cline/shared";import{z as OV}from"zod";var OW="subagent_",l5=64,NN=OV.object({prompt:OV.string().trim().min(1).describe("Task for the subagent to perform")});function qN(f){let $="",J=!0;for(let Q of f.trim().toLowerCase()){let Z=Q.charCodeAt(0);if(!(Z>=97&&Z<=122||Z>=48&&Z<=57||Q==="_")||Q==="_"){if(!J)$+="_",J=!0;continue}$+=Q,J=!1}return J?$.slice(0,-1):$}function yN(f){let $=2166136261;for(let J=0;J<f.length;J++)$^=f.charCodeAt(J),$=Math.imul($,16777619);return($>>>0).toString(36)}function eJ(f){let $=qN(f)||"agent",J=yN(f).slice(0,6),Q=`${OW}${$}`;if(Q.length<=l5)return Q;let Z=l5-OW.length-J.length-1,W=$.slice(0,Math.max(1,Z));return`${OW}${W}_${J}`.slice(0,l5)}function f4(f){let $=new Set,J=[];for(let Q of[...f].sort((Z,W)=>Z.name.localeCompare(W.name))){let Z=eJ(Q.name),W=Z,j=2;while($.has(W)){let H=`_${j++}`,X=Math.max(1,l5-H.length);W=`${Z.slice(0,X)}${H}`}$.add(W),J.push({toolName:W,config:Q})}return J}function wN(f,$){return{...f,providerId:$.providerId??f.providerId,modelId:$.modelId??f.modelId,maxIterations:$.maxIterations??f.maxIterations}}function h2(f){return f4(f.agents).map(({toolName:$,config:J})=>{return zN({name:$,description:`Use the "${J.name}" subagent: ${J.description}`,inputSchema:MN(NN),execute:async(Z,W)=>{let j=f.configProvider.getRuntimeConfig(),H=K$(wN(j,J)),X=f.createSubAgentTools?await f.createSubAgentTools(J,Z,W):[],A=P$({kind:"subagent",prompt:J.systemPrompt,configProvider:H,tools:X,maxIterations:J.maxIterations,parentAgentId:W.agentId,abortSignal:W.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),Y=A.getAgentId(),V=A.getConversationId(),B=W.agentId,K={systemPrompt:J.systemPrompt,task:Z.prompt};if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:Y,conversationId:V,parentAgentId:B,input:K})}catch{}try{let P=await A.run(Z.prompt),R={text:P.text,iterations:P.iterations,finishReason:P.finishReason,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Y,conversationId:V,parentAgentId:B,input:K,result:R,agentResult:P})}catch{}return R}catch(P){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Y,conversationId:V,parentAgentId:B,input:K,error:P instanceof Error?P:Error(String(P))})}catch{}throw P}},timeoutMs:300000,retryable:!1})})}function Uf(){return new Date().toISOString()}function _V(f,$){if($<=0)return 0;return Math.round(f/$*100)}function CN(f,$){let J=new Set;for(let Z of $)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let Q=new Set;for(let Z of f){if(Z.status==="finalized")continue;for(let W of Z.requiredSections)if(!J.has(`${Z.id}:${W}`))Q.add(`${Z.id}:${W}`)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function b2(f,$){let J={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},W={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},H=0,X=0;for(let G of $.members)if(J[G.status]+=1,G.role==="lead")H+=1;else X+=1;let A=[],Y=[],V=$.tasks.filter((G)=>G.status==="completed").length,B=new Map($.tasks.map((G)=>[G.id,G]));for(let G of $.tasks){if(Q[G.status]+=1,G.status==="blocked"){A.push(G.id);continue}if(G.status!=="pending")continue;if(G.dependsOn.every((U)=>{return B.get(U)?.status==="completed"}))Y.push(G.id)}let K=[],P,R=0;for(let G of $.runs){if(Z[G.status]+=1,G.status==="queued"||G.status==="running")K.push(G.id);let F=G.startedAt.getTime();if(F>=R)R=F,P=G.id}for(let G of $.outcomes)W[G.status]+=1;for(let G of $.outcomeFragments)j[G.status]+=1;return{teamName:f,updatedAt:Uf(),members:{total:$.members.length,byStatus:J,leadCount:H,teammateCount:X},tasks:{total:$.tasks.length,byStatus:Q,blockedTaskIds:A,readyTaskIds:Y,completionPct:_V(V,$.tasks.length)},runs:{total:$.runs.length,byStatus:Z,activeRunIds:K,latestRunId:P},outcomes:{total:$.outcomes.length,byStatus:W,finalizedPct:_V(W.finalized,$.outcomes.length),missingRequiredSections:CN($.outcomes,$.outcomeFragments)},fragments:{total:$.outcomeFragments.length,byStatus:j}}}function k2(f){let{event:$}=f;switch($.type){case"team_task_updated":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),taskId:$.task.id,agentId:$.task.assignee??$.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.run.error};case"run_progress":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.message};case"outcome_created":case"outcome_finalized":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),outcomeId:$.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),outcomeId:$.fragment.outcomeId,fragmentId:$.fragment.id,agentId:$.fragment.sourceAgentId};case"team_message":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),taskId:$.message.taskId,agentId:$.message.fromAgentId,message:$.message.subject};case"team_mission_log":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),taskId:$.entry.taskId,agentId:$.entry.agentId,message:$.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf(),agentId:$.agentId}}return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Uf()}}import{sanitizeFileName as SN,TeamMessageType as k}from"@cline/shared";import{nanoid as EN}from"nanoid";import{TeamMessageType as Zc}from"@cline/shared";function _W(f){if(typeof DOMException<"u"&&f instanceof DOMException&&f.name==="AbortError")return!0;if(!(f instanceof Error))return!1;return f.name==="AbortError"||f.message.toLowerCase().includes("aborted")}function TV(f,$){return f?.status==="stopped"&&_W($)}var hN=600000,zV="recovered_queued";function bN(f){return`This is an automatic recovery of interrupted team run ${f.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
497
497
 
498
- ${$.message}`}class S2{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,W]of Object.entries($))this.addAgent(J,W)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:b.AgentEvent,agentId:$,event:Z})}},W=new Z1(J);if(J.onEvent)W.subscribeEvents(J.onEvent);this.agents.set($,W),this.configs.set($,f)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let W=await J.run(f);return this.emitEvent({type:b.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let W=await J.continue(f);return this.emitEvent({type:b.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async runParallel($){let f=$.map(async(J)=>{let W=this.agents.get(J.agentId);if(!W)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:b.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);return this.emitEvent({type:b.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:b.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let W=this.agents.get(J.agentId);if(!W){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:b.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);this.emitEvent({type:b.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:b.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return f}async runPipeline($,f,J){let W=[],Z=f;for(let Q of $){let j=this.agents.get(Q);if(!j){W.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:b.TaskStart,agentId:Q,message:Z});try{let H=await j.run(Z);this.emitEvent({type:b.TaskEnd,agentId:Q,result:H}),W.push({agentId:Q,result:H});let X=$.indexOf(Q)+1;if(X<$.length){let A=$[X];Z=J?J(H,A):`Previous agent output:
498
+ ${f.message}`}class x2{agents=new Map;configs=new Map;onTeamEvent;constructor(f,$){if(this.onTeamEvent=$,f)for(let[J,Q]of Object.entries(f))this.addAgent(J,Q)}addAgent(f,$){if(this.agents.has(f))throw Error(`Agent with id "${f}" already exists in the team`);let J={...$,onEvent:(Z)=>{$.onEvent?.(Z),this.emitEvent({type:k.AgentEvent,agentId:f,event:Z})}},Q=new B$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);this.agents.set(f,Q),this.configs.set(f,$)}removeAgent(f){return this.configs.delete(f),this.agents.delete(f)}getAgent(f){return this.agents.get(f)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:k.TaskStart,agentId:f,message:$});try{let Q=await J.run($);return this.emitEvent({type:k.TaskEnd,agentId:f,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:k.TaskEnd,agentId:f,error:Z,messages:J.getMessages()}),Q}}async continueTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:k.TaskStart,agentId:f,message:$});try{let Q=await J.continue($);return this.emitEvent({type:k.TaskEnd,agentId:f,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:k.TaskEnd,agentId:f,error:Z,messages:J.getMessages()}),Q}}async runParallel(f){let $=f.map(async(J)=>{let Q=this.agents.get(J.agentId);if(!Q)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type: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($)}async runSequential(f){let $=[];for(let J of f){let Q=this.agents.get(J.agentId);if(!Q){$.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type: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}),$.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()}),$.push({agentId:J.agentId,result:void 0,error:W,metadata:J.metadata})}}return $}async runPipeline(f,$,J){let Q=[],Z=$;for(let W of f){let j=this.agents.get(W);if(!j){Q.push({agentId:W,result:void 0,error:Error(`Agent "${W}" not found in team`)});break}this.emitEvent({type:k.TaskStart,agentId:W,message:Z});try{let H=await j.run(Z);this.emitEvent({type:k.TaskEnd,agentId:W,result:H}),Q.push({agentId:W,result:H});let X=f.indexOf(W)+1;if(X<f.length){let A=f[X];Z=J?J(H,A):`Previous agent output:
499
499
  ${H.text}
500
500
 
501
- Please continue from here.`}}catch(H){let X=H instanceof Error?H:Error(String(H));this.emitEvent({type:b.TaskEnd,agentId:Q,error:X,messages:j.getMessages()}),W.push({agentId:Q,result:void 0,error:X});break}}return W}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function QQ($,f){return new S2($,f)}function JV($){let f=QQ({worker:$.worker,reviewer:$.reviewer}),J=f;return J.doAndReview=async(W)=>{let Z=await f.routeTo("worker",W),Q=await f.routeTo("reviewer",`Please review this work:
501
+ Please continue from here.`}}catch(H){let X=H instanceof Error?H:Error(String(H));this.emitEvent({type:k.TaskEnd,agentId:W,error:X,messages:j.getMessages()}),Q.push({agentId:W,result:void 0,error:X});break}}return Q}abortAll(){for(let f of this.agents.values())f.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function TW(f,$){return new x2(f,$)}function NV(f){let $=TW({worker:f.worker,reviewer:f.reviewer}),J=$;return J.doAndReview=async(Q)=>{let Z=await $.routeTo("worker",Q),W=await $.routeTo("reviewer",`Please review this work:
502
502
 
503
- ${Z.text}`);return{workerResult:Z,reviewResult:Q}},J}class Gf{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_${kN(IN(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,W=f?.markRead??!0,Z=f?.limit,Q=this.mailbox.filter((H)=>H.toAgentId===$&&(!J||!H.readAt)),j=typeof Z==="number"&&Z>0?Q.slice(Math.max(0,Q.length-Z)):Q;if(W){let H=new Date;for(let X of j)if(!X.readAt)X.readAt=H}return j.map((H)=>({...H}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,w2($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,w2($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,w2($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,w2(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,w2(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,w2(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let W={...f,apiTimeoutMs:xN,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let H=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,H},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:b.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new Z1(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);let Q={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,Q),this.emitEvent({type:b.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(W){if(!ZQ(W))throw W}J.status="stopped",this.emitEvent({type:b.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,W),this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),{...W}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:b.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let W=this.requireTask($);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...W}}completeTask($,f,J){let W=this.requireTask($);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=f;return this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...W}}async routeToTeammate($,f,J){let W=this.members.get($);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${$}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),Q=Z.length>0?`${this.buildMailboxNotification(Z)}
503
+ ${Z.text}`);return{workerResult:Z,reviewResult:W}},J}class _1{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor(f){this.teamName=f.teamName,this.teamId=`t_${SN(EN(10))}`,this.onTeamEvent=f.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,f.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,f.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,f.maxConcurrentRuns??2);let $=f.leadAgentId??"lead";this.members.set($,{agentId:$,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(f){return this.members.get(f)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((f)=>f.role==="teammate").map((f)=>f.agentId)}getTask(f){return this.tasks.get(f)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(f){return Array.from(this.tasks.values()).map(($)=>{let J=this.getUnresolvedDependencies($);return{...$,blockedBy:J,isReady:$.status==="pending"&&!$.assignee&&J.length===0}}).filter(($)=>{if(f?.status&&$.status!==f.status)return!1;if(f?.assignee&&$.assignee!==f.assignee)return!1;return!0})}listMissionLog(f){if(!f||f<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-f))}listMailbox(f,$){let J=$?.unreadOnly??!0,Q=$?.markRead??!0,Z=$?.limit,W=this.mailbox.filter((H)=>H.toAgentId===f&&(!J||!H.readAt)),j=typeof Z==="number"&&Z>0?W.slice(Math.max(0,W.length-Z)):W;if(Q){let H=new Date;for(let X of j)if(!X.readAt)X.readAt=H}return j.map((H)=>({...H}))}getSnapshot(){let f={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())f[J.status]++;let $={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())$[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:f,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:$}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((f)=>({agentId:f.agentId,role:f.role,description:f.description,status:f.status})),tasks:Array.from(this.tasks.values()).map((f)=>({...f})),mailbox:this.mailbox.map((f)=>({...f})),missionLog:this.missionLog.map((f)=>({...f})),runs:Array.from(this.runs.values()).map((f)=>({...f})),outcomes:Array.from(this.outcomes.values()).map((f)=>({...f})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((f)=>({...f}))}}hydrateState(f){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of f.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...f.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...f.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of f.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of f.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of f.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let $=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of $)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of f.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,I2(f.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,I2(f.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,I2(f.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,I2((f.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,I2((f.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,I2((f.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive(f){let $=this.members.get(f);return!!$&&$.role==="teammate"&&!!$.agent}spawnTeammate({agentId:f,config:$}){let J=this.members.get(f);if(J&&J.role!=="teammate")throw Error(`Team member "${f}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${f}" is currently running and cannot be respawned`);let Q={...$,apiTimeoutMs:hN,consumePendingUserMessage:()=>{let j=this.members.get(f);if(!j||!j.pendingSteerMessage)return;let H=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,H},onEvent:(j)=>{$.onEvent?.(j),this.emitEvent({type:k.AgentEvent,agentId:f,event:j}),this.trackMeaningfulEvent(f,j)}},Z=new B$(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);let W={agentId:f,role:"teammate",description:$.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set(f,W),this.emitEvent({type:k.TeammateSpawned,agentId:f,role:$.role,teammate:{rolePrompt:$.systemPrompt,modelId:$.modelId,maxIterations:$.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:W.agentId,role:W.role,description:W.description,status:W.status}}shutdownTeammate(f,$){let J=this.members.get(f);if(!J||J.role!=="teammate")throw Error(`Teammate "${f}" was not found`);try{J.agent?.abort()}catch(Q){if(!_W(Q))throw Q}J.status="stopped",this.emitEvent({type:k.TeammateShutdown,agentId:f,reason:$})}updateTeammateConnections(f){for(let $ of this.members.values()){if($.role!=="teammate"||!$.agent)continue;$.agent.updateConnection(f)}}createTask(f){let $=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,Q={id:$,title:f.title,description:f.description,status:f.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:f.createdBy,assignee:f.assignee,dependsOn:f.dependsOn??[]};return this.tasks.set($,Q),this.emitEvent({type:k.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask(f,$){let J=this.requireTask(f);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=$,J.updatedAt=new Date,this.emitEvent({type:k.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:$,taskId:f,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask(f,$,J){let Q=this.requireTask(f);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=J,this.emitEvent({type:k.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:$,taskId:f,kind:"blocked",summary:J}),{...Q}}completeTask(f,$,J){let Q=this.requireTask(f);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=J,!Q.assignee)Q.assignee=$;return this.emitEvent({type:k.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:$,taskId:f,kind:"done",summary:J}),{...Q}}async routeToTeammate(f,$,J){let Q=this.members.get(f);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${f}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:k.TaskStart,agentId:f,message:$});try{let Z=this.listMailbox(f,{unreadOnly:!0,markRead:!0}),W=Z.length>0?`${this.buildMailboxNotification(Z)}
504
504
 
505
- ${f}`:f,j=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:b.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:b.TaskEnd,agentId:$,error:Q,messages:W.agent.getMessages()}),!eY(W,Q))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get($)?.status!=="stopped")W.status="idle"}}startTeammateRun($,f,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:W,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,Z),this.runQueue.push(W),this.emitEvent({type:b.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[W]=this.runQueue.splice(J,1),Z=W?this.runs.get(W):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let Q=this.runs.get(this.runQueue[Z]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>f)f=Q.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===$V;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:b.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let W=f?mN($):$.message,Z=await this.routeToTeammate($.agentId,W,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:b.RunCompleted,run:{...$}})}catch(W){let Z=W instanceof Error?W.message:String(W??"Unknown error");$.error=Z,$.endedAt=new Date;let Q=this.members.get($.agentId);if(eY(Q,W))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:b.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:b.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 fV(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await fV($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf($);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:b.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:b.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=$V,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:b.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:b.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,W,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let Q=this.members.get(f);if(!Q)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:W,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:b.TeamMessage,message:{...j}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,W){let Z=[];for(let Q of this.members.values()){if(Q.agentId===$)continue;if(Q.role==="lead")continue;Z.push(this.sendMessage($,Q.agentId,f,J,W?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:b.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:b.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:b.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:b.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let W of f.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:b.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(!ZQ(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==$||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:b.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${W}`}recordProgressStep($,f,J,W=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let Q=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
506
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function fV($){return new Promise((f)=>setTimeout(f,$))}function w2($,f){let J=0;for(let W of $){if(!W.startsWith(f))continue;let Z=Number.parseInt(W.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function jQ($,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}),q5($);break}default:break}}async function HQ($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let W=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",$,f.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function XQ($,f,J,W){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:q2({teamName:Z,sessionId:f,event:J}),summary:y2(Z,$.runtime.teamRuntime.exportState())}})}function pJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function AQ($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&pJ($)}function q5($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function YQ($){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 VQ($,f){let J=f.map((Q)=>{let j=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)j.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")j.push(` iterations=${Q.iterations}`);if(Q.error)j.push(` error=${Q.error}`);return j.join("")}),W=$.activeTeamRunIds.size,Z=W>0?`There are still ${W} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return rJ(`System-delivered teammate async run updates:
505
+ ${$}`:$,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:k.TaskEnd,agentId:f,result:j}),this.recordProgressStep(f,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:k.TaskEnd,agentId:f,error:W,messages:Q.agent.getMessages()}),!TV(Q,W))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get(f)?.status!=="stopped")Q.status="idle"}}startTeammateRun(f,$,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,agentId:f,taskId:J?.taskId,status:"queued",message:$,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,Z),this.runQueue.push(Q),this.emitEvent({type:k.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let f;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let $=this.selectNextDispatchableQueuedRun();f=$.nextDelayedAttemptAt;let J=$.index;if(J<0){this.scheduleQueuedRunDispatch(f);return}let[Q]=this.runQueue.splice(J,1),Z=Q?this.runs.get(Q):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch(f)}selectNextDispatchableQueuedRun(){let f=-1,$=Number.NEGATIVE_INFINITY,J,Q=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let W=this.runs.get(this.runQueue[Z]);if(!W||W.status!=="queued")continue;if(W.nextAttemptAt&&W.nextAttemptAt.getTime()>Q){if(!J||W.nextAttemptAt<J)J=W.nextAttemptAt;continue}if(W.priority>$)$=W.priority,f=Z}return{index:f,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch(f){if(!f)return;let $=Math.max(0,f.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},$)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let f=0;for(let $ of this.runs.values())if($.status==="running")f++;return f}async executeQueuedRun(f){let $=f.currentActivity===zV;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:k.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let Q=$?bN(f):f.message,Z=await this.routeToTeammate(f.agentId,Q,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=Z,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:k.RunCompleted,run:{...f}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");f.error=Z,f.endedAt=new Date;let W=this.members.get(f.agentId);if(TV(W,Q))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:k.RunCancelled,run:{...f},reason:Z});else if(f.retryCount<f.maxRetries)f.retryCount++,f.status="queued",f.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**f.retryCount)),this.runQueue.push(f.id),this.recordRunProgress(f,`retry_scheduled_${f.retryCount}`);else f.status="failed",f.currentActivity="failed",this.emitEvent({type:k.RunFailed,run:{...f}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns(f){let $=f?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!$&&!["running","queued"].includes(J.status))return!1;if(f?.status&&J.status!==f.status)return!1;if(f?.agentId&&J.agentId!==f.agentId)return!1;return!0}).map((J)=>({...J}))}getRun(f){let $=this.runs.get(f);return $?{...$}:void 0}async awaitRun(f,$=250){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);while(J.status==="queued"||J.status==="running")await MV($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await MV(f);return this.listRuns()}cancelRun(f,$){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=$,J.endedAt=new Date,J.currentActivity="cancelled";let Q=this.runQueue.indexOf(f);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:k.RunCancelled,run:{...J},reason:$}),{...J}}recoverActiveRuns(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let Q=this.members.get(J.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type: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=f,J.currentActivity=zV,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:k.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),$}markStaleRunsInterrupted(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=f,J.endedAt=new Date,J.currentActivity="interrupted",$.push({...J}),this.emitEvent({type:k.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,Q,Z){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let W=this.members.get($);if(!W)throw Error(`Unknown recipient "${$}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:k.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast(f,$,J,Q){let Z=[];for(let W of this.members.values()){if(W.agentId===f)continue;if(W.role==="lead")continue;Z.push(this.sendMessage(f,W.agentId,$,J,Q?.taskId))}return Z}appendMissionLog(f){if(!this.members.has(f.agentId))throw Error(`Unknown team member "${f.agentId}"`);let $={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:f.agentId,taskId:f.taskId,kind:f.kind,summary:f.summary,evidence:f.evidence,nextAction:f.nextAction};this.missionLog.push($);let J=this.members.get(f.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:k.TeamMissionLog,entry:{...$}}),{...$}}createOutcome(f){let $={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:f.title,status:"draft",requiredSections:[...new Set(f.requiredSections)],createdBy:f.createdBy,createdAt:new Date};return this.outcomes.set($.id,$),this.emitEvent({type:k.OutcomeCreated,outcome:{...$}}),{...$}}listOutcomes(){return Array.from(this.outcomes.values()).map((f)=>({...f}))}attachOutcomeFragment(f){let $=this.outcomes.get(f.outcomeId);if(!$)throw Error(`Outcome "${f.outcomeId}" was not found`);if(!$.requiredSections.includes(f.section))throw Error(`Section "${f.section}" is not part of outcome "${f.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:f.outcomeId,section:f.section,sourceAgentId:f.sourceAgentId,sourceRunId:f.sourceRunId,content:f.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),$.status==="draft")$.status="in_review";return this.emitEvent({type:k.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment(f){let $=this.outcomeFragments.get(f.fragmentId);if(!$)throw Error(`Fragment "${f.fragmentId}" was not found`);return $.status=f.approved?"reviewed":"rejected",$.reviewedBy=f.reviewedBy,$.reviewedAt=new Date,this.emitEvent({type:k.OutcomeFragmentReviewed,fragment:{...$}}),{...$}}listOutcomeFragments(f){return Array.from(this.outcomeFragments.values()).filter(($)=>$.outcomeId===f).map(($)=>({...$}))}finalizeOutcome(f){let $=this.outcomes.get(f);if(!$)throw Error(`Outcome "${f}" was not found`);let J=this.listOutcomeFragments(f);for(let Q of $.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:k.OutcomeFinalized,outcome:{...$}}),{...$}}cleanup(){for(let f of this.members.values())if(f.role==="teammate"&&f.runningCount>0)throw Error(`Cannot cleanup team while teammate "${f.agentId}" is still running`);if(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let f of this.members.values())if(f.role==="teammate")try{f.agent?.abort()}catch($){if(!_W($))throw $}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[f,$]of this.members.entries())if($.role==="teammate")this.members.delete(f)}requireTask(f){let $=this.tasks.get(f);if(!$)throw Error(`Task "${f}" was not found`);return $}assertDependenciesResolved(f){let $=this.getUnresolvedDependencies(f);if($.length>0)throw Error(`Task "${f.id}" is blocked by "${$[0]}"`)}getUnresolvedDependencies(f){return f.dependsOn.filter(($)=>{let J=this.tasks.get($);return!J||J.status!=="completed"})}trackMeaningfulEvent(f,$){if(this.recordRunActivityFromAgentEvent(f,$),$.type==="iteration_end"&&$.hadToolCalls){this.recordProgressStep(f,`Completed iteration ${$.iteration} with ${$.toolCallCount} tool call(s)`);return}if($.type==="content_end"&&$.contentType==="tool"&&!$.error){this.recordProgressStep(f,`Finished tool "${$.toolName??"unknown"}"`);return}if($.type==="done"){this.appendMissionLog({agentId:f,kind:"done",summary:`Completed a delegated run (${$.iterations} iterations)`});return}if($.type==="error")this.appendMissionLog({agentId:f,kind:"error",summary:$.error.message})}recordRunActivityFromAgentEvent(f,$){let J;switch($.type){case"iteration_start":J=`iteration_${$.iteration}_started`;break;case"content_start":if($.contentType==="tool")J=`running_tool_${$.toolName??"unknown"}`;break;case"content_end":if($.contentType==="tool")J=$.error?this.formatProgressErrorActivity(`tool_${$.toolName??"unknown"}_error`,$.error):`finished_tool_${$.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",$.error.message);break;default:break}if(!J)return;for(let Q of this.runs.values()){if(Q.agentId!==f||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:k.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${Q}`}recordProgressStep(f,$,J,Q=!1){this.missionStepCounter++;let Z=this.members.get(f);if(!Z)return;let W=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!Q&&W<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:f,taskId:J,kind:"progress",summary:$})}buildMailboxNotification(f){if(f.length===0)return"";let $=[`[MAILBOX] You have ${f.length} unread message(s):`];for(let J of f)$.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),$.push(J.body);return $.push("---"),$.join(`
506
+ `)}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function MV(f){return new Promise(($)=>setTimeout($,f))}function I2(f,$){let J=0;for(let Q of f){if(!Q.startsWith($))continue;let Z=Number.parseInt(Q.slice($.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function zW(f,$){switch($.type){case"run_queued":case"run_started":f.activeTeamRunIds.add($.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if($.type==="run_failed")J=$.run.error;else if($.type==="run_cancelled"||$.type==="run_interrupted")J=$.run.error??$.reason;f.activeTeamRunIds.delete($.run.id),f.pendingTeamRunUpdates.push({runId:$.run.id,agentId:$.run.agentId,taskId:$.run.taskId,status:$.type.replace("run_",""),error:J,iterations:$.run.result?.iterations}),p5(f);break}default:break}}async function MW(f,$,J){switch($.type){case"run_progress":await J("onTeamTaskProgress",f,$.run.agentId,$.message,{kind:$.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if($.event.type==="content_start"&&$.event.contentType==="text"&&typeof $.event.text==="string"){let Q=$.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await J("onTeamTaskProgress",f,$.agentId,Q,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",f,$.agentId,$.message);break;case"task_end":{if($.error)await J("onTeamTaskEnd",f,$.agentId,"failed",`[error] ${$.error.message}`,void 0,$.messages);else if($.result?.finishReason==="aborted")await J("onTeamTaskEnd",f,$.agentId,"cancelled","[done] aborted",$.result,$.result.messages);else await J("onTeamTaskEnd",f,$.agentId,"completed",`[done] ${$.result?.finishReason??"completed"}`,$.result,$.result?.messages);break}default:break}}function NW(f,$,J,Q){if(!f.runtime.teamRuntime)return;let Z=f.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:$,teamName:Z,lifecycle:k2({teamName:Z,sessionId:$,event:J}),summary:b2(Z,f.runtime.teamRuntime.exportState())}})}function $4(f){return f.activeTeamRunIds.size>0||f.pendingTeamRunUpdates.length>0}function qW(f,$){if(f.aborting)return!1;if(!($==="completed"||$==="max_iterations"))return!1;return f.config.enableAgentTeams===!0&&$4(f)}function p5(f){let $=f.teamRunWaiters.splice(0);for(let J of $)J()}async function yW(f){while(!0){if(f.aborting)return[];if(f.pendingTeamRunUpdates.length>0){let $=[...f.pendingTeamRunUpdates];return f.pendingTeamRunUpdates.length=0,$}if(f.activeTeamRunIds.size===0)return[];await new Promise(($)=>{f.teamRunWaiters.push($)})}}function wW(f,$){let J=$.map((W)=>{let j=[`- ${W.runId} (${W.agentId}) -> ${W.status}`];if(W.taskId)j.push(` task=${W.taskId}`);if(typeof W.iterations==="number")j.push(` iterations=${W.iterations}`);if(W.error)j.push(` error=${W.error}`);return j.join("")}),Q=f.activeTeamRunIds.size,Z=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return J4(`System-delivered teammate async run updates:
507
507
  ${J.join(`
508
508
  `)}
509
509
 
510
- ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var BQ=4;class u${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 JQ($,f.messagesArtifactUploader,f.logger),this.teamChildren=new y5($,this.manifestStore,(J,W,Z)=>this.toPersistedMessages(J,W,Z),u$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?A6(f.messages,f,J):X6($)}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(),W=J.length>0?J:`${Date.now()}_${uN(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),j=l8({metadata:$.metadata,prompt:$.prompt}),H={version:1,session_id:W,source:$.source,pid:$.pid,started_at:f,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:W,source:$.source,pid:$.pid,startedAt:f,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:H.prompt??null,metadata:j1(H.metadata),hookPath:"",messagesPath:Z,updatedAt:s()}),this.manifestStore.initializeMessagesFile(W,Z,f),this.manifestStore.writeSessionManifest(Q,H),{manifestPath:Q,messagesPath:Z,manifest:H}}async updateSessionStatus($,f,J){let W;if((await rH(()=>this.adapter.getSession($),async(Q)=>{return W=W0(f)?void 0:s(),this.adapter.updateSession({sessionId:$,status:f,endedAt:W??null,exitCode:W0(f)?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},BQ)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession($){for(let f=0;f<BQ;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,Z=$.metadata!==void 0?j1($.metadata)??{}:j1(W)??{},Q=i1(typeof W?.title==="string"?W.title:void 0),j=$.title!==void 0?i1($.title):Q??CZ($.prompt);if(j)Z.title=j;else delete Z.title;let H=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:H?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:A,manifest:Y}=this.manifestStore.readManifestFile($.sessionId);if(Y){if($.prompt!==void 0)Y.prompt=$.prompt??void 0;let V=$.metadata!==void 0?j1($.metadata)??{}:j1(Y.metadata)??{};if(j)V.title=j;Y.metadata=Object.keys(V).length>0?V:void 0,this.manifestStore.writeSessionManifest(A,Y)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let W=X6(f);return this.manifestStore.persistSessionMessages($,W,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,W,Z,Q){return this.teamChildren.onTeamTaskEnd($,f,J,W,Z,Q)}onTeamTaskProgress($,f,J,W){return this.teamChildren.onTeamTaskProgress($,f,J,W)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if(W0($.status)===!1||this.isPidAlive($.pid))return $;let f=s(),J=u$.STALE_REASON;for(let W=0;W<BQ;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(W0(Z.status)===!1)return Z;let Q={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:u$.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:Q,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let H=pH(Z,{status:"failed",endedAt:f,exitCode:1,metadata:Q}),{path:X}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(X,H),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,u$.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:Q,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let Q=j1(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),H=i1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),X=H?{...Q??{},title:H}:Q;return{...Z,metadata:X}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),W=0;for(let Z of J){let Q=await this.reconcileDeadRunningSession(Z);if(Q&&Q.status!==Z.status)W++}return W}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(W.map(async(Z)=>{await eZ(Z.cwd,Z.sessionId),VJ(Z.messagesPath),VJ(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await eZ(J.cwd,f),VJ(J.messagesPath),VJ(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)W.add(vN(Z));for(let Z of W)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function GQ(){return new Date().toISOString()}function jV($,f){let J=`${$}.tmp`;lN(J,`${JSON.stringify(f,null,2)}
511
- `,"utf8"),dN(J,$)}class HV{sessionsDirPath;constructor($=pN()){this.sessionsDirPath=$}ensureSessionsDir(){if(!KQ(this.sessionsDirPath))cN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return QV(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return QV(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!KQ($))return{version:1,sessions:{}};try{let f=JSON.parse(ZV($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){jV(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!KQ($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(ZV($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){jV(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let W=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:W,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:GQ()};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:GQ()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),W=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!W)return;return W.consumedAt=GQ(),this.writeQueue(J),W.task}}class PQ extends u${constructor($,f={}){super(new HV($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}var YV={};w(YV,{CoreSessionService:()=>U$});import{existsSync as rN,mkdirSync as iN}from"node:fs";import{resolveSessionDataDir as nN}from"@cline/shared/storage";var UQ=`
510
+ ${Z}`,f.config.mode)}function J4(f,$){return kN(f,$==="plan"?"plan":$==="yolo"?"yolo":"act")}var CW=4;class rf{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor(f,$={}){this.adapter=f;this.manifestStore=new DW(f,$.messagesArtifactUploader,$.logger),this.teamChildren=new d5(f,this.manifestStore,(J,Q,Z)=>this.toPersistedMessages(J,Q,Z),rf.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages(f,$,J){if(!f)return;return $?h6($.messages,$,J):E6(f)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest(f,$){this.manifestStore.writeSessionManifest(f,$)}readSessionManifest(f){return this.manifestStore.readSessionManifest(f)}async createRootSessionWithArtifacts(f){let $=f.startedAt??s(),J=f.sessionId.trim(),Q=J.length>0?J:`${Date.now()}_${xN(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(Q),W=this.manifestStore.artifacts.sessionManifestPath(Q),j=WJ({metadata:f.metadata,prompt:f.prompt}),H={version:1,session_id:Q,source:f.source,pid:f.pid,started_at:$,status:"running",interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:Q,source:f.source,pid:f.pid,startedAt:$,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:H.prompt??null,metadata:F$(H.metadata),hookPath:"",messagesPath:Z,updatedAt:s()}),this.manifestStore.initializeMessagesFile(Q,Z,$),this.manifestStore.writeSessionManifest(W,H),{manifestPath:W,messagesPath:Z,manifest:H}}async updateSessionStatus(f,$,J){let Q;if((await mX(()=>this.adapter.getSession(f),async(W)=>{return Q=J0($)?void 0:s(),this.adapter.updateSession({sessionId:f,status:$,endedAt:Q??null,exitCode:J0($)?null:typeof J==="number"?J:null,expectedStatusLock:W.statusLock})},CW)).updated){if($==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions(f,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession(f){for(let $=0;$<CW;$++){let J=await this.adapter.getSession(f.sessionId);if(!J)return{updated:!1};let Q=J.metadata??void 0,Z=f.metadata!==void 0?F$(f.metadata)??{}:F$(Q)??{},W=Q1(typeof Q?.title==="string"?Q.title:void 0),j=f.title!==void 0?Q1(f.title):W??AZ(f.prompt);if(j)Z.title=j;else delete Z.title;let H=f.metadata!==void 0||f.prompt!==void 0||f.title!==void 0;if(!(await this.adapter.updateSession({sessionId:f.sessionId,prompt:f.prompt,metadata:H?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:A,manifest:Y}=this.manifestStore.readManifestFile(f.sessionId);if(Y){if(f.prompt!==void 0)Y.prompt=f.prompt??void 0;let V=f.metadata!==void 0?F$(f.metadata)??{}:F$(Y.metadata)??{};if(j)V.title=j;Y.metadata=Object.keys(V).length>0?V:void 0,this.manifestStore.writeSessionManifest(A,Y)}return{updated:!0}}return{updated:!1}}queueSpawnRequest(f){return this.teamChildren.queueSpawnRequest(f)}upsertSubagentSession(f){return this.teamChildren.upsertSubagentSession(f)}upsertSubagentSessionFromHook(f){return this.teamChildren.upsertSubagentSessionFromHook(f)}appendSubagentHookAudit(f,$){return this.teamChildren.appendSubagentHookAudit($),Promise.resolve()}persistSessionMessages(f,$,J){let Q=E6($);return this.manifestStore.persistSessionMessages(f,Q,J)}applySubagentStatus(f,$){return this.teamChildren.applySubagentStatus(f,$)}applySubagentStatusBySessionId(f,$){return this.teamChildren.applySubagentStatusBySessionId(f,$)}applyStatusToRunningChildSessions(f,$){return this.teamChildren.applyStatusToRunningChildSessions(f,$)}onTeamTaskStart(f,$,J){return this.teamChildren.onTeamTaskStart(f,$,J)}onTeamTaskEnd(f,$,J,Q,Z,W){return this.teamChildren.onTeamTaskEnd(f,$,J,Q,Z,W)}onTeamTaskProgress(f,$,J,Q){return this.teamChildren.onTeamTaskProgress(f,$,J,Q)}handleSubAgentStart(f,$){return this.teamChildren.handleSubAgentStart(f,$)}handleSubAgentEnd(f,$){return this.teamChildren.handleSubAgentEnd(f,$)}isPidAlive(f){if(!Number.isFinite(f)||f<=0)return!1;try{return process.kill(Math.floor(f),0),!0}catch($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="EPERM"}}async reconcileDeadRunningSession(f){if(J0(f.status)===!1||this.isPidAlive(f.pid))return f;let $=s(),J=rf.STALE_REASON;for(let Q=0;Q<CW;Q++){let Z=await this.adapter.getSession(f.sessionId);if(!Z)return;if(J0(Z.status)===!1)return Z;let W={...Z.metadata??{},terminal_marker:J,terminal_marker_at:$,terminal_marker_pid:Z.pid,terminal_marker_source:rf.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:$,exitCode:1,metadata:W,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let H=gX(Z,{status:"failed",endedAt:$,exitCode:1,metadata:W}),{path:X}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(X,H),this.manifestStore.appendStaleSessionHookLog($,Z.sessionId,Z.pid,J,rf.STALE_SOURCE),{...Z,status:"failed",endedAt:$,exitCode:1,metadata:W,statusLock:j.statusLock,updatedAt:$}}return await this.adapter.getSession(f.sessionId)}async listSessions(f=200){let $=Math.max(1,Math.floor(f)),J=Math.min($*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,$).map((Z)=>{let W=F$(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),H=Q1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),X=H?{...W??{},title:H}:W;return{...Z,metadata:X}})}async reconcileDeadSessions(f=2000){let $=Math.max(1,Math.floor(f)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:$,status:Z})))).flat(),Q=0;for(let Z of J){let W=await this.reconcileDeadRunningSession(Z);if(W&&W.status!==Z.status)Q++}return Q}async deleteSession(f){let $=f.trim();if(!$)throw Error("session id is required");let J=await this.adapter.getSession($);if(!J)return{deleted:!1};if(await this.adapter.deleteSession($,!1),!J.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$});await this.adapter.deleteSession($,!0),await Promise.allSettled(Q.map(async(Z)=>{await CZ(Z.cwd,Z.sessionId),TJ(Z.messagesPath),TJ(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await CZ(J.cwd,$),TJ(J.messagesPath),TJ(this.manifestStore.artifacts.sessionManifestPath($,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty($);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir($)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)Q.add(IN(Z));for(let Z of Q)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function EW(){return new Date().toISOString()}function CV(f,$){let J=`${f}.tmp`;vN(J,`${JSON.stringify($,null,2)}
511
+ `,"utf8"),mN(J,f)}class SV{sessionsDirPath;constructor(f=cN()){this.sessionsDirPath=f}ensureSessionsDir(){if(!SW(this.sessionsDirPath))gN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return wV(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return wV(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let f=this.indexPath();if(!SW(f))return{version:1,sessions:{}};try{let $=JSON.parse(yV(f,"utf8"));if($?.version===1&&$.sessions)return $}catch{}return{version:1,sessions:{}}}writeIndex(f){CV(this.indexPath(),f)}readQueue(){let f=this.spawnQueuePath();if(!SW(f))return{version:1,nextId:1,requests:[]};try{let $=JSON.parse(yV(f,"utf8"));if($?.version===1&&typeof $.nextId==="number"&&Array.isArray($.requests))return $}catch{}return{version:1,nextId:1,requests:[]}}writeQueue(f){CV(this.spawnQueuePath(),f)}async upsertSession(f){let $=this.readIndex();$.sessions[f.sessionId]=f,this.writeIndex($)}async getSession(f){return this.readIndex().sessions[f]}async listSessions(f){return Object.values(this.readIndex().sessions).filter(($)=>f.parentSessionId!==void 0?$.parentSessionId===f.parentSessionId:!0).filter(($)=>f.status!==void 0?$.status===f.status:!0).sort(($,J)=>J.startedAt.localeCompare($.startedAt)).slice(0,f.limit)}async updateSession(f){let $=this.readIndex(),J=$.sessions[f.sessionId];if(!J)return{updated:!1,statusLock:0};if(f.expectedStatusLock!==void 0&&J.statusLock!==f.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let Q=f.expectedStatusLock!==void 0?f.expectedStatusLock+1:J.statusLock,Z={...J,status:f.status??J.status,endedAt:f.endedAt!==void 0?f.endedAt:J.endedAt??null,exitCode:f.exitCode!==void 0?f.exitCode:J.exitCode??null,prompt:f.prompt!==void 0?f.prompt:J.prompt??null,metadata:f.metadata!==void 0?f.metadata??null:J.metadata??null,parentSessionId:f.parentSessionId!==void 0?f.parentSessionId??null:J.parentSessionId??null,parentAgentId:f.parentAgentId!==void 0?f.parentAgentId??null:J.parentAgentId??null,agentId:f.agentId!==void 0?f.agentId??null:J.agentId??null,conversationId:f.conversationId!==void 0?f.conversationId??null:J.conversationId??null,statusLock:Q,isSubagent:f.setRunning||f.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:EW()};if(f.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return $.sessions[f.sessionId]=Z,this.writeIndex($),{updated:!0,statusLock:Z.statusLock}}async deleteSession(f,$){let J=this.readIndex();if(!J.sessions[f])return!1;if(delete J.sessions[f],$){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===f)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest(f){let $=this.readQueue();$.requests.push({id:$.nextId,rootSessionId:f.rootSessionId,parentAgentId:f.parentAgentId,task:f.task,systemPrompt:f.systemPrompt,createdAt:EW()}),$.nextId+=1,this.writeQueue($)}async claimSpawnRequest(f,$){let J=this.readQueue(),Q=J.requests.find((Z)=>Z.rootSessionId===f&&Z.parentAgentId===$&&!Z.consumedAt);if(!Q)return;return Q.consumedAt=EW(),this.writeQueue(J),Q.task}}class hW extends rf{constructor(f,$={}){super(new SV(f),$)}ensureSessionsDir(){return super.ensureSessionsDir()}}var bV={};q(bV,{CoreSessionService:()=>Rf});import{existsSync as uN,mkdirSync as dN}from"node:fs";import{resolveSessionDataDir as lN}from"@cline/shared/storage";var bW=`
512
512
  session_id AS sessionId,
513
513
  source,
514
514
  pid,
@@ -535,37 +535,37 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
535
535
  metadata_json AS metadata,
536
536
  hook_path AS hookPath,
537
537
  messages_path AS messagesPath,
538
- updated_at AS updatedAt`;function FQ($){$.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 RQ($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function XV($){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 AV{store;sessionsDirPath;constructor($,f=nN()){this.store=$;this.sessionsDirPath=f}ensureSessionsDir(){if(!rN(this.sessionsDirPath))iN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
538
+ updated_at AS updatedAt`;function kW(f){f.interactive=f.interactive===1,f.enableTools=f.enableTools===1,f.enableSpawn=f.enableSpawn===1,f.enableTeams=f.enableTeams===1,f.isSubagent=f.isSubagent===1;let $=f.metadata;if(typeof $==="string"&&$.trim())try{let J=JSON.parse($);f.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{f.metadata=null}else f.metadata=null;return f}function IW(f){if(!f||Object.keys(f).length===0)return null;return JSON.stringify(f)}function EV(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class hV{store;sessionsDirPath;constructor(f,$=lN()){this.store=f;this.sessionsDirPath=$}ensureSessionsDir(){if(!uN(this.sessionsDirPath))dN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
539
539
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
540
540
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
541
541
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
542
542
  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,RQ($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let f=this.store.queryOne(`SELECT ${UQ} FROM sessions WHERE session_id = ?`,[$]);return f?FQ(f):void 0}async listSessions($){let f=[],J=[];if($.parentSessionId)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.status)f.push("status = ?"),J.push($.status);let W=f.length>0?`WHERE ${f.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${UQ}
543
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,f.statusLock,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.isSubagent?1:0,f.prompt??null,IW(f.metadata),"",f.hookPath??"",f.messagesPath??null,f.updatedAt])}async getSession(f){let $=this.store.queryOne(`SELECT ${bW} FROM sessions WHERE session_id = ?`,[f]);return $?kW($):void 0}async listSessions(f){let $=[],J=[];if(f.parentSessionId)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.status)$.push("status = ?"),J.push(f.status);let Q=$.length>0?`WHERE ${$.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${bW}
544
544
  FROM sessions
545
- ${W}
545
+ ${Q}
546
546
  ORDER BY started_at DESC
547
- LIMIT ?`,[...J,$.limit]).map(FQ)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
547
+ LIMIT ?`,[...J,f.limit]).map(kW)}async updateSession(f){if(f.setRunning){if(f.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
548
548
  SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
549
549
  parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
550
550
  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(RQ($.metadata));if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId??null);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId??null);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId??null);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId??null);if(f.length===0){let j=await this.getSession($.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let W=0;if($.expectedStatusLock!==void 0)W=$.expectedStatusLock+1,f.push("status_lock = ?"),J.push(W);f.push("updated_at = ?"),J.push(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)W=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:W}}async deleteSession($,f){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
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
551
+ WHERE session_id = ? AND status_lock = ?`,[s(),f.expectedStatusLock+1,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.prompt??null,f.sessionId,f.expectedStatusLock]).changes??0)>0,statusLock:f.expectedStatusLock+1}}let $=[],J=[];if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt??null);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(IW(f.metadata));if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId??null);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId??null);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId??null);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId??null);if($.length===0){let j=await this.getSession(f.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let Q=0;if(f.expectedStatusLock!==void 0)Q=f.expectedStatusLock+1,$.push("status_lock = ?"),J.push(Q);$.push("updated_at = ?"),J.push(s());let Z=`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`;if(J.push(f.sessionId),f.expectedStatusLock!==void 0)Z+=" AND status_lock = ?",J.push(f.expectedStatusLock);if((this.store.run(Z,J).changes??0)===0)return{updated:!1,statusLock:0};if(f.expectedStatusLock===void 0)Q=(await this.getSession(f.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession(f,$){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}async enqueueSpawnRequest(f){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
552
+ VALUES (?, ?, ?, ?, ?, NULL)`,[f.rootSessionId,f.parentAgentId,f.task??null,f.systemPrompt??null,s()])}async claimSpawnRequest(f,$){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
553
553
  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 U$ extends u${store;constructor($,f={}){super(new AV($,f.sessionArtifactsDir),f);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
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 Rf extends rf{store;constructor(f,$={}){super(new hV(f,$.sessionArtifactsDir),$);this.store=f}createRootSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
555
555
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
556
556
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
557
557
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
558
558
  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 aN($){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 iJ,nJ;function tN($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;c4(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function sN($){await $.reconcileDeadSessions?.().catch(()=>{})}function KV($){try{let f=new G$;return f.init(),new U$(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),BV($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new PQ(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function VV($,f,J){return new F$({sessionService:J??$.sessionService??KV($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function DQ($){if(iJ)return iJ;if(nJ)return await nJ;return nJ=(async()=>{return iJ=KV($),await sN(iJ),iJ})().finally(()=>{nJ=void 0}),await nJ}async function h2($){let f=h1($.distinctId);$.telemetry?.setDistinctId(f);let J=aN($);if(tN(J,$),J==="remote"){let W=$.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:W}),new M2({endpoint:W,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let W=$.hub?.endpoint?.trim(),Z=W||await b1({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:W||void 0}),new g$({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let W=await G8({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(W){$.logger?.log("Using discovered local hub runtime host",{url:W});let Z=new g$({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(Q){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q}),BV($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:Q,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),VV($,f)}return VV($,f)}class aJ{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,W,Z,Q,j,H,X){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=W,this.capabilities=Z,this.logger=Q,this.telemetry=j,this.distinctId=H,this.settings=GY($),this.pendingPrompts=PY($),this.automation=new S9(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=X?new gJ({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:MA(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:yA({host:$,getExtensionContext:()=>J5({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:X.dbPath,logger:X.logger,pollIntervalMs:X.pollIntervalMs,claimLeaseSeconds:X.claimLeaseSeconds,globalMaxConcurrency:X.globalMaxConcurrency,watcherDebounceMs:X.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((A)=>{if(A.type!=="ended")return;this.disposeSessionBootstrap(A.payload.sessionId)})}static async create($={}){let f=R0($.capabilities),J=await h2({...$,capabilities:f}),W=NA($.automation),Z=new aJ(J,$.clientName,J.runtimeAddress,$.prepare,f,$.logger,$.telemetry,$.distinctId,W?{...W,logger:$.logger}:void 0);if(W&&W.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=UY($),J=await this.prepare?.(f);try{let W=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(u9(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>J5({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return FY({input:W,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(W){throw await Promise.resolve(J?.dispose?.()),W}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await _5(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?u9($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>J5({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 UV={};w(UV,{resolvePluginSkillDirectoriesFromPaths:()=>e1,resolvePluginConfigSearchPaths:()=>t8,resolveAndLoadAgentPlugins:()=>j2,resolveAgentPluginPaths:()=>o1,loadAgentPluginsFromPathsWithDiagnostics:()=>s1,loadAgentPluginsFromPaths:()=>K6,loadAgentPluginFromPath:()=>n8,discoverPluginModulePaths:()=>s8});var DV={};w(DV,{toHookConfigFileName:()=>$J,runSubprocessEvent:()=>C2,runHook:()=>b2,resolveHooksConfigSearchPaths:()=>o8,parseHookEventPayload:()=>E2,mergeAgentHooks:()=>Wf,listHookConfigFiles:()=>A1,createSubprocessHooks:()=>h5,createHookConfigFileHooks:()=>fJ,createHookConfigFileExtension:()=>Y2,createHookAuditHooks:()=>A2,createAgentHooksExtension:()=>H2,HookEventPayloadSchema:()=>S5,HookEventNameSchema:()=>w5,HookConfigFileName:()=>X2,HOOK_CONFIG_FILE_EVENT_MAP:()=>e8,HOOKS_CONFIG_DIRECTORY_NAME:()=>L6});import{HookEventNameSchema as w5,HookEventPayloadSchema as S5,parseHookEventPayload as E2,resolveHookSessionContext as ZM}from"@cline/shared";import{z as Pf}from"zod";import{spawn as oN}from"node:child_process";import{augmentNodeCommandForDebug as eN,withResolvedClineBuildEnv as $M}from"@cline/shared";function fM($){let f=$.trim();if(!f)return{};let W=f.split(`
560
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function JM($,f){let J=$ instanceof Error?$:Error(String($)),W=J,Z=f.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function WM($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,Z)=>{let Q=(j)=>{J.off("error",Q);let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){W();return}Z(j)};J.once("error",Q),J.end(f,(j)=>{if(J.off("error",Q),j){let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){W();return}Z(j);return}W()})})}async function C2($,f){let J=eN(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!f.detached,Z=oN(J[0],J.slice(1),{cwd:f.cwd,env:$M(f.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:W})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(G)=>{K(JM(G,J))})});if(await WM(Z,JSON.stringify($)),W){await Promise.race([Q,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let H="",X="",A=!1,Y;Z.stdout.on("data",(B)=>{H+=B.toString()}),Z.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:G,parseError:R}=fM(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:G,parseError:R,timedOut:A})})});return await Promise.race([V,j])}var QM=Pf.object({contextModification:Pf.string().optional(),cancel:Pf.boolean().optional(),review:Pf.boolean().optional(),errorMessage:Pf.string().optional(),context:Pf.string().optional(),overrideInput:Pf.unknown().optional()}).passthrough();var jM=["agent","hook"];async function b2($,f={}){let J=f.command??jM;return await C2($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function RV($){return $ instanceof Error?$:Error(String($))}function HM($){if(!$||typeof $!=="object")return;let f=QM.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 FV($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))if(typeof W==="string")f[J]=W;else f[J]=JSON.stringify(W);return f}function c$($,f,J){let W=J.env??process.env,Z=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:ZM(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function XM($){return{name:$.name,message:$.message,stack:$.stack}}function AM($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function YM($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function VM($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function BM($){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 KM($){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 Uf($,f){try{let J=await b2($,{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?.(RV(J),$)}}function h5($={}){return{hooks:{beforeRun:async(H)=>{let X=YM(H);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let Y={...c$("agent_resume",X,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await Uf(Y,$)}else{let Y={...c$("agent_start",X,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await Uf(Y,$)}return},beforeTool:async(H)=>{let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...c$("tool_call",X,$),hookName:"tool_call",iteration:H.snapshot.iteration,tool_call:{id:H.toolCall.toolCallId,name:H.toolCall.toolName,input:H.input},preToolUse:{toolName:H.toolCall.toolName,parameters:FV(H.input)}};try{let Y=await b2(A,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:A,result:Y,detached:!1}),Y?.timedOut)throw Error("tool_call hook command timed out");if(Y?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${Y.parseError}`);return KM(HM(Y?.parsedJson))}catch(Y){$.onDispatchError?.(RV(Y),A);return}},afterTool:async(H)=>{let X=BM(H),A={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},Y={...c$("tool_result",A,$),hookName:"tool_result",iteration:H.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:FV(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await Uf(Y,$);return},afterRun:async({snapshot:H,result:X})=>{let A={agentId:H.agentId,conversationId:H.conversationId??H.runId??H.agentId,parentAgentId:H.parentAgentId??null};if(X.status==="completed"){let B={...c$("agent_end",A,$),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await Uf(B,$);return}let Y=X.status==="aborted"||AM(X.error?.message)?"agent_abort":"agent_error",V=Y==="agent_error"?{...c$(Y,A,$),hookName:Y,iteration:X.iterations,error:XM(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...c$(Y,A,$),hookName:Y,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await Uf(V,$)},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...c$("prompt_submit",X,$),hookName:"prompt_submit",userPromptSubmit:{prompt:VM(H.message.content),attachments:[]}};await Uf(A,$)}},shutdown:async({agentId:H,conversationId:X,parentAgentId:A,reason:Y})=>{let V={...c$("session_shutdown",{agentId:H,conversationId:X,parentAgentId:A},$),hookName:"session_shutdown",reason:Y};await Uf(V,$)}}}LQ();var OV={};w(OV,{registerRemoteConfigSessionBlobUpload:()=>b5,readRemoteConfigSessionBlobUploadMetadata:()=>OQ,prepareRemoteConfigCoreIntegration:()=>_Q,createRemoteConfigSessionMessagesArtifactUploader:()=>zQ,buildRemoteConfigSessionBlobUploadMetadata:()=>C5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>E5});import{buildRemoteConfigSessionBlobUploadMetadata as C5,clearRemoteConfigSessionBlobUpload as GM,createClineTelemetryServiceConfig as PM,createSessionId as UM,createRemoteConfigSessionMessagesArtifactUploader as FM,prepareRemoteConfigRuntime as RM,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as E5,readRemoteConfigSessionBlobUploadMetadata as OQ,registerRemoteConfigSessionBlobUpload as b5}from"@cline/shared";function DM($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return M$(PM(J)).telemetry}function zQ(){let $=FM();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function _Q($){let f=await RM($),J=DM(f,$),W=[f.pluginDefinition],Z=f.claims?.subject,Q=C5(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:W,telemetry:J,applyToStartSessionInput(H){let X=H.config.extensions??[],A=H.config.telemetry,Y=Q?H.config.sessionId?.trim()||UM():H.config.sessionId;if(Y&&Q)j=Y;let V=Y&&Q?b5(Y,f.bundle?.remoteConfig,Z):void 0,B=V?{...H.sessionMetadata??{},[E5]:V}:H.sessionMetadata;return{...H,...B?{sessionMetadata:B}:{},config:{...H.config,...Y?{sessionId:Y}:{},extensions:[...X,...W],telemetry:J??A}}},async dispose(){if(j)GM(j)}}}var wV={};w(wV,{createTeamName:()=>I5,DefaultRuntimeBuilder:()=>x2});import{hasRuntimeConfigExtension as EM}from"@cline/shared";import{nanoid as bM}from"nanoid";Z$();var yV={};w(yV,{createLocalTeamStore:()=>yQ,SqliteTeamStore:()=>Ff,FileTeamStore:()=>tJ});import{appendFileSync as LM,existsSync as k2,mkdirSync as zV,readdirSync as OM,readFileSync as _V,renameSync as zM,writeFileSync as _M}from"node:fs";import{join as TQ}from"node:path";import{resolveTeamDataDir as TM}from"@cline/shared/storage";function TV(){return new Date().toISOString()}function NQ($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function NV($){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 tJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??TM()}init(){this.ensureTeamDir()}listTeamNames(){if(!k2(this.teamDirPath))return[];return OM(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>k2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?NV(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!k2(J))return[];return _V(J,"utf8").split(`
561
- `).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,f)}loadRuntime($){let f=this.readEnvelope($);return{state:f?.teamState?NV(f.teamState):void 0,teammates:f?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,f){this.ensureTeamSubdir($),LM(this.historyPath($),`${JSON.stringify({ts:TV(),eventType:f.type,payload:f})}
562
- `,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let W={version:1,updatedAt:TV(),teamState:f,teammates:J},Z=this.statePath($),Q=`${Z}.tmp`;_M(Q,`${JSON.stringify(W,null,2)}
563
- `,"utf8"),zM(Q,Z)}markInProgressRunsInterrupted($,f){let J=this.readEnvelope($);if(!J?.teamState?.runs?.length)return[];let W=J.teamState.runs.filter((Q)=>Q.status==="queued"||Q.status==="running").map((Q)=>Q.id);if(W.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((Q)=>Q.status==="queued"||Q.status==="running"?{...Q,status:"interrupted",error:f,endedAt:Z}:Q)},this.persistRuntime($,J.teamState,J.teammates),W}ensureTeamDir(){if(!k2(this.teamDirPath))zV(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let f=TQ(this.ensureTeamDir(),NQ($));if(!k2(f))zV(f,{recursive:!0});return f}statePath($){return TQ(this.ensureTeamDir(),NQ($),"state.json")}historyPath($){return TQ(this.ensureTeamDir(),NQ($),"task-history.jsonl")}readEnvelope($){let f=this.statePath($);if(!k2(f))return;try{let J=JSON.parse(_V(f,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as NM,mkdirSync as MM}from"node:fs";import{join as yM}from"node:path";import{safeJsonParse as MV}from"@cline/shared";import{loadSqliteDb as qM,nowIso as MQ}from"@cline/shared/db";import{resolveDbDataDir as wM}from"@cline/shared/storage";function SM(){return wM()}function I2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function hM($){let f=MV($);if(!Array.isArray(f))return[];let J=[];for(let W of f){if(!W||typeof W!=="object")continue;let Z=W,Q=Z.agentId,j=Z.rolePrompt;if(typeof Q!=="string"||!Q.trim())continue;if(typeof j!=="string"||!j.trim())continue;let H={agentId:Q.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())H.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))H.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(H)}return J}function CM($){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 Ff{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??SM()}init(){this.getRawDb()}ensureTeamDir(){if(!NM(this.teamDirPath))MM(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return yM(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=qM(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
559
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,null,null,"running",0,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,null,null,null,null,0,f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"","",f.messagesPath,s()])}}function pN(f){if(f.backendMode)return f.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let $=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if($==="local"||$==="hub"||$==="remote")return $;return"auto"}var Q4,Z4;function rN(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;f6($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function iN(f){await f.reconcileDeadSessions?.().catch(()=>{})}function xV(f){try{let $=new Ff;return $.init(),new Rf($,{messagesArtifactUploader:f.messagesArtifactUploader,logger:f.logger})}catch($){return f.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),IV(f.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:$,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new hW(void 0,{messagesArtifactUploader:f.messagesArtifactUploader,logger:f.logger})}}function kV(f,$,J){return new Df({sessionService:J??f.sessionService??xV(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function xW(f){if(Q4)return Q4;if(Z4)return await Z4;return Z4=(async()=>{return Q4=xV(f),await iN(Q4),Q4})().finally(()=>{Z4=void 0}),await Z4}async function g2(f){let $=g$(f.distinctId);f.telemetry?.setDistinctId($);let J=pN(f);if(rN(J,f),J==="remote"){let Q=f.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return f.logger?.log("Using remote runtime host",{endpoint:Q}),new S2({endpoint:Q,authToken:f.remote?.authToken,clientType:f.remote?.clientType,displayName:f.remote?.displayName,workspaceRoot:f.remote?.workspaceRoot,cwd:f.remote?.cwd,capabilities:f.capabilities})}if(J==="hub"){let Q=f.hub?.endpoint?.trim(),Z=Q||await c$({strategy:f.hub?.strategy??"require-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return f.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:Q||void 0}),new lf({url:Z,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities,telemetry:f.telemetry},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd})}if(J==="auto"){let Q=await L8({endpoint:f.hub?.endpoint,strategy:f.hub?.strategy??"prefer-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(Q){f.logger?.log("Using discovered local hub runtime host",{url:Q});let Z=new lf({url:Q,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities,telemetry:f.telemetry},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});try{return await Z.connect(),Z}catch(W){f.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:W}),IV(f.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:W,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return f.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),kV(f,$)}return kV(f,$)}class W4{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor(f,$,J,Q,Z,W,j,H,X){this.clientName=$,this.runtimeAddress=J,this.host=f,this.prepare=Q,this.capabilities=Z,this.logger=W,this.telemetry=j,this.distinctId=H,this.settings=hY(f),this.pendingPrompts=bY(f),this.automation=new rZ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=X?new rJ({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:pA(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:rA({host:f,getExtensionContext:()=>R5({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:X.dbPath,logger:X.logger,pollIntervalMs:X.pollIntervalMs,claimLeaseSeconds:X.claimLeaseSeconds,globalMaxConcurrency:X.globalMaxConcurrency,watcherDebounceMs:X.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((A)=>{if(A.type!=="ended")return;this.disposeSessionBootstrap(A.payload.sessionId)})}static async create(f={}){let $=L0(f.capabilities),J=await g2({...f,capabilities:$}),Q=lA(f.automation),Z=new W4(J,f.clientName,J.runtimeAddress,f.prepare,$,f.logger,f.telemetry,f.distinctId,Q?{...Q,logger:f.logger}:void 0);if(Q&&Q.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap(f){let $=this.activeSessionBootstraps.get(f);if(!$)return;this.activeSessionBootstraps.delete(f),await Promise.resolve($.dispose?.())}async start(f){let $=kY(f),J=await this.prepare?.($);try{let Q=J?await J.applyToStartSessionInput($):$,Z=await this.host.startSession(ZW(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(W)=>R5({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 IY({input:Q,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(Q){throw await Promise.resolve(J?.dispose?.()),Q}}send=(...f)=>this.host.runTurn(...f);getAccumulatedUsage=(...f)=>{return this.host.getAccumulatedUsage?.(...f)??Promise.resolve(void 0)};abort=(...f)=>this.host.abort(...f);stop=async(f)=>{await this.host.stopSession(f),await this.disposeSessionBootstrap(f)};dispose=async(...f)=>{try{await this.automationService?.dispose(),await this.host.dispose(...f)}finally{this.unsubscribeBootstrapCleanup();let $=[...this.activeSessionBootstraps.keys()];await Promise.allSettled($.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...f)=>this.host.getSession(...f);listHistory=async(f={})=>await m5(this.host,f);list=async(f=200,$={})=>await this.listHistory({...$,limit:f});delete=async(f)=>{let $=await this.host.deleteSession(f);if($)await this.disposeSessionBootstrap(f);return $};update=(...f)=>this.host.updateSession(...f);readMessages=(...f)=>this.host.readSessionMessages(...f);async restore(f){let $=f.start?ZW(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>R5({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:f.sessionId,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restore:f.restore,start:$})}ingestHookEvent=(...f)=>this.host.dispatchHookEvent(...f);subscribe(f,$){return this.host.subscribe(f,$)}updateSessionModel=(...f)=>{return this.host.updateSessionModel?.(...f)??Promise.resolve()}}var vV={};q(vV,{resolvePluginSkillDirectoriesFromPaths:()=>H1,resolvePluginConfigSearchPaths:()=>VJ,resolveAndLoadAgentPlugins:()=>P2,resolveAgentPluginPaths:()=>j1,loadAgentPluginsFromPathsWithDiagnostics:()=>W1,loadAgentPluginsFromPaths:()=>k6,loadAgentPluginFromPath:()=>AJ,discoverPluginModulePaths:()=>BJ});var dV={};q(dV,{toHookConfigFileName:()=>GJ,runSubprocessEvent:()=>m2,runHook:()=>c2,resolveHooksConfigSearchPaths:()=>KJ,parseHookEventPayload:()=>v2,mergeAgentHooks:()=>V1,listHookConfigFiles:()=>D$,createSubprocessHooks:()=>n5,createHookConfigFileHooks:()=>FJ,createHookConfigFileExtension:()=>R2,createHookAuditHooks:()=>U2,createAgentHooksExtension:()=>G2,HookEventPayloadSchema:()=>i5,HookEventNameSchema:()=>r5,HookConfigFileName:()=>F2,HOOK_CONFIG_FILE_EVENT_MAP:()=>PJ,HOOKS_CONFIG_DIRECTORY_NAME:()=>u6});import{HookEventNameSchema as r5,HookEventPayloadSchema as i5,parseHookEventPayload as v2,resolveHookSessionContext as fq}from"@cline/shared";import{z as T1}from"zod";import{spawn as nN}from"node:child_process";import{augmentNodeCommandForDebug as aN,withResolvedClineBuildEnv as tN}from"@cline/shared";function sN(f){let $=f.trim();if(!$)return{};let Q=$.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]:$;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function oN(f,$){let J=f instanceof Error?f:Error(String(f)),Q=J,Z=$.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function eN(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end($,(j)=>{if(J.off("error",W),j){let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function m2(f,$){let J=aN($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!$.detached,Z=nN(J[0],J.slice(1),{cwd:$.cwd,env:tN($.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q}),W=new Promise((B)=>{Z.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(P)=>{K(oN(P,J))})});if(await eN(Z,JSON.stringify(f)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let H="",X="",A=!1,Y;Z.stdout.on("data",(B)=>{H+=B.toString()}),Z.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if(($.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,Z.kill("SIGKILL")},$.timeoutMs);Z.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:P,parseError:R}=sN(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:P,parseError:R,timedOut:A})})});return await Promise.race([V,j])}var $q=T1.object({contextModification:T1.string().optional(),cancel:T1.boolean().optional(),review:T1.boolean().optional(),errorMessage:T1.string().optional(),context:T1.string().optional(),overrideInput:T1.unknown().optional()}).passthrough();var Jq=["agent","hook"];async function c2(f,$={}){let J=$.command??Jq;return await m2(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function uV(f){return f instanceof Error?f:Error(String(f))}function Qq(f){if(!f||typeof f!=="object")return;let $=$q.safeParse(f);if(!$.success)return;let J=$.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function cV(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,Q]of Object.entries(f))if(typeof Q==="string")$[J]=Q;else $[J]=JSON.stringify(Q);return $}function nf(f,$,J){let Q=J.env??process.env,Z=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",W=J.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:fq(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function Zq(f){return{name:f.name,message:f.message,stack:f.stack}}function Wq(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function jq(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function Hq(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function Xq(f){return{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}function Aq(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}async function z1(f,$){try{let J=await c2(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(uV(J),f)}}function n5(f={}){return{hooks:{beforeRun:async(H)=>{let X=jq(H);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let Y={...nf("agent_resume",X,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await z1(Y,f)}else{let Y={...nf("agent_start",X,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await z1(Y,f)}return},beforeTool:async(H)=>{let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...nf("tool_call",X,f),hookName:"tool_call",iteration:H.snapshot.iteration,tool_call:{id:H.toolCall.toolCallId,name:H.toolCall.toolName,input:H.input},preToolUse:{toolName:H.toolCall.toolName,parameters:cV(H.input)}};try{let Y=await c2(A,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:A,result:Y,detached:!1}),Y?.timedOut)throw Error("tool_call hook command timed out");if(Y?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${Y.parseError}`);return Aq(Qq(Y?.parsedJson))}catch(Y){f.onDispatchError?.(uV(Y),A);return}},afterTool:async(H)=>{let X=Xq(H),A={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},Y={...nf("tool_result",A,f),hookName:"tool_result",iteration:H.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:cV(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await z1(Y,f);return},afterRun:async({snapshot:H,result:X})=>{let A={agentId:H.agentId,conversationId:H.conversationId??H.runId??H.agentId,parentAgentId:H.parentAgentId??null};if(X.status==="completed"){let B={...nf("agent_end",A,f),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await z1(B,f);return}let Y=X.status==="aborted"||Wq(X.error?.message)?"agent_abort":"agent_error",V=Y==="agent_error"?{...nf(Y,A,f),hookName:Y,iteration:X.iterations,error:Zq(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...nf(Y,A,f),hookName:Y,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await z1(V,f)},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...nf("prompt_submit",X,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Hq(H.message.content),attachments:[]}};await z1(A,f)}},shutdown:async({agentId:H,conversationId:X,parentAgentId:A,reason:Y})=>{let V={...nf("session_shutdown",{agentId:H,conversationId:X,parentAgentId:A},f),hookName:"session_shutdown",reason:Y};await z1(V,f)}}}gW();var pV={};q(pV,{registerRemoteConfigSessionBlobUpload:()=>s5,readRemoteConfigSessionBlobUploadMetadata:()=>mW,prepareRemoteConfigCoreIntegration:()=>cW,createRemoteConfigSessionMessagesArtifactUploader:()=>vW,buildRemoteConfigSessionBlobUploadMetadata:()=>a5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>t5});import{buildRemoteConfigSessionBlobUploadMetadata as a5,clearRemoteConfigSessionBlobUpload as Yq,createClineTelemetryServiceConfig as Vq,createSessionId as Bq,createRemoteConfigSessionMessagesArtifactUploader as Kq,prepareRemoteConfigRuntime as Pq,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as t5,readRemoteConfigSessionBlobUploadMetadata as mW,registerRemoteConfigSessionBlobUpload as s5}from"@cline/shared";function Gq(f,$){let J=f.telemetry||$.telemetryService?{...$.telemetryService??{},...f.telemetry??{}}:void 0;if(!J)return;return Sf(Vq(J)).telemetry}function vW(){let f=Kq();return{async uploadMessagesFile($){await f.uploadMessagesFile($)}}}async function cW(f){let $=await Pq(f),J=Gq($,f),Q=[$.pluginDefinition],Z=$.claims?.subject,W=a5($.bundle?.remoteConfig,Z),j;return{prepared:$,extensions:Q,telemetry:J,applyToStartSessionInput(H){let X=H.config.extensions??[],A=H.config.telemetry,Y=W?H.config.sessionId?.trim()||Bq():H.config.sessionId;if(Y&&W)j=Y;let V=Y&&W?s5(Y,$.bundle?.remoteConfig,Z):void 0,B=V?{...H.sessionMetadata??{},[t5]:V}:H.sessionMetadata;return{...H,...B?{sessionMetadata:B}:{},config:{...H.config,...Y?{sessionId:Y}:{},extensions:[...X,...Q],telemetry:J??A}}},async dispose(){if(j)Yq(j)}}}var oV={};q(oV,{createTeamName:()=>f9,DefaultRuntimeBuilder:()=>l2});import{hasRuntimeConfigExtension as wq}from"@cline/shared";import{nanoid as Cq}from"nanoid";jf();var sV={};q(sV,{createLocalTeamStore:()=>pW,SqliteTeamStore:()=>M1,FileTeamStore:()=>j4});import{appendFileSync as Fq,existsSync as u2,mkdirSync as rV,readdirSync as Uq,readFileSync as iV,renameSync as Rq,writeFileSync as Dq}from"node:fs";import{join as uW}from"node:path";import{resolveTeamDataDir as Lq}from"@cline/shared/storage";function nV(){return new Date().toISOString()}function dW(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function aV(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class j4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??Lq()}init(){this.ensureTeamDir()}listTeamNames(){if(!u2(this.teamDirPath))return[];return Uq(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>u2(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?aV($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!u2(J))return[];return iV(J,"utf8").split(`
561
+ `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,$)}loadRuntime(f){let $=this.readEnvelope(f);return{state:$?.teamState?aV($.teamState):void 0,teammates:$?.teammates??[],interruptedRunIds:[]}}handleTeamEvent(f,$){this.ensureTeamSubdir(f),Fq(this.historyPath(f),`${JSON.stringify({ts:nV(),eventType:$.type,payload:$})}
562
+ `,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let Q={version:1,updatedAt:nV(),teamState:$,teammates:J},Z=this.statePath(f),W=`${Z}.tmp`;Dq(W,`${JSON.stringify(Q,null,2)}
563
+ `,"utf8"),Rq(W,Z)}markInProgressRunsInterrupted(f,$){let J=this.readEnvelope(f);if(!J?.teamState?.runs?.length)return[];let Q=J.teamState.runs.filter((W)=>W.status==="queued"||W.status==="running").map((W)=>W.id);if(Q.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((W)=>W.status==="queued"||W.status==="running"?{...W,status:"interrupted",error:$,endedAt:Z}:W)},this.persistRuntime(f,J.teamState,J.teammates),Q}ensureTeamDir(){if(!u2(this.teamDirPath))rV(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(f){let $=uW(this.ensureTeamDir(),dW(f));if(!u2($))rV($,{recursive:!0});return $}statePath(f){return uW(this.ensureTeamDir(),dW(f),"state.json")}historyPath(f){return uW(this.ensureTeamDir(),dW(f),"task-history.jsonl")}readEnvelope(f){let $=this.statePath(f);if(!u2($))return;try{let J=JSON.parse(iV($,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as Oq,mkdirSync as _q}from"node:fs";import{join as Tq}from"node:path";import{safeJsonParse as tV}from"@cline/shared";import{loadSqliteDb as zq,nowIso as lW}from"@cline/shared/db";import{resolveDbDataDir as Mq}from"@cline/shared/storage";function Nq(){return Mq()}function d2(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function qq(f){let $=tV(f);if(!Array.isArray($))return[];let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q,W=Z.agentId,j=Z.rolePrompt;if(typeof W!=="string"||!W.trim())continue;if(typeof j!=="string"||!j.trim())continue;let H={agentId:W.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())H.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))H.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(H)}return J}function yq(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class M1{teamDirPath;db;constructor(f={}){this.teamDirPath=f.teamDir??Nq()}init(){this.getRawDb()}ensureTeamDir(){if(!Oq(this.teamDirPath))_q(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Tq(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let f=zq(this.dbPath());return this.ensureSchema(f),this.db=f,f}ensureSchema(f){if(f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec(`
564
564
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
565
565
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
566
566
  version INTEGER NOT NULL
567
567
  );
568
- `),!$.prepare("SELECT version FROM team_store_schema_version WHERE lock = 1").get())$.prepare("INSERT INTO team_store_schema_version (lock, version) VALUES (1, 1)").run();$.exec(`
568
+ `),!f.prepare("SELECT version FROM team_store_schema_version WHERE lock = 1").get())f.prepare("INSERT INTO team_store_schema_version (lock, version) VALUES (1, 1)").run();f.exec(`
569
569
  CREATE TABLE IF NOT EXISTS team_events (
570
570
  id INTEGER PRIMARY KEY AUTOINCREMENT,
571
571
  team_name TEXT NOT NULL,
@@ -575,17 +575,17 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
575
575
  causation_id TEXT,
576
576
  correlation_id TEXT
577
577
  );
578
- `),$.exec(`
578
+ `),f.exec(`
579
579
  CREATE INDEX IF NOT EXISTS idx_team_events_name_ts
580
580
  ON team_events(team_name, ts DESC);
581
- `),$.exec(`
581
+ `),f.exec(`
582
582
  CREATE TABLE IF NOT EXISTS team_runtime_snapshot (
583
583
  team_name TEXT PRIMARY KEY,
584
584
  state_json TEXT NOT NULL,
585
585
  teammates_json TEXT NOT NULL,
586
586
  updated_at TEXT NOT NULL
587
587
  );
588
- `),$.exec(`
588
+ `),f.exec(`
589
589
  CREATE TABLE IF NOT EXISTS team_tasks (
590
590
  team_name TEXT NOT NULL,
591
591
  task_id TEXT NOT NULL,
@@ -599,7 +599,7 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
599
599
  updated_at TEXT NOT NULL,
600
600
  PRIMARY KEY(team_name, task_id)
601
601
  );
602
- `),$.exec(`
602
+ `),f.exec(`
603
603
  CREATE TABLE IF NOT EXISTS team_runs (
604
604
  team_name TEXT NOT NULL,
605
605
  run_id TEXT NOT NULL,
@@ -615,10 +615,10 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
615
615
  version INTEGER NOT NULL DEFAULT 1,
616
616
  PRIMARY KEY(team_name, run_id)
617
617
  );
618
- `),$.exec(`
618
+ `),f.exec(`
619
619
  CREATE INDEX IF NOT EXISTS idx_team_runs_status
620
620
  ON team_runs(team_name, status);
621
- `),$.exec(`
621
+ `),f.exec(`
622
622
  CREATE TABLE IF NOT EXISTS team_outcomes (
623
623
  team_name TEXT NOT NULL,
624
624
  outcome_id TEXT NOT NULL,
@@ -629,7 +629,7 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
629
629
  version INTEGER NOT NULL DEFAULT 1,
630
630
  PRIMARY KEY(team_name, outcome_id)
631
631
  );
632
- `),$.exec(`
632
+ `),f.exec(`
633
633
  CREATE TABLE IF NOT EXISTS team_outcome_fragments (
634
634
  team_name TEXT NOT NULL,
635
635
  outcome_id TEXT NOT NULL,
@@ -644,13 +644,13 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
644
644
  version INTEGER NOT NULL DEFAULT 1,
645
645
  PRIMARY KEY(team_name, fragment_id)
646
646
  );
647
- `)}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}withTransaction($){let f=this.getRawDb();f.exec("BEGIN IMMEDIATE;");try{$(),f.exec("COMMIT;")}catch(J){try{f.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let f=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[I2($)]);if(!f)return;let J=MV(f.state_json);if(!J)return;try{return CM(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),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f]),Z=W?hM(W.teammates_json):[];return{state:J,teammates:Z,interruptedRunIds:[]}}appendTeamEvent($,f,J,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
648
- VALUES (?, ?, ?, ?, NULL, ?)`,[I2($),MQ(),f,JSON.stringify(J),W??null])}persistRuntime($,f,J){let W=I2($),Z=MQ();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
647
+ `)}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}withTransaction(f){let $=this.getRawDb();$.exec("BEGIN IMMEDIATE;");try{f(),$.exec("COMMIT;")}catch(J){try{$.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((f)=>f.team_name)}readState(f){let $=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[d2(f)]);if(!$)return;let J=tV($.state_json);if(!J)return;try{return yq(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 ?",[d2(f),$]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime(f){let $=d2(f),J=this.readState($),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[$]),Z=Q?qq(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, ?)`,[d2(f),lW(),$,JSON.stringify(J),Q??null])}persistRuntime(f,$,J){let Q=d2(f),Z=lW();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
649
649
  VALUES (?, ?, ?, ?)
650
650
  ON CONFLICT(team_name) DO UPDATE SET
651
651
  state_json = excluded.state_json,
652
652
  teammates_json = excluded.teammates_json,
653
- updated_at = excluded.updated_at`,[W,JSON.stringify(f),JSON.stringify(J),Z]);for(let Q of f.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
653
+ updated_at = excluded.updated_at`,[Q,JSON.stringify($),JSON.stringify(J),Z]);for(let W of $.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
654
654
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
655
655
  ON CONFLICT(team_name, task_id) DO UPDATE SET
656
656
  title = excluded.title,
@@ -660,7 +660,7 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
660
660
  depends_on_json = excluded.depends_on_json,
661
661
  summary = excluded.summary,
662
662
  version = team_tasks.version + 1,
663
- updated_at = excluded.updated_at`,[W,Q.id,Q.title,Q.description,Q.status,Q.assignee??null,JSON.stringify(Q.dependsOn??[]),Q.summary??null,Q.updatedAt.toISOString()]);for(let Q of f.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
663
+ updated_at = excluded.updated_at`,[Q,W.id,W.title,W.description,W.status,W.assignee??null,JSON.stringify(W.dependsOn??[]),W.summary??null,W.updatedAt.toISOString()]);for(let W of $.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
664
664
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
665
665
  ON CONFLICT(team_name, run_id) DO UPDATE SET
666
666
  agent_id = excluded.agent_id,
@@ -672,14 +672,14 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
672
672
  error = excluded.error,
673
673
  lease_owner = excluded.lease_owner,
674
674
  heartbeat_at = excluded.heartbeat_at,
675
- version = team_runs.version + 1`,[W,Q.id,Q.agentId,Q.taskId??null,Q.status,Q.message,Q.startedAt?Q.startedAt.toISOString():null,Q.endedAt?Q.endedAt.toISOString():null,Q.error??null,Q.leaseOwner??null,Q.heartbeatAt?Q.heartbeatAt.toISOString():null]);for(let Q of f.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
675
+ version = team_runs.version + 1`,[Q,W.id,W.agentId,W.taskId??null,W.status,W.message,W.startedAt?W.startedAt.toISOString():null,W.endedAt?W.endedAt.toISOString():null,W.error??null,W.leaseOwner??null,W.heartbeatAt?W.heartbeatAt.toISOString():null]);for(let W of $.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
676
676
  VALUES (?, ?, ?, ?, ?, ?, 1)
677
677
  ON CONFLICT(team_name, outcome_id) DO UPDATE SET
678
678
  title = excluded.title,
679
679
  status = excluded.status,
680
680
  schema_json = excluded.schema_json,
681
681
  finalized_at = excluded.finalized_at,
682
- version = team_outcomes.version + 1`,[W,Q.id,Q.title,Q.status,JSON.stringify({requiredSections:Q.requiredSections}),Q.finalizedAt?Q.finalizedAt.toISOString():null]);for(let Q of f.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
682
+ version = team_outcomes.version + 1`,[Q,W.id,W.title,W.status,JSON.stringify({requiredSections:W.requiredSections}),W.finalizedAt?W.finalizedAt.toISOString():null]);for(let W of $.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
683
683
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
684
684
  ON CONFLICT(team_name, fragment_id) DO UPDATE SET
685
685
  outcome_id = excluded.outcome_id,
@@ -690,30 +690,30 @@ ${Z}`,$.config.mode)}function rJ($,f){return gN($,f==="plan"?"plan":f==="yolo"?"
690
690
  status = excluded.status,
691
691
  reviewed_by = excluded.reviewed_by,
692
692
  reviewed_at = excluded.reviewed_at,
693
- version = team_outcome_fragments.version + 1`,[W,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=I2($),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(W.length===0)return[];let Z=MQ();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
694
- WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),W.map((Q)=>Q.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function yQ($={}){try{let f=new Ff($);return f.init(),f}catch{let f=new tJ({teamDir:$.teamDir});return f.init(),f}}function k5($,f){return EM($,f)}function kM($,f){let J=f?.["*"]??{},W=f?.[$]??{};return{...J,...W}.enabled!==!1}function IM($,f){return $.filter((J)=>kM(J.name,f))}function qV($,f){return S1(IM($,f))}function I5(){return`team-${bM(5)}`}function qQ($,f,J,W,Z,Q,j,H){let X=m0[b$({mode:J})],A=cf(f,W,J,Z??uf);return qV(p1({cwd:$,...X,enableSkills:!!j,...A,executors:{...j?{skills:j}:{},...H??{}}}),Q)}function xM($){return qQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,mM,$.toolExecutors).some((f)=>f.name==="skills")}var mM=async()=>"";async function gM($){let f=T0();if(!m$({filePath:f}))return{tools:[]};let J=new Vf({clientFactory:z2({settingsPath:f})}),W;try{W=await Yf(J,{filePath:f})}catch(H){await J.dispose().catch(()=>{});let X=H instanceof Error?H.message:String(H);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${X}`),{tools:[]}}let Z=W.filter((H)=>H.disabled!==!0),Q=await Promise.allSettled(Z.map((H)=>_2({serverName:H.name,provider:J}))),j=[];for(let[H,X]of Q.entries())if(X.status==="fulfilled")j.push(...X.value);else{let A=X.reason instanceof Error?X.reason.message:String(X.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[H].name}", skipping: ${A}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function vM($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function uM($){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 cM($){let f=m0[b$({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 x2{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:W,logger:Z,telemetry:Q,createSpawnTool:j,onTeamRestored:H,userInstructionService:X,configExtensions:A,toolExecutors:Y}=$,V=$.onTeamEvent??(()=>{}),B=cM(f),K=W$(),G=[],R=f.teamName?.trim()||I5(),P=f.sessionId?.trim()||R,U=k5(A,"rules"),F=k5(A,"skills"),z=k5(A,"workflows"),_=k5(A,"plugins"),D=U||F||z,O=!1,N=Boolean(X),q=X,$0;if(!q&&D)q=U1({skills:F?{workspacePath:f.cwd,includePluginSkills:_,pluginSkillDirectories:_?$.pluginSkillDirectories:void 0,pluginPaths:f.pluginPaths,cwd:f.cwd}:{workspacePath:f.cwd},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(q)await q.start().catch(()=>{});let A0=B.enableTools&&F&&Boolean(q)&&q?.hasConfiguredSkills(f.skills)===!0&&xM({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:f.toolPolicies,toolExecutors:Y}),o=q&&D?q.createExtension({includeRules:U,includeSkills:F,includeWorkflows:z,registerSkillsTool:A0,allowedSkillNames:f.skills}):void 0,Y0=o?[...W??f.extensions??[],o]:W??f.extensions;if(B.enableTools){if(G.push(...qQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,Y)),!B.disableMcpSettingsTools){let r=await gM(f.logger);G.push(...r.tools),$0=r.shutdown}}let i,J$=B.enableAgentTeams?yQ():void 0,p=J$?.loadRuntime(P),n0=p?.state,k=p?.teammates??[],D0=new Map(k.map((r)=>[r.agentId,r])),n=f.sessionId||R,a0,T1=[],N1=!1,zf=lf({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:Y0,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(!this.teamRuntimeEntries.has(n))this.teamRuntimeEntries.set(n,{delegatedAgentConfigProvider:zf});let d2=()=>{if(!B.enableAgentTeams)return;let r=this.teamRuntimeEntries.get(n)??{delegatedAgentConfigProvider:zf};if(this.teamRuntimeEntries.set(n,r),i=r.runtime,!i){if(i=new Gf({teamName:R,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(f0)=>{if(V(f0),i&&J$){if(f0.type==="teammate_spawned"&&f0.teammate?.rolePrompt){let D$={agentId:f0.agentId,rolePrompt:f0.teammate.rolePrompt,modelId:f0.teammate.modelId,maxIterations:f0.teammate.maxIterations};D0.set(D$.agentId,D$)}if(f0.type==="teammate_shutdown"&&!uM(f0.reason))D0.delete(f0.agentId);J$.handleTeamEvent(P,f0),J$.persistRuntime(P,i.exportState(),Array.from(D0.values()))}}}),n0)i.hydrateState(n0),N1=!0;r.runtime=i}if(!O){if(!i)return;O=!0;let f0=nf({runtime:i,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(n0),restoredTeammates:k,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(D$)=>{T1=D$,a0?.addTools(D$)},createBaseTools:B.enableTools?()=>qQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,Y):void 0,teammateConfigProvider:zf});if(N1)i.recoverActiveRuns("runtime_recovered");if(f0.restoredFromPersistence)H?.();G.push(...f0.tools)}return i};if(B.enableSpawnAgent&&j){let r=j();G.push({...r,execute:async(f0,D$)=>{return d2(),r.execute(f0,D$)}})}if(B.enableAgentTeams)d2();let X4=qV(G,f.toolPolicies),YW=X4.some((r)=>r.name===J0.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),_f=B.enableAgentTeams?()=>{let r=this.teamRuntimeEntries.get(n)?.runtime;if(!r)return;let f0=r.listTasks(),D$=f0.some((l$)=>l$.status==="in_progress"||l$.status==="pending"),m7=r.listRuns({}),NK=m7.some((l$)=>l$.status==="running"||l$.status==="queued");if(D$||NK){let l$=f0.filter((C0)=>C0.status==="in_progress"||C0.status==="pending").map((C0)=>`${C0.id} (${C0.status}): ${C0.title}`).join(", "),g7=m7.filter((C0)=>C0.status==="running"||C0.status==="queued").map((C0)=>`${C0.id} (${C0.status})`).join(", "),VW=[];if(l$)VW.push(`Unfinished tasks: ${l$}`);if(g7)VW.push(`Active runs: ${g7}`);return`[SYSTEM] You still have team obligations. ${VW.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,l2=YW?{requireCompletionTool:!0,..._f?{completionGuard:_f}:{}}:_f?{completionGuard:_f}:void 0;return{tools:X4,logger:Z??f.logger,telemetry:Q??f.telemetry,teamRuntime:i,teamRestoredFromPersistence:Boolean(n0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(n)?.delegatedAgentConfigProvider??zf,extensions:Y0,completionPolicy:l2,registerLeadAgent:(r)=>{if(a0=r,T1.length>0)r.addTools(S1(T1,[...K]))},shutdown:async(r)=>{if(vM(i,r),this.teamRuntimeEntries.delete(n),await $0?.(),!N)q?.stop()}}}}var hV={};w(hV,{requestDesktopToolApproval:()=>SQ});import{mkdir as dM,readFile as lM,unlink as pM,writeFile as rM}from"node:fs/promises";import{join as SV}from"node:path";function iM($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function nM($){return new Promise((f)=>setTimeout(f,$))}async function wQ($){try{await pM($)}catch{}}async function SQ($,f={}){let J=f.approvalDir?.trim(),W=f.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await dM(J,{recursive:!0});let Z=iM(`${$.toolCallId}`),Q=SV(J,`${W}.request.${Z}.json`),j=SV(J,`${W}.decision.${Z}.json`),H=f.nowIso??(()=>new Date().toISOString());await rM(Q,`${JSON.stringify({requestId:Z,sessionId:W,createdAt:H(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
695
- `,"utf8");let X=f.timeoutMs??300000,A=f.pollIntervalMs??200,Y=Date.now();while(Date.now()-Y<X){try{let V=await lM(j,"utf8"),B=JSON.parse(V),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([wQ(j),wQ(Q)]),K}catch{}await nM(A)}return await wQ(Q),{approved:!1,reason:"Tool approval request timed out"}}Z$();Z$();var kV={};w(kV,{uninstallPlugin:()=>mQ});import{existsSync as g2,readdirSync as aM,readFileSync as tM,rmdirSync as sM,rmSync as oM,statSync as eM}from"node:fs";import{basename as l0,dirname as O1,extname as $y,isAbsolute as fy,join as d$,relative as Jy,resolve as m2,sep as hQ}from"node:path";import{discoverPluginModulePaths as Wy,resolvePluginConfigSearchPaths as Zy}from"@cline/shared/storage";var IQ="_installed",Qy="package",jy=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function CQ($){return $.trim().toLowerCase()}function f$($,f){let J=f?.trim();if(!J)return;$.add(J)}function Hy($){return $.replace(/-[0-9a-f]{12}$/i,"")}function EQ($){let f=$y($);return f?$.slice(0,-f.length):$}function bQ($){if(!g2($))return;try{let f=JSON.parse(tM($,"utf8"));return typeof f.name==="string"?f.name.trim():void 0}catch{return}}function xQ($,f){let J=Jy(f,$);return J===""||!J.startsWith("..")&&!fy(J)}function CV($){let J=m2($).split(hQ),W=J.lastIndexOf(IQ);if(W<0)return;let Z=J[W+1];if(!Z)return;let Q=jy.get(Z)??1,j=W+2+Q;if(J.length<j)return;let H=J.slice(0,j).join(hQ)||hQ;return g2(H)?H:void 0}function x5($){try{return aM($,{withFileTypes:!0})}catch{return[]}}function Xy($){let f=d$($,IQ);if(!g2(f))return[];let J=[];for(let W of x5(f)){if(!W.isDirectory())continue;let Z=d$(f,W.name);if(W.name==="git"){for(let Q of x5(Z)){if(!Q.isDirectory())continue;let j=d$(Z,Q.name);for(let H of x5(j))if(H.isDirectory())J.push(d$(j,H.name))}continue}for(let Q of x5(Z))if(Q.isDirectory())J.push(d$(Z,Q.name))}return J.sort((W,Z)=>W.localeCompare(Z))}function EV($){try{return Wy($)}catch{return[]}}function kQ($){let f=EV($),J=new Set;f$(J,l0($)),f$(J,Hy(l0($))),f$(J,bQ(d$($,"package.json"))),f$(J,bQ(d$($,Qy,"package.json")));for(let W of f)f$(J,l0(W)),f$(J,EQ(l0(W)));return{installPath:$,entryPaths:f,names:[...J].sort((W,Z)=>W.localeCompare(Z)),installed:!0}}function Ay($,f){let J=m2($),W=f.find((j)=>xQ(J,j));if(!W)return;let Z=O1(J);while(Z!==W&&Z!==O1(Z)){if(g2(d$(Z,"package.json")))return Z;Z=O1(Z)}let Q=l0(J);if((Q==="index.ts"||Q==="index.js")&&O1(J)!==W)return O1(J);return J}function bV($,f){let J=Ay($,f);if(!J)return;let W=new Set;return f$(W,l0($)),f$(W,EQ(l0($))),f$(W,l0(J)),f$(W,EQ(l0(J))),f$(W,bQ(d$(J,"package.json"))),{installPath:J,entryPaths:[$],names:[...W].sort((Z,Q)=>Z.localeCompare(Q)),installed:!1}}function Yy($){let f=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Zy(f).filter((J)=>g2(J))}function Vy($){let f=new Map;for(let J of $){for(let W of Xy(J))f.set(W,kQ(W));for(let W of EV(J)){let Z=CV(W);if(Z){if(!f.has(Z))f.set(Z,kQ(Z));continue}let Q=bV(W,$);if(Q)f.set(Q.installPath,Q)}}return[...f.values()].sort((J,W)=>J.installPath.localeCompare(W.installPath))}function By($,f){let J=CQ(f);if(!J)return!1;if(CQ($.installPath)===J)return!0;return $.names.some((W)=>CQ(W)===J)}function Ky($,f,J){let W=m2($);for(let Q of f){if(xQ(W,Q.installPath))return Q;if(Q.entryPaths.some((j)=>m2(j)===W))return Q}let Z=CV(W);if(Z)return kQ(Z);if(g2(W))return bV(W,J);return}function Gy($){let f=O0(),J=f.disabledPlugins;if(!J?.length)return;let W=J.filter((Z)=>{let Q=m2(Z);if(xQ(Q,$.installPath))return!1;return!$.entryPaths.some((j)=>m2(j)===Q)});if(W.length===J.length)return;N$({...f,disabledPlugins:W})}function Py($){let f=O1($);while(f!==O1(f)&&l0(f)!==IQ){try{sM(f)}catch{return}f=O1(f)}}function Uy($){return`${$.names[0]??l0($.installPath)} at ${$.installPath}`}async function mQ($){let f=Yy($),J=Vy(f),W=$.path?.trim(),Z=$.name?.trim(),Q;if(W){if(Q=Ky(W,J,f),!Q)throw Error(`No plugin found at ${W}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let H=J.filter((X)=>By(X,Z));if(H.length===0)throw Error(`No plugin found matching "${Z}"`);if(H.length>1)throw Error(`Multiple plugins match "${Z}": ${H.map(Uy).join(", ")}`);Q=H[0]}let j=eM(Q.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${Q.installPath}`);if(oM(Q.installPath,{recursive:j.isDirectory(),force:!0}),Gy(Q),Q.installed)Py(Q.installPath);return{name:Z||Q.names[0]||l0(Q.installPath),installPath:Q.installPath,removedPaths:[Q.installPath],entryPaths:Q.entryPaths}}var fB={};w(fB,{updateLocalProvider:()=>p5,saveLocalProviderSettings:()=>rQ,saveLocalProviderOAuthCredentials:()=>tQ,resolveLocalClineAuthToken:()=>sQ,refreshProviderModelsFromSource:()=>iQ,normalizeOAuthProvider:()=>nQ,loginLocalProvider:()=>aQ,listLocalProviders:()=>lQ,getLocalProviderModels:()=>pQ,ensureCustomProvidersLoaded:()=>c5,deleteLocalProvider:()=>r5,addLocalProvider:()=>dQ});import*as N0 from"@cline/llms";import{getClineEnvironmentConfig as xy}from"@cline/shared";import{existsSync as Fy,mkdirSync as Ry,readFileSync as Dy,writeFileSync as Ly}from"node:fs";import{mkdir as Oy,readFile as zy,writeFile as _y}from"node:fs/promises";import{dirname as gQ,join as Ty}from"node:path";import*as w0 from"@cline/llms";import{ModelCapabilitySchema as Ny,ProviderCapabilitySchema as My,ProviderClientSchema as yy,ProviderProtocolSchema as qy}from"@cline/shared";import{z as l}from"zod";var wy=l.object({id:l.string().optional(),name:l.string().optional(),maxTokens:l.number().optional(),contextWindow:l.number().optional(),maxInputTokens:l.number().optional(),capabilities:l.array(Ny).optional(),supportsVision:l.boolean().optional(),supportsAttachments:l.boolean().optional(),supportsReasoning:l.boolean().optional()}).passthrough(),Sy=l.object({name:l.string(),baseUrl:l.string(),defaultModelId:l.string().optional(),protocol:qy.optional(),client:yy.optional(),capabilities:l.array(My).optional(),modelsSourceUrl:l.string().optional()}).passthrough(),IV=l.object({provider:Sy.optional(),models:l.record(l.string(),wy).optional()}).passthrough(),xV=l.object({version:l.literal(1),providers:l.record(l.string(),IV)}),hy=l.object({version:l.literal(1),providers:l.record(l.string(),l.unknown())}),m5=new Set;function mV($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function Rf($){return Ty(gQ($.getFilePath()),"models.json")}function g5(){return{version:1,providers:{}}}function gV($){let f=hy.safeParse($);if(!f.success)return g5();let J={};for(let[W,Z]of Object.entries(f.data.providers)){let Q=IV.safeParse(Z);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function vQ($){if(!Fy($))return g5();try{let f=Dy($,"utf8");return gV(JSON.parse(f))}catch{}return g5()}async function v2($){try{let f=await zy($,"utf8");return gV(JSON.parse(f))}catch{}return g5()}function vV($,f){Ry(gQ($),{recursive:!0});let J=xV.parse(f);Ly($,`${JSON.stringify(J,null,2)}
696
- `,"utf8")}async function v5($,f){await Oy(gQ($),{recursive:!0});let J=xV.parse(f);await _y($,`${JSON.stringify(J,null,2)}
697
- `,"utf8")}function uV($,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 cV($){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 dV($){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 Cy($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function lV($,f){return $??f??"openai-chat"}function pV($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function rV($,f,J){let W=new Set(f?.capabilities??J??[]);if(f?.supportsVision)W.add("images");if(f?.supportsAttachments)W.add("files");if(f?.supportsReasoning)W.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:W.size>0?[...W]:void 0}}function Ey($,f){for(let[J,W]of Object.entries(f??{})){let Z=W.id?.trim()||J.trim();if(!Z)continue;w0.registerModel($,Z,rV(Z,W))}}function by($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function ky($){return Object.assign({},...w0.resolveProviderModelCatalogKeys($).map((J)=>w0.getGeneratedModelsForProvider(J)))}function Iy($){let f=$.provider.trim();if(!f||w0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let W=w0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=ky(f),Q=dV($.capabilities),j=Q.length>0?Q:void 0,H=$.model?.trim(),X={...Z,...W?.models??{}};if(H)X[H]=by(H,X[H],j);let A=Object.keys(X).filter(Boolean),Y=H||A[0];if(!Y)return;let V=lV($.protocol,W?.provider.protocol),B=pV($.client,V,W?.provider.client);w0.registerProvider({provider:{id:f,name:W?.provider.name??mV(f),description:W?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:Y,capabilities:cV($.capabilities)??W?.provider.capabilities,source:"file"},models:X})}function u5($){for(let f of Object.values($.providers))Iy(f.settings)}function sJ($,f){let J=f.models??{};if(!Cy(f.provider)){Ey($,J);return}let W=dV(f.provider.capabilities),Z=Object.entries(J).map(([A,Y])=>({id:Y.id?.trim()||A.trim(),model:Y})).filter(({id:A})=>A.length>0),Q=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=lV(f.provider.protocol,void 0),H=pV(f.provider.client,j,void 0),X=Object.fromEntries(Z.map(({id:A,model:Y})=>[A,{...rV(A,Y,W.length>0?W:void 0),status:"active"}]));w0.registerProvider({provider:{id:$,name:f.provider.name.trim()||mV($),protocol:j,client:H,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:Q,capabilities:cV(f.provider.capabilities),source:"file"},models:X})}function iV($){let f=Rf($);if(m5.has(f))return;let J=vQ(f);for(let[W,Z]of Object.entries(J.providers))sJ(W,Z);m5.add(f)}async function c5($){let f=Rf($);if(m5.has(f))return;let J=await v2(f);for(let[W,Z]of Object.entries(J.providers))sJ(W,Z);m5.add(f)}function my($){return $.apiKey??$.auth?.apiKey}function gy($){return($.auth?.accessToken?.trim()??"").length>0}function aV($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function vy($){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 uy($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of $)J=J*31+W.charCodeAt(0)>>>0;return f[J%f.length]}function tV($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>uV(f,J))}async function cy($,f){let J=await N0.getModelsForProvider($);if(!f)return J;let W=await HJ($,{loadPrivateOnAuth:!0,failOnError:!1},f);return W?.knownModels?{...J,...W.knownModels}:J}function uQ($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function dy($){if(!$?.length)return;return[...new Set($)]}function ly($,f){return dy([...$??[],...f??[]])}function py($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function ry($){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 iy($){let f=$?.configFields;if(!Array.isArray(f))return;return f.filter(ry)}var d5={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},nV={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function ny($){if(!$)return[d5];if($.source!=="system")return $.baseUrl?[d5,nV]:[d5];let f=[];if($.env?.length)f.push(d5);if($.baseUrl)f.push(nV);return f}function ay($,f){return f.split(".").reduce((J,W)=>{if(!J||typeof J!=="object")return;return J[W]},$)}function ty($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function sy($,f,J){if(!$?.length)return;let W={};for(let Z of $){let j=ty(Z.path==="baseUrl"&&f?.baseUrl===void 0?J?.baseUrl:ay(f,Z.path))??Z.defaultValue;if(j!==void 0)W[Z.path]=j}return W}function sV($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function cQ($,f){let J=f?.includes("vision")??!1,W=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function oV($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await y6($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function eV($,f){let J=$.read(),W=!1;if(J.providers[f])delete J.providers[f],W=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,W=!0;if(W)$.write(J);N0.unregisterProvider(f)}async function dQ($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!W&&!Z){let G=Rf($);if((await v2(G)).providers[J]){let P=await r5($,{providerId:J});return{providerId:J,settingsPath:P.settingsPath,modelsPath:P.modelsPath,modelsCount:0}}return eV($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(N0.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=f.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let j=uQ(f.models),H=f.modelsSourceUrl?.trim(),X=await oV({providerId:J,explicitModels:j,modelsSourceUrl:H,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=f.defaultModelId?.trim()&&X.includes(f.defaultModelId.trim())?f.defaultModelId.trim():X[0],Y=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,V=sV(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:W,headers:V,timeout:f.timeoutMs,model:A,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=Rf($),K=await v2(B);return K.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:A,protocol:f.protocol,client:f.client,capabilities:Y,modelsSourceUrl:H},models:cQ(X,Y)},await v5(B,K),sJ(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:X.length}}async function p5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=Rf($),Z=await v2(W),Q=Z.providers[J];if(!Q){let _=$.getProviderSettings(J);if(!_)throw Error(`provider "${J}" does not exist`);let D=f.modelsSourceUrl?.trim(),O=uQ(f.models)[0]??_.model?.trim();if(!O&&!D)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:f.name?.trim()||aV(J),baseUrl:f.baseUrl?.trim()??_.baseUrl?.trim()??"",defaultModelId:O,protocol:_.protocol,client:_.client,capabilities:_.capabilities},models:O?cQ([O],_.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??Q.provider.name.trim();if(!j)throw Error("name is required");let H=f.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!H)throw Error("baseUrl is required");let X=f.capabilities===void 0?Q.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],A=f.protocol===void 0?Q.provider.protocol:f.protocol??void 0,Y=f.client===void 0?Q.provider.client:f.client??void 0,V=uQ(f.models),B=f.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,G=Object.keys(Q.models??{}).map((_)=>_.trim()).filter(Boolean),R=await oV({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let P=f.defaultModelId===void 0?Q.provider.defaultModelId?.trim():f.defaultModelId?.trim(),U=P&&R.includes(P)?P:R[0],z={...$.getProviderSettings(J)??{},provider:J,baseUrl:H,model:U};if(A)z.protocol=A;else delete z.protocol;if(Y)z.client=Y;else delete z.client;if(f.apiKey!==void 0){let _=f.apiKey?.trim()??"";if(_)z.apiKey=_;else delete z.apiKey}if(f.headers!==void 0){let _=sV(f.headers);if(_)z.headers=_;else delete z.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")z.timeout=f.timeoutMs;else delete z.timeout;return $.saveProviderSettings(z,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:H,defaultModelId:U,protocol:A,client:Y,capabilities:X,modelsSourceUrl:B},models:cQ(R,X)},await v5(W,Z),sJ(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W,modelsCount:R.length}}async function r5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=Rf($),Z=await v2(W);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await v5(W,Z),N0.unregisterProvider(J),eV($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W}}async function lQ($){let f=$.read(),J=N0.getProviderIds(),W=await Promise.all(J.map(async(Q)=>{let[j,H]=await Promise.all([N0.getProvider(Q),N0.getModelsForProvider(Q)]),X=tV(H),A=f.providers[Q]?.settings,Y=j?.name??aV(Q),V=ly(j?.capabilities,A?.capabilities),B=iy(j?.metadata)??ny(j);return{provider:{id:Q,name:Y,models:X.length,color:uy(Q),letter:vy(Y),enabled:Boolean(A),apiKey:A?my(A):void 0,oauthAccessTokenPresent:A?gy(A):void 0,baseUrl:A?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:A?.protocol??j?.protocol,client:A?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:sy(B,A,j),modelList:X},rank:py(j?.metadata)}}));return W.sort((Q,j)=>{if(Q.rank!==j.rank)return Q.rank-j.rank;return Q.provider.name.localeCompare(j.provider.name)||Q.provider.id.localeCompare(j.provider.id)}),{providers:W.map((Q)=>Q.provider),settingsPath:$.getFilePath()}}async function pQ($,f){let J=$.trim(),W=await cy(J,f),Z=tV(W);return{providerId:J,models:Z}}function l5($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function $B($,f){if(!l5(f))return l5($)?{...$}:void 0;let J=l5($)?{...$}:{};for(let[W,Z]of Object.entries(f)){if(Z==null||Z===""){delete J[W];continue}if(l5(Z)){let Q=$B(J[W],Z);if(Q&&Object.keys(Q).length>0)J[W]=Q;else delete J[W];continue}J[W]=Z}return Object.keys(J).length>0?J:void 0}function rQ($,f){let J=f.providerId.trim();if(f.enabled===!1){let Q=$.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return $.write(Q),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,Q)&&typeof f[Q]==="string")if(f[Q].trim().length===0)delete Z[Q];else Z[Q]=f[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,Q))Z[Q]=f[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,Q)&&f[Q]!=null){let j=$B(Z[Q],f[Q]);if(j)Z[Q]=j;else delete Z[Q]}return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function iQ($,f){let J=f.trim(),W=$.getProviderSettings(J),Q=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),H=q6(j,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!j||!H)return{providerId:J,refreshed:!1};let X=await p5($,{providerId:J,name:Q.name,baseUrl:j,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:H,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function nQ($){let f=$.trim().toLowerCase();if(f==="codex"||f==="openai-codex")return"openai-codex";if(f==="cline"||f==="oca")return f;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function oy($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function aQ($,f,J,W){let Z=GJ({onPrompt:async(Q)=>Q.defaultValue??"",openUrl:J,onOpenUrlError:({error:Q})=>{throw Q instanceof Error?Q:Error(String(Q))}});if($==="cline")return F2({apiBaseUrl:f?.baseUrl?.trim()||xy().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:W});if($==="oca")return V2({mode:f?.oca?.mode,callbacks:Z,telemetry:W});return R2({onAuth:Z.onAuth,onPrompt:Z.onPrompt,onProgress:Z.onProgress,onManualCodeInput:Z.onManualCodeInput,telemetry:W})}function tQ($,f,J,W){let Z={...J?.auth??{},accessToken:oy(f,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function sQ($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var JB={};w(JB,{getProviderConfigFields:()=>oQ});import*as i5 from"@cline/llms";import{isOAuthProviderId as ey}from"@cline/shared";var $q=["apiKey","baseUrl","awsRegion","awsProfile","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],fq={bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function Jq($,f){let J={};for(let W of $q){let Z=$[W],Q=f[W];if(Z||Q)J[W]={...Z,...Q}}return J}function Wq($){let f=fq[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:Jq($.fields,f.fields)}}var Zq=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Qq($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return Zq.has($)}function oQ($){let f=i5.normalizeProviderId($);if(ey(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=i5.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let W=J?.provider.baseUrl,Z={apiKey:{}};if(Qq(f,J))Z.baseUrl={defaultValue:W};return Wq({providerId:f,authMethod:"api-key",fields:Z})}var jB={};w(jB,{resolveLegacyClineAuth:()=>f7,migrateLegacyProviderSettings:()=>oJ});import{existsSync as jq,readFileSync as Hq}from"node:fs";import{dirname as Xq,join as eQ}from"node:path";import*as a5 from"@cline/llms";import{resolveClineDataDir as Aq}from"@cline/shared/storage";var n5="openai",QB=a5.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,WB=128000;function f7($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;let W=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:W,accountId:J.userInfo?.id}}catch{return}}function h($){let f=$?.trim();return f?f:void 0}function ZB($){if(!jq($))return;try{let f=Hq($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function Yq($){let f=$.dataDir??Aq(),J=$.globalStatePath??eQ(f,"globalState.json"),W=$.secretsPath??eQ(f,"secrets.json"),Z=ZB(J),Q=ZB(W);if(!Z&&!Q)return;return{globalState:Z??{},secrets:Q??{}}}function $7($){if($===n5)return QB;return $}function Vq($,f,J,W){let Z=J==="plan"?"planMode":"actMode",Q=f===W?h(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,H={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(H?h(typeof $[H]==="string"?$[H]:void 0):void 0)??Q}function Bq($,f,J){let W=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,Q=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??W,H=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!H&&X===void 0)return;return{...H?{effort:H}:{},...X!==void 0?{budgetTokens:X}:{}}}function Kq($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),W=h(J.access_token),Z=h(J.refresh_token),Q=h(J.accountId);if(!W&&!Z&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...Z?{refreshToken:Z}:{},...Q?{accountId:Q}:{}}}}catch{return}}function Gq($){let f=a5.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function Pq($,f,J,W){let Z=$7($),Q=h(W==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=Vq(f,$,W,Q)??Gq(Z),H=Bq(f,Z,W),X=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,A={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey},Y={};if($==="openai-codex")Object.assign(Y,Kq(J));if($==="cline")try{let U=h(J["cline:clineAccountId"]);if(U)Y.auth={...Y.auth??{},...f7(U)}}catch{}if($===n5&&f.openAiHeaders)Y.headers=f.openAiHeaders;if($==="bedrock"){let U=f.awsAuthentication==="profile"||f.awsUseProfile===!0;Y.aws={accessKey:h(J.awsAccessKey),secretKey:h(J.awsSecretKey),sessionToken:h(J.awsSessionToken),region:h(f.awsRegion),authentication:f.awsAuthentication,profile:U?h(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:h(f.awsBedrockEndpoint),customModelBaseId:h(W==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")Y.gcp={projectId:h(f.vertexProjectId),region:h(f.vertexRegion)};if($===n5&&(f.azureApiVersion||f.azureIdentity!==void 0))Y.azure={apiVersion:h(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")Y.sap={clientId:h(J.sapAiCoreClientId),clientSecret:h(J.sapAiCoreClientSecret),tokenUrl:h(f.sapAiCoreTokenUrl),resourceGroup:h(f.sapAiResourceGroup),deploymentId:h(W==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){Y.oca={mode:f.ocaMode};let U=h(J.ocaRefreshToken);if(U)Y.auth={...Y.auth??{},refreshToken:U}}if($==="qwen")Y.apiLine=f.qwenApiLine;if($==="moonshot")Y.apiLine=f.moonshotApiLine;if($==="zai")Y.apiLine=f.zaiApiLine;if($==="minimax")Y.apiLine=f.minimaxApiLine;let V={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=h(A[$]),K=h(V[$]),G={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...H?{reasoning:H}:{},...X?{timeout:X}:{},...Y},R=YJ.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function Uq($,f){if($!==QB)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:WB,maxInputTokens:WB,capabilities:["streaming","tools","images"]}}}}function Fq($,f){let J=new Set;for(let Z of[$.actModeApiProvider,$.planModeApiProvider]){let Q=h(Z);if(Q)J.add(Q)}if(h(f.apiKey))J.add("anthropic");if(h(f.openRouterApiKey))J.add("openrouter");if(h(f.openAiApiKey))J.add(n5);if(h(f.openAiNativeApiKey))J.add("openai-native");if(h(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(h(f.geminiApiKey))J.add("gemini");if(h(f.ollamaApiKey))J.add("ollama");if(h(f.awsAccessKey)||h(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||h($.awsProfile))J.add("bedrock");if(h($.vertexProjectId)||h($.vertexRegion))J.add("vertex");if(h(f.clineApiKey))J.add("cline");let W=f7(h(f["cline:clineAccountId"]));if(W?.accessToken||W?.refreshToken||W?.accountId)J.add("cline");if(h(f.ocaApiKey))J.add("oca");if(h(f.sapAiCoreClientId)||h(f.sapAiCoreClientSecret)||h($.sapAiCoreTokenUrl)||h($.sapAiCoreBaseUrl)||h($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function oJ($){let f=$.providerSettingsManager.read(),J=Yq($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:W,secrets:Z}=J,Q=W.mode==="plan"?"plan":"act",j=Fq(W,Z),H=G1();H.providers={...f.providers},H.lastUsedProvider=f.lastUsedProvider;let X=new Date().toISOString(),A=0,Y=eQ(Xq($.providerSettingsManager.getFilePath()),"models.json"),V=vQ(Y),B=0;for(let R of j){let P=$7(R);if(H.providers[P])continue;let U=Pq(R,W,Z,Q);if(!U)continue;H.providers[P]={settings:U,updatedAt:X,tokenSource:"migration"},A+=1;let F=Uq(P,U);if(F&&!V.providers[P])V.providers[P]=F,B+=1}if(A===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=h(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),G=K?$7(K):void 0;if(H.lastUsedProvider=f.lastUsedProvider??(G&&H.providers[G]?G:Object.keys(H.providers)[0]),$.providerSettingsManager.write(H),B>0)vV(Y,V);return{migrated:A>0||B>0,providerCount:Object.keys(H.providers).length,lastUsedProvider:H.lastUsedProvider}}L0();m4();var AB={};w(AB,{trimMessagesToCheckpoint:()=>XB,trimMessagesBeforeCheckpoint:()=>W7,readSessionCheckpointHistory:()=>eJ,createRestoredCheckpointMetadata:()=>J7,createCheckpointRestorePlan:()=>Z7,applyCheckpointToWorktree:()=>Q7});import{execFile as Rq}from"node:child_process";import{promisify as Dq}from"node:util";var u2=Dq(Rq);function eJ($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let Z=String(W.ref??"").trim(),Q=Number(W.createdAt??0),j=Number(W.runCount??0);if(Z.length===0||!Number.isFinite(Q)||!Number.isInteger(j)||j<1)return[];let H=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:Z,createdAt:Q,runCount:j,...H?{kind:H}:{}}]})}function J7($,f){let J=eJ($).filter((Z)=>Z.runCount<=f),W=J.at(-1);return W?{latest:W,history:J}:void 0}function Lq($,f){return $.reduce((J,W)=>{if(W.runCount>f)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function HB($,f){let J=0;for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return W}throw Error(`Could not find user message for checkpoint run ${f}`)}function XB($,f){let J=HB($,f);return $.slice(0,J+1)}function W7($,f){let J=HB($,f);return $.slice(0,J)}function Z7($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=Lq(eJ($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let W=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:W,...$.restoreMessages!==!1?{messages:XB($.messages??[],f)}:{}}}async function Q7($,f){if((await u2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await u2("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await u2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await u2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await u2("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await u2("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}var YB={};w(YB,{SessionVersioningService:()=>z1,SessionVersioningError:()=>S0});class S0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function Oq($){let f=$.sessionId.trim();if(!f)throw new S0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new S0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new S0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new S0("invalid_restore","checkpointRunCount must be a positive integer");return f}class z1{async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,W=Oq({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(W);if(!Z)throw new S0("session_not_found",`Session ${W} not found`);let Q=f?await $.readMessages(W):void 0;if(f&&Q?.length===0)throw new S0("session_messages_not_found",`No messages found for session ${W}`);let j=Z7({session:Z,messages:Q,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??Q7)(j.cwd,j.checkpoint);let H=B$({session:Z,messages:Q});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:H};let X=J7(Z,$.checkpointRunCount),A=$.restore?.omitCheckpointMessageFromSession?W7(Q??[],$.checkpointRunCount):j.messages??[],Y={sourceSession:Z,sourceMessages:Q,sourceSnapshot:H,plan:j,restoredCheckpointMetadata:X,initialMessages:A,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new S0("invalid_restore","start is required when restore.messages is true");let V=$.buildStartInput?await $.buildStartInput(Y,$.start):$.start,B=await $.startSession(V),K=$.getStartedSessionId?.(B);if(K)await($.retainCheckpointRefs??LX)(j.cwd,K,X?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:H,...G?{restoredSnapshot:B$({session:G,messages:A})}:{}}}}var VB={};w(VB,{FileTeamPersistenceStore:()=>t5});import{appendFileSync as zq,existsSync as j7,mkdirSync as _q,readFileSync as Tq,renameSync as Nq,unlinkSync as Mq,writeFileSync as yq}from"node:fs";import{join as H7}from"node:path";import{resolveTeamDataDir as qq}from"@cline/shared/storage";function wq($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class t5{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=wq($.teamName),J=$.baseDir?.trim()||qq();this.dirPath=H7(J,f),this.statePath=H7(this.dirPath,"state.json"),this.taskHistoryPath=H7(this.dirPath,"task-history.jsonl")}loadState(){if(!j7(this.statePath))return;try{let $=Tq(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 XV(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`;yq(J,`${JSON.stringify(f,null,2)}
698
- `,"utf8"),Nq(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(),zq(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
699
- `,"utf8")}ensureDir(){if(!j7(this.dirPath))_q(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(j7(this.statePath))Mq(this.statePath)}}var BB={};w(BB,{ChatViewStateSchema:()=>X7,ChatSummarySchema:()=>fW,ChatSessionStatusSchema:()=>o5,ChatSessionConfigSchema:()=>s5,ChatMessageSchema:()=>$W,ChatMessageRoleSchema:()=>e5});import{z as C}from"zod";var s5=C.object({workspaceRoot:C.string().min(1),cwd:C.string().optional(),provider:C.string().min(1),model:C.string().min(1),mode:C.enum(["act","plan"]).default("act"),apiKey:C.string(),systemPrompt:C.string().optional(),rules:C.string().optional(),maxIterations:C.number().int().positive().optional(),enableTools:C.boolean(),enableSpawn:C.boolean().optional(),enableTeams:C.boolean().optional(),autoApproveTools:C.boolean().optional(),missionStepInterval:C.number().int().positive().optional(),missionTimeIntervalMs:C.number().int().positive().optional()}),o5=C.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),e5=C.enum(["user","assistant","tool","system","status","error"]),$W=C.object({id:C.string().min(1),sessionId:C.string().nullable(),role:e5,content:C.string(),createdAt:C.number().int().nonnegative(),meta:C.object({stream:C.enum(["stdout","stderr"]).optional(),toolName:C.string().optional(),iteration:C.number().int().nonnegative().optional(),agentId:C.string().optional(),conversationId:C.string().optional(),hookEventName:C.string().optional(),inputTokens:C.number().int().nonnegative().optional(),outputTokens:C.number().int().nonnegative().optional(),checkpoint:C.object({ref:C.string(),createdAt:C.number().int().nonnegative(),runCount:C.number().int().positive(),kind:C.enum(["stash","commit"]).optional()}).optional()}).optional()}),fW=C.object({toolCalls:C.number().int().nonnegative(),tokensIn:C.number().int().nonnegative(),tokensOut:C.number().int().nonnegative()}),X7=C.object({sessionId:C.string().nullable(),status:o5,config:s5,messages:C.array($W),rawTranscript:C.string(),error:C.string().nullable(),summary:fW});var KB={};w(KB,{CORE_BUILD_VERSION:()=>A7});var A7=M3;import{Agent as Vw,createAgentRuntime as Bw}from"@cline/agents";var PB={};w(PB,{fetchClineRecommendedModels:()=>Y7,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW});import{getClineEnvironmentConfig as Sq}from"@cline/shared";var hq=5000,JW={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 Cq($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function GB($){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 Eq($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],W=Array.isArray(f.free)?f.free:[],Z=J.map(GB).filter((j)=>j!==null),Q=W.map(GB).filter((j)=>j!==null);if(Z.length===0&&Q.length===0)return null;return{recommended:Z,free:Q}}function bq($){let f=$.baseUrl?.trim();if(f)return f;let J=Sq().apiBaseUrl;try{return($.providerSettingsManager??new R$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function kq($,f,J){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await $(f,{signal:W.signal})}finally{clearTimeout(Z)}}async function Y7($={}){try{let f=bq($),J=$.fetchImpl??fetch,W=await kq(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??hq);if(!W.ok)throw Error(`HTTP ${W.status}`);let Z=await W.json(),Q=Eq(Z);if(Q)return Q}catch{}return Cq(JW)}var UB={};w(UB,{loadLlmsConfigFromFile:()=>B7,defineLlmsConfig:()=>V7});import{readFile as Iq}from"node:fs/promises";import xq from"node:path";function V7($){return $}async function B7($){let f=xq.resolve($),J=await Iq(f,"utf8"),W;try{W=JSON.parse(J)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${Q}`)}return mq(W,f)}function mq($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let W=$.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}var zB={};w(zB,{createLlmsSdk:()=>G7,DefaultLlmsSdk:()=>$4});import{BUILT_IN_PROVIDER_IDS as DB,createHandler as uq,createHandlerAsync as cq,getProviderCollection as dq,hasProvider as LB,registerAsyncHandler as lq,registerHandler as pq,registerModel as rq,registerProvider as OB}from"@cline/llms";function FB($){return $?{...$}:{}}function gq($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function vq($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function RB($){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 K7{providers=new Map;register($){vq($.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??{},...FB($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:gq($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...FB($.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 $4{configuredProviders=new K7;constructor($){this.applyConfig($)}createHandler($){return uq(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return cq(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(OB($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)pq($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)lq($.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.`);OB({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($){rq($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...DB]}async getBuiltInProviders(){return(await Promise.all(DB.map((f)=>dq(f)))).filter((f)=>f!==void 0).map((f)=>RB({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=LB(f.id),W=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof W==="string"&&LB(W);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function G7($){return new $4($)}MW();async function iq(){return Promise.resolve().then(() => (LQ(),LV))}function Fw(){return new Date().toISOString()}function Rw($){if(SB($)!=="providers.json")return;let f=U7($);if(SB(f)!=="settings")return;return U7(f)}class R${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Uw(),this.dataDir=$.dataDir??Rw(this.filePath),this.dataDir||!$.filePath)oJ({providerSettingsManager:this,dataDir:this.dataDir});if(iV(this),u5(this.read()),P7(this.filePath))try{wB(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!P7(this.filePath))return G1();try{let $=Gw(this.filePath,"utf8"),f=JSON.parse($),J=G2.safeParse(f);if(J.success)return u5(J.data),J.data}catch{}return G1()}write($){let f=G2.parse($),J=U7(this.filePath);if(!P7(J))Kw(J,{recursive:!0,mode:448});Pw(this.filePath,`${JSON.stringify(f,null,2)}
700
- `,"utf8");try{wB(this.filePath,384)}catch{}u5(f)}saveProviderSettings($,f={}){let J=YJ.parse($),W=this.read(),Z=J.provider,Q=f.setLastUsed!==!1,j=W.providers[Z],H=f.tokenSource??j?.tokenSource??"manual",X={...W,providers:{...W.providers,[Z]:{settings:J,updatedAt:Fw(),tokenSource:H}},lastUsedProvider:Q?Z:W.lastUsedProvider};return this.write(X),X}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return v0(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return v0(f,$)}async refreshCatalog(){try{await B2({})}catch{}}}L0();x4();import{getClineEnvironmentConfig as Dw,isOAuthProviderId as Lw}from"@cline/shared";var F7="workos:";function Ow($,f){if($==="cline")return`${F7}${f}`;return f}function zw($,f){if($==="cline"&&f.toLowerCase().startsWith(F7))return f.slice(F7.length);return f}function _w($){let J=_0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function Tw($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=_w(f);if(W)return W;return Date.now()-1}function Nw($,f){let J=f.auth?.accessToken?.trim(),W=f.auth?.refreshToken?.trim();if(!J||!W)return null;let Z=zw($,J);if(!Z)return null;return{access:Z,refresh:W,expires:Tw(f,Z),accountId:f.auth?.accountId}}function Mw($,f){let J=$?.expiresAt,W=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===W}class ZW 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 R7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new R$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!Lw($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let W=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,W),W}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let W=Nw($,J);if(!W)return null;let Z=await this.resolveCredentials($,J,W,f);if(!Z)throw new ZW($);let Q=Ow($,Z.access),j={...J.auth??{},accessToken:Q,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let H={...J,auth:j},X=!Mw(J.auth,H.auth);if(X)this.providerSettingsManager.saveProviderSettings(H,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:Q,accountId:Z.accountId,refreshed:X}}async resolveCredentials($,f,J,W){if($==="cline")return UJ(J,{apiBaseUrl:f.baseUrl?.trim()||Dw().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if($==="oca")return ZJ(J,{forceRefresh:W,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return RJ(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as yw}from"@cline/shared";import{nanoid as qw}from"nanoid";class hB{list($){return $?p0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((X)=>X.id===J);if(W<0)return{sessionId:f.sessionId,prompts:p0($),updated:!1};let Z=$.pendingPrompts[W];if(!Z)return{sessionId:f.sessionId,prompts:p0($),updated:!1};let Q=f.prompt===void 0?Z.prompt:yw(f.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,H={...Z,prompt:Q,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(W,1),ww($,H,W,Z.delivery),{sessionId:f.sessionId,prompts:p0($),prompt:QW(H),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:f.sessionId,prompts:p0($),removed:!1};let[Z]=$.pendingPrompts.splice(W,1);return{sessionId:f.sessionId,prompts:p0($),prompt:Z?QW(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j}=f,H=$.pendingPrompts.findIndex((X)=>X.prompt===J);if(H>=0){let[X]=$.pendingPrompts.splice(H,1),A={...X,prompt:J,mode:W??X.mode,userImages:Q??X.userImages,userFiles:j??X.userFiles};if(Z==="steer"||X.delivery==="steer")$.pendingPrompts.unshift({...A,delivery:"steer"});else $.pendingPrompts.push(A)}else{let X={id:`pending_${Date.now()}_${qw(5)}`,prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(X);else $.pendingPrompts.push(X)}return p0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((W)=>W.delivery==="steer");if(f<0)return{prompts:p0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:p0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:p0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),p0($)}clear($){return $.pendingPrompts.length=0,[]}}class D7{deps;service=new hB;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:p0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let W=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{W=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,W&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=QW(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function QW($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function p0($){return $.pendingPrompts.map(QW)}function ww($,f,J,W){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(W==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}L0();class O7{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let W=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=IZ(J),j=!!W&&(!Q.agentId||Q.agentId===L7(W.agent));xZ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:L7(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(jQ(J,f),f.type==="agent_event"){let W={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};xZ(W,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let W=I$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:L7(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(W)a$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await HQ($,f,this.deps.invokeBackendOptional),J)XQ(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let X=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!X)return;let A=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!A)return;await X.ingestEvent(A);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let W=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():$,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:Q,delivery:j})}handlePluginLog($,f,J){let W=this.deps.getSession($),Z=J??W?.config.extensionContext?.logger??W?.config.logger;if(!Z||!f||typeof f!=="object")return;let Q=f,j=typeof Q.message==="string"?Q.message:"";if(!j)return;let H=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(H.sessionId??=$,typeof Q.pluginName==="string"&&Q.pluginName)H.pluginName=Q.pluginName;if(Q.level==="debug"){Z.debug(j,H);return}if(Q.level==="error"){if(Z.error)Z.error(j,H);else Z.log(j,{...H,severity:"error"});return}Z.log(j,H)}}function L7($){return $.getAgentId()}function z7($){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:H1($.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 _7($,f){let J=$[f];return typeof J==="function"?J:null}async function CB($,f,...J){let W=_7($,f);if(!W)throw Error(`session service method not available: ${f}`);return Promise.resolve(W.apply($,J))}async function EB($,f,...J){let W=_7($,f);if(!W)return;await Promise.resolve(W.apply($,J))}async function bB($,f,...J){let W=_7($,f);if(!W)return;return await Promise.resolve(W.apply($,J))}Z$();L0();function T7($,f,J,W){return Q1({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=f.enableTools?p1({cwd:f.cwd,...m0[b$({mode:f.mode})],executors:W}):[];if(f.enableSpawnAgent)Q.push(T7($,f,J,W));return S1(Q)},onSubAgentEvent:(Q)=>$.onAgentEvent(J,f,Q),onSubAgentStart:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let H=I$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId});if(H)a$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...H});f8(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...H}),$.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime,H=$.subAgentStarts.get(Q.subAgentId),X=H?Date.now()-H.startedAt:0,A=Q.result?.text?Q.result.text.split(`
701
- `).length:0;f8(f.telemetry,{event:"ended",ulid:J,durationMs:X,outputLines:A,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...I$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as Sw,stat as hw}from"node:fs/promises";var Cw=20480000;async function kB($){let f=await hw($);if(!f.isFile())throw Error("Path is not a file");if(f.size>Cw)throw Error("File is too large to read into context.");let J=await Sw($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var IB=5000;function Q4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function vw($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=Q4(f.inputTokens),W=Q4(f.outputTokens),Z=Q4(f.cacheReadTokens),Q=Q4(f.cacheWriteTokens),j=Q4(f.totalCost);if(J===void 0||W===void 0||Z===void 0||Q===void 0||j===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:Z,cacheWriteTokens:Q,totalCost:j}}function uw($,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 F${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new vJ;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new z1;constructor($){let f=bw();if(f)gw(f);let J=h1($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new x2,this.createAgentInstance=$.createAgent??((W)=>new Z1(W)),this.defaultCapabilities=R0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new R$,this.oauthTokenManager=$.oauthTokenManager??new R7({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new D7({getSession:(W)=>this.sessions.get(W),emit:(W)=>this.emit(W),send:(W)=>this.runTurn(W)}),this.pendingPrompts={list:async(W)=>this.pendingPromptsController.list(W.sessionId),update:async(W)=>this.pendingPromptsController.update(W),delete:async(W)=>this.pendingPromptsController.delete(W)},this.eventBridge=new O7({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,Z,Q)=>{this.invoke("persistSessionMessages",W,Z,Q)},enqueuePendingPrompt:(W,Z)=>this.pendingPromptsController.enqueue(W,Z),invokeBackendOptional:(W,...Z)=>this.invokeOptional(W,...Z)})}async startSession($){let f=$.source??P0.CLI,J=s(),W=$.config.sessionId?.trim()??"",Z=W||Iw(),Q=$,j=Q.initialMessages??[],H=j.length>0?of(j):B0(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=N7(X,Z),Y=N7(A,`${Z}.messages.json`),V=N7(A,`${Z}.json`),B=H1($.config),K=y0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:B,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:Y}),G;if(W.length>0&&j.length>0&&!Q.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",Z);if(k)K=k,G={manifestPath:V,messagesPath:k.messages_path||Y,manifest:k}}let P=await this.seedAggregateUsageFromArtifacts({initialUsage:H,sessionDir:A,rootMessagesPath:G?.messagesPath??Y,manifest:K});this.usageBySession.set(Z,H),this.aggregateUsageBySession.set(Z,P);let U=R0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,z=$.localRuntime,_=z?.extensionContext?.logger??z?.logger,D=z?.extensionContext?.automation,O;O=await HA({input:Q,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,k.payload,_);return}this.eventBridge.handlePluginEvent(Z,k,D)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(Z,k),O.config.onTeamEvent?.(k)},createSpawnTool:()=>T7({getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,D0,n)=>this.eventBridge.dispatchAgentEvent(k,D0,n),invokeBackendOptional:(k,...D0)=>this.invokeOptional(k,...D0)},O.config,Z,F),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(Z,()=>k)}});let N=await this.runtimeBuilder.build(O.runtimeBuilderInput),q=O.config,$0=O.providerConfig;if(N.teamRuntime&&!q.teamName?.trim())q.teamName=N.teamRuntime.getTeamName();let A0=[...N.tools,...q.extraTools??[]],o=N.extensions??O.extensions,Y0={sessionId:Z,providerId:$0.providerId,modelId:$0.modelId,apiKey:$0.apiKey,baseUrl:$0.baseUrl,headers:$0.headers,knownModels:$0.knownModels,providerConfig:$0,thinking:q.thinking,reasoningEffort:q.reasoningEffort??$0.reasoningEffort,systemPrompt:q.systemPrompt,maxIterations:q.maxIterations,execution:q.execution,prepareTurn:L8(q),tools:A0,hooks:O.hooks,extensions:o,hookErrorMode:q.hookErrorMode,initialMessages:O.effectiveInput.initialMessages,userFileContentLoader:kB,toolPolicies:O.toolPolicies,requestToolApproval:O.requestToolApproval?async(k)=>{let D0=O.requestToolApproval,n=this.sessions.get(Z);if(n)await this.markTurnPending(n);try{if(!D0)return{approved:!1,reason:"Tool approval callback is not configured."};return await D0(k)}finally{let a0=this.sessions.get(Z);if(a0?.status==="pending")await this.markTurnRunning(a0)}}:void 0,telemetry:q.telemetry,onConsecutiveMistakeLimitReached:q.onConsecutiveMistakeLimitReached,completionPolicy:N.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(Z);return k?rJ(k.prompt,k.mode??q.mode):void 0},logger:N.logger??q.logger,extensionContext:q.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(Z,q,k)};Y0.hooks={...Y0.hooks,onEvent:async(k)=>{if(await O.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let D0=this.sessions.get(Z);if(!D0)return;let n=D0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,n,q.systemPrompt)}catch(a0){q.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:a0}),Df(q.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:a0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:q.providerId,modelId:q.modelId}})}}};let i=this.createAgentInstance(Y0);if(Y0.onEvent)i.subscribeEvents(Y0.onEvent);N.registerLeadAgent?.(i);let J$=I$({agentId:i.getAgentId(),conversationId:i.getConversationId(),teamId:N.teamRuntime?.getTeamId(),teamName:N.teamRuntime?.getTeamName(),teamRole:N.teamRuntime?"lead":void 0});if(AA(q,Z,W.length>0,B,J$),J$)a$(q.telemetry,{ulid:Z,modelId:q.modelId,provider:q.providerId,...J$});if(N.teamRuntime)y4(q.telemetry,{ulid:Z,teamId:N.teamRuntime.getTeamId(),teamName:N.teamRuntime.getTeamName(),leadAgentId:i.getAgentId(),restoredFromPersistence:N.teamRestoredFromPersistence===!0});let p={sessionId:Z,config:q,sessionMetadata:Q.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:N,agent:i,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:O.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,p),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(p),await this.invoke("persistSessionMessages",p.sessionId,j,p.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(p,"completed",0)}let n0;try{if(Q.prompt?.trim())if(n0=await this.executeTurn(p,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!p.interactive)await this.finalizeSingleRun(p,n0.finishReason);else await this.completeInteractiveTurn(p,n0.finishReason)}catch(k){if(p.interactive&&p.aborting)n0=await this.completeAbortedInteractiveTurn(p);else throw Df(p.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:p.sessionId,providerId:p.config.providerId,modelId:p.config.modelId}}),await this.failSession(p),k}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:Y,result:n0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let W=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),W=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:W,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw Df(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=s9(this.usageBySession.get($)),J=s9(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&&!W0(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&&!W0(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 z7(f);let J=$.trim();if(!J)return;let W=await this.getRow(J);if(W)return d8(W);let Z=await this.readManifest(J);return Z?z5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(d8),W=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(W.has(Z.sessionId))continue;J.unshift(z7(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 R1(J.messagesPath);let W=await this.readManifest(f);return R1(W?.messages_path)}async dispatchHookEvent($){await MY($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),W=J.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=W;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,W,J.userImages,J.userFiles);while(AQ($,Z.finishReason)){let Q=await YQ($);if(Q.length===0)break;let j=VQ($,Q);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(pJ($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),W=B0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:W}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:W,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,W){let Z=$.started||$.agent.getMessages().length>0,Q=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??B0(),H=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=H,$.turnPrimaryUsage=B0(),$.turnUsageByAgent=new Map,L4($.config.telemetry,$.sessionId,$.config.mode),wf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let X=Z?()=>$.agent.continue(f,J,W):()=>$.agent.run(f,J,W),A=await this.runWithAuthRetry($,X,Q);$.started=!0;let Y=A6(A.messages,A,Q);$.persistedMessages=Y;let V=p8($.turnUsageByAgent?.values()??[]),B=H0(j,A.usage),K=H0(H0(B0(),A.usage),V),G=H0(H,K);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:G.totalCost,usage:B,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,Y,$.config.systemPrompt),this.observeTaskCompletionTool($,A),A}catch(X){throw Df($.config.telemetry,{component:"core",operation:"session.turn",error:X,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),X}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((W)=>W.name===J0.SUBMIT_AND_EXIT&&W.error===void 0))return;$.submitAndExitObserved=!0,e2($.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=H1($.config),W=mw(f.prompt).trim();if(!W)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await gf(W,J);YA($.config.telemetry,Z);let Q=rJ(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),H=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),X=Array.from(new Set([...j,...H]));return{prompt:Q,userImages:f.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=H1($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),W=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(pJ($))return;let J=f==="aborted"||$.aborting,W=f==="error";await this.shutdownSession($,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)e2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});q5($);let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Df($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){W("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){W("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Df($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){W("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let W=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!W.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,W0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=W.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=W.endedAt??s(),$.endedAt=W0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(W){if(!xw(W,$.config.providerId))throw W;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(W){if(W instanceof ZW)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=new y$($);throw Df(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>kw(W)?W:M7($,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return I$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=H0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let W=M7(f),Z=`${J}.messages.json`,Q;try{Q=Ew($)}catch{return B0()}let j=B0();for(let H of Q){if(!H.endsWith(".messages.json"))continue;if(H===Z)continue;let X=M7($,H);if(X===W)continue;let A=await R1(X);if(A.length===0)continue;j=H0(j,of(A))}return j}withPersistedAggregateUsageFloor($,f){let J=vw(f.metadata?.aggregateUsage);if(J)return uw($,J);let W=f.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=$.totalCost)return $;return{...$,totalCost:W}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:B$({session:f,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),IB))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(IB)).find((W)=>W.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return CB(this.sessionService,$,...f)}invokeOptional($,...f){return EB(this.sessionService,$,...f)}invokeOptionalValue($,...f){return bB(this.sessionService,$,...f)}}function dw($){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 lw($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function NB($={}){let f=new F$({sessionService:new U$(new G$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||P0.CLI,interactive:!1,config:{providerId:cw(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:lw(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:dw(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function pw($){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 xB=120,y7="...";function f4($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=xB)return f;let J=xB-Buffer.byteLength(y7,"utf8");if(J<=0)return y7;let W="";for(let Z of f){if(Buffer.byteLength(W+Z,"utf8")>J)break;W+=Z}return`${W}${y7}`}async function mB($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await R1(J)].reverse().find((X)=>X.role==="assistant"),Q=Z?pw(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",H=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:f4(Q&&Q.length>0?Q:H.length>0?H:j),severity:"info"}}import{captureSdkError as AW,createSessionId as OS}from"@cline/shared";import{createSessionId as aw}from"@cline/shared";import{createSessionId as nw}from"@cline/shared";function rw($){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 iw($){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 jW($,f,J,W){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:rw($.status),participants:f?[...f.participants.values()]:[],metadata:iw($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...W?{aggregateUsage:{...W}}:{}}}function u($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function m($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function HW($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function h0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function Lf($,f,J){return{version:"v1",event:$,eventId:nw("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function r0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let W=await $.sessionHost.getAccumulatedUsage?.(f);return jW(J,$.sessionState.get(f),W?.usage,W?.aggregateUsage)}async function i0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[W,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return B$({session:J,messages:W,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function XW($,f,J,W,Z={}){let Q=$.sessionState.get(f);if(Q){if(Z.interactive!==void 0)Q.interactive=Z.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:W});return Q}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:W}]])};return $.sessionState.set(f,j),j}async function q7($,f){let J=aw("approval_"),W=f.sessionId;if($.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{$.pendingApprovals.set(J,{sessionId:W,resolve:Q}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},W))})}function w7($,f,J){let W=$.pendingApprovals.get(f);if(!W)return;return $.pendingApprovals.delete(f),W.resolve(J),{sessionId:W.sessionId}}function S7($,f,J){let W=0;for(let[Z,Q]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:Q.sessionId}))continue;$.pendingApprovals.delete(Z),Q.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},Q.sessionId)),W+=1}return W}async function gB($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return m(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,Q=f.payload?.approved===!0,j=w7($,J,{approved:Q,reason:Z});if(!j)return m(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:Z},j.sessionId)),u(f,{approvalId:J,approved:Q})}import{createSessionId as ow}from"@cline/shared";function tw($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var vB={debug:10,info:20,warn:30,error:40,silent:50};function sw(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function g($,f,J={}){if(vB[$]<vB[sw()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,Q])=>[Z,tw(Q)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function h7($,f){let J=f instanceof Error?f.stack||f.message:String(f);g("error",$,{error:J})}async function uB($,f,J,W,Z,Q){let j=ow("capreq_"),H=performance.now();return g("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((X,A)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:Q,resolve:(Y)=>{if(g(Y.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:Y.ok,error:Y.error,durationMs:Math.round(performance.now()-H)}),!Y.ok){A(Error(Y.error||`Capability ${J} was rejected by ${Z}.`));return}X(Y.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:W},f)),g("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function cB($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return m(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==W.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return W.onProgress?.(Q),u(f,{requestId:J})}function _1($,f,J){let W=0;for(let[Z,Q]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...Q}))continue;$.pendingCapabilityRequests.delete(Z),g("warn","capability.request.cancelled",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),W+=1}return W}async function dB($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",W=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!W||!Z)return m(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,W,Q,Z);return u(f,j)}catch(Q){return m(f,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function lB($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return m(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==W.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);$.pendingCapabilityRequests.delete(J);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,H=f.payload?.ok===!0;return g(H?"info":"warn","capability.respond",{requestId:J,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:H,error:j}),W.resolve({ok:H,payload:Q,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:H,payload:Q,error:j},W.sessionId)),u(f,{requestId:J,ok:H})}import{createSessionId as ew}from"@cline/shared";function pB($,f){let J=f.payload,W=J?.clientId?.trim()||f.clientId?.trim()||ew("client_");return $.clients.set(W,{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),u(f,{clientId:W})}function rB($,f){let J=f.clientId?.trim(),W=J?$.clients.get(J):void 0;if(!J||!W)return m(f,"client_not_found","Client is not registered with this hub.");let Z=HW(f.payload?.metadata);if(W.lastSeenAt=Date.now(),Z)W.metadata=JSON.parse(JSON.stringify(Z));return u(f)}function iB($,f,J){let W=f.clientId?.trim();if(W)$.clients.delete(W),J(W),$.publish($.buildEvent("hub.client.disconnected",{clientId:W}));return u(f)}function nB($,f){return u(f,{clients:[...$.clients.values()]})}var $S=30000;function fS($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function JS($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function WS($,f,J){let W=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${f}`;return m($,C1,W)}function ZS($){return $?$:void 0}function QS($){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 jS($,f,J,W){let Z=performance.now(),Q=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:W},H=setInterval(()=>{if(Q)return;let Y=Math.round(performance.now()-Z);g("warn","run.heartbeat",{...j,elapsedMs:Y}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:Y,...W?{timeoutMs:W}:{}},J.sessionId))},$S),X=$.sessionHost.runTurn(J);X.then((Y)=>{if(!Q)return;g("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:Y?.finishReason})},(Y)=>{if(!Q)return;g("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:Y})});let A;try{if(!W)return await X;return await Promise.race([X,new Promise((Y,V)=>{A=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${W}ms.`;Q=!0,clearInterval(H),V(Error(B)),g("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),S7($,(K)=>K.sessionId===J.sessionId,B),_1($,(K)=>K.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((K)=>{g("error","run.timeout_abort_failed",{...j,error:K})})},W)})])}finally{if(Q=!0,clearInterval(H),A)clearTimeout(A)}}async function aB($,f){let J=h0(f),W=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!Z.trim())return m(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let Q=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,j=Array.isArray(Q?.userFiles)?Q.userFiles.filter((Y)=>typeof Y==="string"):void 0,H=QS(W);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await jS($,f,{sessionId:J,prompt:Z,mode:ZS(W.mode),delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:j,timeoutMs:H},H)}catch(Y){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);if(q$(Y))return WS(f,J,Y);throw $.publish($.buildEvent("run.failed",{reason:"error",error:Y instanceof Error?Y.message:String(Y)},J)),Y}if(X){let Y=await i0($,J),V=JS(X);if($.publish($.buildEvent(fS(X.finishReason),{reason:X.finishReason,...V?{error:V}:{},result:X,...Y?{snapshot:Y}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let A=await i0($,J);return u(f,X||A?{...X?{result:X}:{},...A?{snapshot:A}:{}}:void 0)}async function tB($,f){let J=h0(f),W=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";S7($,(Z)=>Z.sessionId===J,W);try{await $.sessionHost.abort(J,f.payload?.reason)}catch(Z){g("warn","run.abort_failed",{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J,error:Z})}finally{_1($,(Z)=>Z.sessionId===J,W)}return u(f,{applied:!0})}async function sB($,f){let J=E2(f.payload?.payload);if(!J)return m(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),u(f,{applied:!0})}async function oB($,f){switch(f.type){case"chunk":return;case"agent_event":await HS($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,W]=await Promise.all([r0($,f.payload.sessionId),i0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},f.payload.sessionId));return}case"ended":await XS($,f);return;default:return}}async function HS($,f){let{sessionId:J,event:W}=f.payload;if(W.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:W.iteration},J));return}if(W.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},J));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){$.publish($.buildEvent("assistant.delta",{text:W.text},J));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},J));return}if(W.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},J));return}}if(W.type==="content_end"){switch(W.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:W.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:W.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},J));break}return}if(W.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens??0,cacheWriteTokens:W.cacheWriteTokens??0,totalCost:W.cost??0},totals:{inputTokens:W.totalInputTokens,outputTokens:W.totalOutputTokens,cacheReadTokens:W.totalCacheReadTokens??0,cacheWriteTokens:W.totalCacheWriteTokens??0,totalCost:W.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(W.type==="done")$.publish($.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function XS($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),W=J===f.payload.reason||J==="run.start.reply";if(W)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,Q]=await Promise.all([r0($,f.payload.sessionId),i0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await mB(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(W)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...Q?{snapshot:Q}:{}},f.payload.sessionId))}import{createSessionId as $K,parseRuntimeConfigExtensions as fK}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as bp,HUB_COMPACTION_CAPABILITY as kp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Ip,HUB_HOOK_CAPABILITY_PREFIX as xp,HUB_MISTAKE_LIMIT_CAPABILITY as mp,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as gp,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as vp,isHubToolExecutorName as AS}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as pp,HUB_COMPACTION_CAPABILITY as rp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ip,HUB_HOOK_CAPABILITY_PREFIX as np,HUB_MISTAKE_LIMIT_CAPABILITY as ap,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as tp,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as sp}from"@cline/shared";var YS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Of($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function VS($,f){let J=typeof $.name==="string"?$.name.trim():"",W=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",Q=Of($.inputSchema);if(!J||!W||!Q||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:W,inputSchema:Q,...Of($.lifecycle)?{lifecycle:Of($.lifecycle)}:{}}}function E7($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let W of $){if(!W||typeof W!=="object"||Array.isArray(W))continue;let Z=W,Q=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(Q==="tool"){let H=VS(Z,J);if(H)f.push(H);continue}if(Q==="toolExecutor"){let H=Z.executor;if(!AS(H))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:H});continue}if(Q==="hook"){let H=typeof Z.name==="string"?Z.name.trim():"";if(!H)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:H});continue}if(Q==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...Of(Z.config)?{config:Of(Z.config)}:{}});continue}if(Q==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...Of(Z.config)?{config:Of(Z.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(Q==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function eB($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function BS($){return Object.hasOwn($,"update")?$.update:$}function j4($){return $.trim().replace(/^\/+/,"").toLowerCase()}function KS($){let f=($??[]).map(j4).filter(Boolean);return f.length>0?new Set(f):void 0}function GS($,f,J){if(!J)return!0;let W=j4($),Z=j4(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function C7($,f){let J=KS(f);return $.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>GS(W.id,W.name,J))}function PS($,f){let J=async(W,Z)=>{let Q=j4(W),H=C7($,f).filter((B)=>B.id===Q||j4(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(H.length!==1)return H.length>1?`Skill "${W}" is ambiguous. Use one of: ${H.map((B)=>B.id).join(", ")}`:`Skill "${W}" not found.`;let X=H[0].skill,A=Z?.trim(),Y=A?`
693
+ version = team_outcome_fragments.version + 1`,[Q,W.outcomeId,W.id,W.section,W.sourceAgentId,W.sourceRunId??null,W.content,W.status,W.reviewedBy??null,W.reviewedAt?W.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted(f,$){let J=d2(f),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(Q.length===0)return[];let Z=lW();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
694
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[$,Z,J]),Q.map((W)=>W.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function pW(f={}){try{let $=new M1(f);return $.init(),$}catch{let $=new j4({teamDir:f.teamDir});return $.init(),$}}function o5(f,$){return wq(f,$)}function Sq(f,$){let J=$?.["*"]??{},Q=$?.[f]??{};return{...J,...Q}.enabled!==!1}function Eq(f,$){return f.filter((J)=>Sq(J.name,$))}function rW(f,$){return x$(Eq(f,$))}var hq={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 bq(f){let $=f.trim().toLowerCase();return hq[$]??$}function kq(f,$){if($.tools===void 0)return f;let J=new Set($.tools.map(bq));if($.skills!==void 0)J.add("skills");return f.filter((Q)=>J.has(Q.name))}function f9(){return`team-${Cq(5)}`}function e5(f,$,J,Q,Z,W,j,H){let X=c0[mf({mode:J})],A=J2($,Q,J,Z??$2);return rW($1({cwd:f,...X,enableSkills:!!j,...A,executors:{...j?{skills:j}:{},...H??{}}}),W)}function Iq(f){return e5(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,xq,f.toolExecutors).some(($)=>$.name==="skills")}var xq=async()=>"";async function gq(f){let $=M0();if(!df({filePath:$}))return{tools:[]};let J=new D1({clientFactory:q2({settingsPath:$})}),Q;try{Q=await R1(J,{filePath:$})}catch(H){await J.dispose().catch(()=>{});let X=H instanceof Error?H.message:String(H);return f?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${X}`),{tools:[]}}let Z=Q.filter((H)=>H.disabled!==!0),W=await Promise.allSettled(Z.map((H)=>y2({serverName:H.name,provider:J}))),j=[];for(let[H,X]of W.entries())if(X.status==="fulfilled")j.push(...X.value);else{let A=X.reason instanceof Error?X.reason.message:String(X.reason);f?.log(`[mcp] Failed to load tools from MCP server "${Z[H].name}", skipping: ${A}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function mq(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function vq(f){if(f===void 0)return!0;switch(f){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function cq(f){let $=c0[mf({mode:f.mode})];return{sessionId:f.sessionId||"",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",enableTools:f.enableTools!==!1,enableSpawnAgent:f.enableSpawnAgent??$.enableSpawnAgent??!0,enableAgentTeams:f.enableAgentTeams??$.enableAgentTeams??!0,disableMcpSettingsTools:f.disableMcpSettingsTools===!0,yolo:f.yolo===!0,missionLogIntervalSteps:typeof f.missionLogIntervalSteps==="number"&&Number.isFinite(f.missionLogIntervalSteps)?f.missionLogIntervalSteps:3,missionLogIntervalMs:typeof f.missionLogIntervalMs==="number"&&Number.isFinite(f.missionLogIntervalMs)?f.missionLogIntervalMs:120000}}class l2{teamRuntimeEntries=new Map;async build(f){let{config:$,hooks:J,extensions:Q,logger:Z,telemetry:W,createSpawnTool:j,onTeamRestored:H,userInstructionService:X,configExtensions:A,toolExecutors:Y}=f,V=f.onTeamEvent??(()=>{}),B=cq($),K=$.workspaceRoot??$.cwd,P=f.toolPolicies??$.toolPolicies,R=Wf(),G=[],F=$.teamName?.trim()||f9(),U=$.sessionId?.trim()||F,_=B.enableSpawnAgent?E2({workspaceRoot:K}):{configs:[],errors:[]},M=_.configs.some((g)=>g.skills!==void 0),L=o5(A,"rules"),D=o5(A,"skills"),y=D||M,b=o5(A,"workflows"),I=o5(A,"plugins"),o=L||D||b,A0=!1,f0=Boolean(X),t=X,s0;for(let g of _.errors)(Z??$.logger)?.log?.(`[agents] Failed to load agent config at ${g.path}: ${g.error.message}`);if(!t&&(o||M))t=z$({skills:y?{workspacePath:K,includePluginSkills:I,pluginSkillDirectories:I?f.pluginSkillDirectories:void 0,pluginPaths:$.pluginPaths,cwd:$.cwd}:{workspacePath:K},rules:{workspacePath:$.cwd},workflows:{workspacePath:$.cwd}});if(t)await t.start().catch(()=>{});let E$=B.enableTools&&D&&Boolean(t)&&t?.hasConfiguredSkills($.skills)===!0&&Iq({cwd:$.cwd,providerId:$.providerId,mode:B.mode,modelId:$.modelId,toolRoutingRules:$.toolRoutingRules,toolPolicies:P,toolExecutors:Y}),i=t&&o?t.createExtension({includeRules:L,includeSkills:D,includeWorkflows:b,registerSkillsTool:E$,allowedSkillNames:$.skills}):void 0,Of=i?[...Q??$.extensions??[],i]:Q??$.extensions;if(B.enableTools){if(G.push(...e5($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,P,void 0,Y)),!B.disableMcpSettingsTools){let g=await gq($.logger);G.push(...g.tools),s0=g.shutdown}}let w,P0=B.enableAgentTeams?pW():void 0,Q0=P0?.loadRuntime(U),y0=Q0?.state,C1=Q0?.teammates??[],_f=new Map(C1.map((g)=>[g.agentId,g])),Zf=$.sessionId||F,t2,S1=[],R4=!1,Tf=K$({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey??"",baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:J,extensions:Of,logger:Z??$.logger,telemetry:f.telemetry??$.telemetry,workspaceMetadata:$.workspaceMetadata});if(B.enableSpawnAgent){if(_.configs.length>0)G.push(...rW(h2({configProvider:Tf,agents:_.configs,createSubAgentTools:(g)=>B.enableTools?kq(e5($.cwd,g.providerId??$.providerId,B.mode,g.modelId??$.modelId,$.toolRoutingRules,P,g.skills!==void 0&&t?.createSkillsExecutor?t.createSkillsExecutor(g.skills):void 0,Y),g):[],hookErrorMode:$.hookErrorMode,toolPolicies:P,requestToolApproval:f.requestToolApproval,onSubAgentEvent:f.onSubAgentEvent,onSubAgentStart:f.onSubAgentStart,onSubAgentEnd:f.onSubAgentEnd}),P))}if(!this.teamRuntimeEntries.has(Zf))this.teamRuntimeEntries.set(Zf,{delegatedAgentConfigProvider:Tf});let D4=()=>{if(!B.enableAgentTeams)return;let g=this.teamRuntimeEntries.get(Zf)??{delegatedAgentConfigProvider:Tf};if(this.teamRuntimeEntries.set(Zf,g),w=g.runtime,!w){if(w=new _1({teamName:F,leadAgentId:$.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:($0)=>{if(V($0),w&&P0){if($0.type==="teammate_spawned"&&$0.teammate?.rolePrompt){let zf={agentId:$0.agentId,rolePrompt:$0.teammate.rolePrompt,modelId:$0.teammate.modelId,maxIterations:$0.teammate.maxIterations};_f.set(zf.agentId,zf)}if($0.type==="teammate_shutdown"&&!vq($0.reason))_f.delete($0.agentId);P0.handleTeamEvent(U,$0),P0.persistRuntime(U,w.exportState(),Array.from(_f.values()))}}}),y0)w.hydrateState(y0),R4=!0;g.runtime=w}if(!A0){if(!w)return;A0=!0;let $0=W2({runtime:w,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(y0),restoredTeammates:C1,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(zf)=>{S1=zf,t2?.addTools(zf)},createBaseTools:B.enableTools?()=>e5($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,P,void 0,Y):void 0,teammateConfigProvider:Tf});if(R4)w.recoverActiveRuns("runtime_recovered");if($0.restoredFromPersistence)H?.();G.push(...$0.tools)}return w};if(B.enableSpawnAgent&&j){let g=j();G.push({...g,execute:async($0,zf)=>{return D4(),g.execute($0,zf)}})}if(B.enableAgentTeams)D4();let E1=rW(G,P),y9=E1.some((g)=>g.name==="submit_and_exit"&&g.lifecycle?.completesRun===!0),L4=B.enableAgentTeams?()=>{let g=this.teamRuntimeEntries.get(Zf)?.runtime;if(!g)return;let $0=g.listTasks(),zf=$0.some((tf)=>tf.status==="in_progress"||tf.status==="pending"),Q3=g.listRuns({}),tK=Q3.some((tf)=>tf.status==="running"||tf.status==="queued");if(zf||tK){let tf=$0.filter((k0)=>k0.status==="in_progress"||k0.status==="pending").map((k0)=>`${k0.id} (${k0.status}): ${k0.title}`).join(", "),Z3=Q3.filter((k0)=>k0.status==="running"||k0.status==="queued").map((k0)=>`${k0.id} (${k0.status})`).join(", "),w9=[];if(tf)w9.push(`Unfinished tasks: ${tf}`);if(Z3)w9.push(`Active runs: ${Z3}`);return`[SYSTEM] You still have team obligations. ${w9.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,aK=y9?{requireCompletionTool:!0,...L4?{completionGuard:L4}:{}}:L4?{completionGuard:L4}:void 0;return{tools:E1,logger:Z??$.logger,telemetry:W??$.telemetry,teamRuntime:w,teamRestoredFromPersistence:Boolean(y0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(Zf)?.delegatedAgentConfigProvider??Tf,extensions:Of,completionPolicy:aK,registerLeadAgent:(g)=>{if(t2=g,S1.length>0)g.addTools(x$(S1,[...R]))},shutdown:async(g)=>{if(mq(w,g),this.teamRuntimeEntries.delete(Zf),await s0?.(),!f0)t?.stop()}}}}var fB={};q(fB,{requestDesktopToolApproval:()=>nW});import{mkdir as uq,readFile as dq,unlink as lq,writeFile as pq}from"node:fs/promises";import{join as eV}from"node:path";function rq(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function iq(f){return new Promise(($)=>setTimeout($,f))}async function iW(f){try{await lq(f)}catch{}}async function nW(f,$={}){let J=$.approvalDir?.trim(),Q=$.sessionId?.trim();if(!J||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await uq(J,{recursive:!0});let Z=rq(`${f.toolCallId}`),W=eV(J,`${Q}.request.${Z}.json`),j=eV(J,`${Q}.decision.${Z}.json`),H=$.nowIso??(()=>new Date().toISOString());await pq(W,`${JSON.stringify({requestId:Z,sessionId:Q,createdAt:H(),toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,iteration:f.iteration,agentId:f.agentId,conversationId:f.conversationId},null,2)}
695
+ `,"utf8");let X=$.timeoutMs??300000,A=$.pollIntervalMs??200,Y=Date.now();while(Date.now()-Y<X){try{let V=await dq(j,"utf8"),B=JSON.parse(V),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([iW(j),iW(W)]),K}catch{}await iq(A)}return await iW(W),{approved:!1,reason:"Tool approval request timed out"}}jf();jf();var ZB={};q(ZB,{uninstallPlugin:()=>J7});import{existsSync as r2,readdirSync as nq,readFileSync as aq,rmdirSync as tq,rmSync as sq,statSync as oq}from"node:fs";import{basename as i0,dirname as w$,extname as eq,isAbsolute as fy,join as af,relative as $y,resolve as p2,sep as aW}from"node:path";import{discoverPluginModulePaths as Jy,resolvePluginConfigSearchPaths as Qy}from"@cline/shared/storage";var f7="_installed",Zy="package",Wy=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function tW(f){return f.trim().toLowerCase()}function Qf(f,$){let J=$?.trim();if(!J)return;f.add(J)}function jy(f){return f.replace(/-[0-9a-f]{12}$/i,"")}function sW(f){let $=eq(f);return $?f.slice(0,-$.length):f}function oW(f){if(!r2(f))return;try{let $=JSON.parse(aq(f,"utf8"));return typeof $.name==="string"?$.name.trim():void 0}catch{return}}function $7(f,$){let J=$y($,f);return J===""||!J.startsWith("..")&&!fy(J)}function $B(f){let J=p2(f).split(aW),Q=J.lastIndexOf(f7);if(Q<0)return;let Z=J[Q+1];if(!Z)return;let W=Wy.get(Z)??1,j=Q+2+W;if(J.length<j)return;let H=J.slice(0,j).join(aW)||aW;return r2(H)?H:void 0}function $9(f){try{return nq(f,{withFileTypes:!0})}catch{return[]}}function Hy(f){let $=af(f,f7);if(!r2($))return[];let J=[];for(let Q of $9($)){if(!Q.isDirectory())continue;let Z=af($,Q.name);if(Q.name==="git"){for(let W of $9(Z)){if(!W.isDirectory())continue;let j=af(Z,W.name);for(let H of $9(j))if(H.isDirectory())J.push(af(j,H.name))}continue}for(let W of $9(Z))if(W.isDirectory())J.push(af(Z,W.name))}return J.sort((Q,Z)=>Q.localeCompare(Z))}function JB(f){try{return Jy(f)}catch{return[]}}function eW(f){let $=JB(f),J=new Set;Qf(J,i0(f)),Qf(J,jy(i0(f))),Qf(J,oW(af(f,"package.json"))),Qf(J,oW(af(f,Zy,"package.json")));for(let Q of $)Qf(J,i0(Q)),Qf(J,sW(i0(Q)));return{installPath:f,entryPaths:$,names:[...J].sort((Q,Z)=>Q.localeCompare(Z)),installed:!0}}function Xy(f,$){let J=p2(f),Q=$.find((j)=>$7(J,j));if(!Q)return;let Z=w$(J);while(Z!==Q&&Z!==w$(Z)){if(r2(af(Z,"package.json")))return Z;Z=w$(Z)}let W=i0(J);if((W==="index.ts"||W==="index.js")&&w$(J)!==Q)return w$(J);return J}function QB(f,$){let J=Xy(f,$);if(!J)return;let Q=new Set;return Qf(Q,i0(f)),Qf(Q,sW(i0(f))),Qf(Q,i0(J)),Qf(Q,sW(i0(J))),Qf(Q,oW(af(J,"package.json"))),{installPath:J,entryPaths:[f],names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!1}}function Ay(f){let $=f.workspaceRoot?.trim()||f.cwd?.trim()||process.cwd();return Qy($).filter((J)=>r2(J))}function Yy(f){let $=new Map;for(let J of f){for(let Q of Hy(J))$.set(Q,eW(Q));for(let Q of JB(J)){let Z=$B(Q);if(Z){if(!$.has(Z))$.set(Z,eW(Z));continue}let W=QB(Q,f);if(W)$.set(W.installPath,W)}}return[...$.values()].sort((J,Q)=>J.installPath.localeCompare(Q.installPath))}function Vy(f,$){let J=tW($);if(!J)return!1;if(tW(f.installPath)===J)return!0;return f.names.some((Q)=>tW(Q)===J)}function By(f,$,J){let Q=p2(f);for(let W of $){if($7(Q,W.installPath))return W;if(W.entryPaths.some((j)=>p2(j)===Q))return W}let Z=$B(Q);if(Z)return eW(Z);if(r2(Q))return QB(Q,J);return}function Ky(f){let $=_0(),J=$.disabledPlugins;if(!J?.length)return;let Q=J.filter((Z)=>{let W=p2(Z);if($7(W,f.installPath))return!1;return!f.entryPaths.some((j)=>p2(j)===W)});if(Q.length===J.length)return;Cf({...$,disabledPlugins:Q})}function Py(f){let $=w$(f);while($!==w$($)&&i0($)!==f7){try{tq($)}catch{return}$=w$($)}}function Gy(f){return`${f.names[0]??i0(f.installPath)} at ${f.installPath}`}async function J7(f){let $=Ay(f),J=Yy($),Q=f.path?.trim(),Z=f.name?.trim(),W;if(Q){if(W=By(Q,J,$),!W)throw Error(`No plugin found at ${Q}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let H=J.filter((X)=>Vy(X,Z));if(H.length===0)throw Error(`No plugin found matching "${Z}"`);if(H.length>1)throw Error(`Multiple plugins match "${Z}": ${H.map(Gy).join(", ")}`);W=H[0]}let j=oq(W.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${W.installPath}`);if(sq(W.installPath,{recursive:j.isDirectory(),force:!0}),Ky(W),W.installed)Py(W.installPath);return{name:Z||W.names[0]||i0(W.installPath),installPath:W.installPath,removedPaths:[W.installPath],entryPaths:W.entryPaths}}var zB={};q(zB,{updateLocalProvider:()=>A9,saveLocalProviderSettings:()=>Y7,saveLocalProviderOAuthCredentials:()=>P7,resolveLocalClineAuthToken:()=>F7,refreshProviderModelsFromSource:()=>V7,normalizeOAuthProvider:()=>B7,loginLocalProvider:()=>K7,loginAndSaveLocalProviderOAuthCredentials:()=>G7,listLocalProviders:()=>X7,getLocalProviderModels:()=>A7,ensureCustomProvidersLoaded:()=>j9,deleteLocalProvider:()=>Y9,addLocalProvider:()=>H7});import*as q0 from"@cline/llms";import{existsSync as Fy,mkdirSync as Uy,readFileSync as Ry,writeFileSync as Dy}from"node:fs";import{mkdir as Ly,readFile as Oy,writeFile as _y}from"node:fs/promises";import{dirname as Q7,join as Ty}from"node:path";import*as E0 from"@cline/llms";import{ModelCapabilitySchema as zy,ProviderCapabilitySchema as My,ProviderClientSchema as Ny,ProviderProtocolSchema as qy}from"@cline/shared";import{z as r}from"zod";var yy=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(zy).optional(),supportsVision:r.boolean().optional(),supportsAttachments:r.boolean().optional(),supportsReasoning:r.boolean().optional()}).passthrough(),wy=r.object({name:r.string(),baseUrl:r.string(),defaultModelId:r.string().optional(),protocol:qy.optional(),client:Ny.optional(),capabilities:r.array(My).optional(),modelsSourceUrl:r.string().optional()}).passthrough(),WB=r.object({provider:wy.optional(),models:r.record(r.string(),yy).optional()}).passthrough(),jB=r.object({version:r.literal(1),providers:r.record(r.string(),WB)}),Cy=r.object({version:r.literal(1),providers:r.record(r.string(),r.unknown())}),J9=new Set;function HB(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function N1(f){return Ty(Q7(f.getFilePath()),"models.json")}function Q9(){return{version:1,providers:{}}}function XB(f){let $=Cy.safeParse(f);if(!$.success)return Q9();let J={};for(let[Q,Z]of Object.entries($.data.providers)){let W=WB.safeParse(Z);if(W.success)J[Q]=W.data}return{version:1,providers:J}}function Z7(f){if(!Fy(f))return Q9();try{let $=Ry(f,"utf8");return XB(JSON.parse($))}catch{}return Q9()}async function i2(f){try{let $=await Oy(f,"utf8");return XB(JSON.parse($))}catch{}return Q9()}function AB(f,$){Uy(Q7(f),{recursive:!0});let J=jB.parse($);Dy(f,`${JSON.stringify(J,null,2)}
696
+ `,"utf8")}async function Z9(f,$){await Ly(Q7(f),{recursive:!0});let J=jB.parse($);await _y(f,`${JSON.stringify(J,null,2)}
697
+ `,"utf8")}function YB(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function VB(f){if(!f||f.length===0)return;let $=new Set;if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("tools"))$.add("tools");return $.size>0?[...$]:void 0}function BB(f){let $=new Set;if(!f||f.length===0)return[...$];if(f.includes("streaming"))$.add("streaming");if(f.includes("tools"))$.add("tools");if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("vision"))$.add("images"),$.add("files");return[...$]}function Sy(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function KB(f,$){return f??$??"openai-chat"}function PB(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function GB(f,$,J){let Q=new Set($?.capabilities??J??[]);if($?.supportsVision)Q.add("images");if($?.supportsAttachments)Q.add("files");if($?.supportsReasoning)Q.add("reasoning");return{id:f,name:$?.name??f,maxTokens:$?.maxTokens,contextWindow:$?.contextWindow,maxInputTokens:$?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function Ey(f,$){for(let[J,Q]of Object.entries($??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;E0.registerModel(f,Z,GB(Z,Q))}}function hy(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function by(f){return Object.assign({},...E0.resolveProviderModelCatalogKeys(f).map((J)=>E0.getGeneratedModelsForProvider(J)))}function ky(f){let $=f.provider.trim();if(!$||E0.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let Q=E0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=by($),W=BB(f.capabilities),j=W.length>0?W:void 0,H=f.model?.trim(),X={...Z,...Q?.models??{}};if(H)X[H]=hy(H,X[H],j);let A=Object.keys(X).filter(Boolean),Y=H||A[0];if(!Y)return;let V=KB(f.protocol,Q?.provider.protocol),B=PB(f.client,V,Q?.provider.client);E0.registerProvider({provider:{id:$,name:Q?.provider.name??HB($),description:Q?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:Y,capabilities:VB(f.capabilities)??Q?.provider.capabilities,source:"file"},models:X})}function W9(f){for(let $ of Object.values(f.providers))ky($.settings)}function H4(f,$){let J=$.models??{};if(!Sy($.provider)){Ey(f,J);return}let Q=BB($.provider.capabilities),Z=Object.entries(J).map(([A,Y])=>({id:Y.id?.trim()||A.trim(),model:Y})).filter(({id:A})=>A.length>0),W=$.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=KB($.provider.protocol,void 0),H=PB($.provider.client,j,void 0),X=Object.fromEntries(Z.map(({id:A,model:Y})=>[A,{...GB(A,Y,Q.length>0?Q:void 0),status:"active"}]));E0.registerProvider({provider:{id:f,name:$.provider.name.trim()||HB(f),protocol:j,client:H,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:W,capabilities:VB($.provider.capabilities),source:"file"},models:X})}function FB(f){let $=N1(f);if(J9.has($))return;let J=Z7($);for(let[Q,Z]of Object.entries(J.providers))H4(Q,Z);J9.add($)}async function j9(f){let $=N1(f);if(J9.has($))return;let J=await i2($);for(let[Q,Z]of Object.entries(J.providers))H4(Q,Z);J9.add($)}function Iy(f){return f.apiKey??f.auth?.apiKey}function xy(f){return(f.auth?.accessToken?.trim()??"").length>0}function RB(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function gy(f){let $=f.split(/\s+/).filter(Boolean);if($.length===0)return"?";if($.length===1)return $[0].slice(0,2).toUpperCase();return`${$[0][0]}${$[1][0]}`.toUpperCase()}function my(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of f)J=J*31+Q.charCodeAt(0)>>>0;return $[J%$.length]}function DB(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>YB($,J))}async function vy(f,$){let J=await q0.getModelsForProvider(f);if(!$)return J;let Q=await DJ(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return Q?.knownModels?{...J,...Q.knownModels}:J}function W7(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function cy(f){if(!f?.length)return;return[...new Set(f)]}function uy(f,$){return cy([...f??[],...$??[]])}function dy(f){let $=f?.popularRank;return typeof $==="number"&&Number.isFinite($)?$:Number.MAX_SAFE_INTEGER}function ly(f){if(!f||typeof f!=="object")return!1;let $=f;return typeof $.path==="string"&&$.path.trim().length>0&&typeof $.label==="string"&&$.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String($.type))}function py(f){let $=f?.configFields;if(!Array.isArray($))return;return $.filter(ly)}var H9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},UB={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function ry(f){if(!f)return[H9];if(f.source!=="system")return f.baseUrl?[H9,UB]:[H9];let $=[];if(f.env?.length)$.push(H9);if(f.baseUrl)$.push(UB);return $}function iy(f,$){return $.split(".").reduce((J,Q)=>{if(!J||typeof J!=="object")return;return J[Q]},f)}function ny(f){if(typeof f==="string"||typeof f==="number"||typeof f==="boolean"||f===null)return f;return}function ay(f,$,J){if(!f?.length)return;let Q={};for(let Z of f){let j=ny(Z.path==="baseUrl"&&$?.baseUrl===void 0?J?.baseUrl:iy($,Z.path))??Z.defaultValue;if(j!==void 0)Q[Z.path]=j}return Q}function LB(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function j7(f,$){let J=$?.includes("vision")??!1,Q=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function OB(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await p6(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function _B(f,$){let J=f.read(),Q=!1;if(J.providers[$])delete J.providers[$],Q=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,Q=!0;if(Q)f.write(J);q0.unregisterProvider($)}async function H7(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=$.baseUrl.trim(),Z=$.apiKey?.trim()??"";if(!Q&&!Z){let P=N1(f);if((await i2(P)).providers[J]){let G=await Y9(f,{providerId:J});return{providerId:J,settingsPath:G.settingsPath,modelsPath:G.modelsPath,modelsCount:0}}return _B(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:P,modelsCount:0}}if(q0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=$.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=W7($.models),H=$.modelsSourceUrl?.trim(),X=await OB({providerId:J,explicitModels:j,modelsSourceUrl:H,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=$.defaultModelId?.trim()&&X.includes($.defaultModelId.trim())?$.defaultModelId.trim():X[0],Y=$.capabilities?.length?[...new Set($.capabilities)]:void 0,V=LB($.headers);f.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:V,timeout:$.timeoutMs,model:A,protocol:$.protocol,client:$.client},{setLastUsed:!1});let B=N1(f),K=await i2(B);return K.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:A,protocol:$.protocol,client:$.client,capabilities:Y,modelsSourceUrl:H},models:j7(X,Y)},await Z9(B,K),H4(J,K.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:B,modelsCount:X.length}}async function A9(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=N1(f),Z=await i2(Q),W=Z.providers[J];if(!W){let M=f.getProviderSettings(J);if(!M)throw Error(`provider "${J}" does not exist`);let L=$.modelsSourceUrl?.trim(),D=W7($.models)[0]??M.model?.trim();if(!D&&!L)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:$.name?.trim()||RB(J),baseUrl:$.baseUrl?.trim()??M.baseUrl?.trim()??"",defaultModelId:D,protocol:M.protocol,client:M.client,capabilities:M.capabilities},models:D?j7([D],M.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=$.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let H=$.baseUrl?.trim()??W.provider.baseUrl.trim();if(!H)throw Error("baseUrl is required");let X=$.capabilities===void 0?W.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],A=$.protocol===void 0?W.provider.protocol:$.protocol??void 0,Y=$.client===void 0?W.provider.client:$.client??void 0,V=W7($.models),B=$.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,K=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!B,P=Object.keys(W.models??{}).map((M)=>M.trim()).filter(Boolean),R=await OB({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:P,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let G=$.defaultModelId===void 0?W.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=G&&R.includes(G)?G:R[0],_={...f.getProviderSettings(J)??{},provider:J,baseUrl:H,model:F};if(A)_.protocol=A;else delete _.protocol;if(Y)_.client=Y;else delete _.client;if($.apiKey!==void 0){let M=$.apiKey?.trim()??"";if(M)_.apiKey=M;else delete _.apiKey}if($.headers!==void 0){let M=LB($.headers);if(M)_.headers=M;else delete _.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")_.timeout=$.timeoutMs;else delete _.timeout;return f.saveProviderSettings(_,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:H,defaultModelId:F,protocol:A,client:Y,capabilities:X,modelsSourceUrl:B},models:j7(R,X)},await Z9(Q,Z),H4(J,Z.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Q,modelsCount:R.length}}async function Y9(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=N1(f),Z=await i2(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await Z9(Q,Z),q0.unregisterProvider(J),_B(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Q}}async function X7(f){let $=f.read(),J=q0.getProviderIds(),Q=await Promise.all(J.map(async(W)=>{let[j,H]=await Promise.all([q0.getProvider(W),q0.getModelsForProvider(W)]),X=DB(H),A=$.providers[W]?.settings,Y=j?.name??RB(W),V=uy(j?.capabilities,A?.capabilities),B=py(j?.metadata)??ry(j);return{provider:{id:W,name:Y,models:X.length,color:my(W),letter:gy(Y),enabled:Boolean(A),apiKey:A?Iy(A):void 0,oauthAccessTokenPresent:A?xy(A):void 0,baseUrl:A?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:A?.protocol??j?.protocol,client:A?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:ay(B,A,j),modelList:X},rank:dy(j?.metadata)}}));return Q.sort((W,j)=>{if(W.rank!==j.rank)return W.rank-j.rank;return W.provider.name.localeCompare(j.provider.name)||W.provider.id.localeCompare(j.provider.id)}),{providers:Q.map((W)=>W.provider),settingsPath:f.getFilePath()}}async function A7(f,$){let J=f.trim(),Q=await vy(J,$),Z=DB(Q);return{providerId:J,models:Z}}function X9(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function TB(f,$){if(!X9($))return X9(f)?{...f}:void 0;let J=X9(f)?{...f}:{};for(let[Q,Z]of Object.entries($)){if(Z==null||Z===""){delete J[Q];continue}if(X9(Z)){let W=TB(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 Y7(f,$){let J=$.providerId.trim();if($.enabled===!1){let W=f.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return f.write(W),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let Z={...f.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,W)&&typeof $[W]==="string")if($[W].trim().length===0)delete Z[W];else Z[W]=$[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,W))Z[W]=$[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,W)&&$[W]!=null){let j=TB(Z[W],$[W]);if(j)Z[W]=j;else delete Z[W]}return f.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function V7(f,$){let J=$.trim(),Q=f.getProviderSettings(J),W=q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),H=r6(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!H)return{providerId:J,refreshed:!1};let X=await A9(f,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:H,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function B7(f){let $=f.trim().toLowerCase(),J=B0($);if(J)return J.providerId;throw Error(`provider "${f}" does not support OAuth login`)}async function K7(f,$,J,Q){let Z=B0(f);if(!Z)throw Error(`provider "${f}" does not support OAuth login`);let W=T2({onPrompt:async(j)=>j.defaultValue??"",openUrl:J,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return Z.login({settings:$,callbacks:W,telemetry:Q})}function P7(f,$,J,Q,Z){return l$({manager:f,providerId:$,settings:J,credentials:Q,setLastUsed:Z?.setLastUsed})}async function G7(f,$,J,Q){let Z=T2({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});return y8(f,$,{callbacks:Z,telemetry:Q})}function F7(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var MB={};q(MB,{getProviderConfigFields:()=>U7});import*as V9 from"@cline/llms";var ty=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],sy={"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 oy(f,$){let J={};for(let Q of ty){let Z=f[Q],W=$[Q];if(Z||W)J[Q]={...Z,...W}}return J}function ey(f){let $=sy[f.providerId];if(!$)return f;return{...f,description:$.description??f.description,fields:$.mode==="replace"?$.fields:oy(f.fields,$.fields)}}var fw=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function $w(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return fw.has(f)}function U7(f){let $=V9.normalizeProviderId(f);if(d$($))return{providerId:$,authMethod:"oauth",fields:{}};let J=V9.MODEL_COLLECTIONS_BY_PROVIDER_ID[$];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:$,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if($w($,J))Z.baseUrl={defaultValue:Q};return ey({providerId:$,authMethod:"api-key",fields:Z})}var wB={};q(wB,{resolveLegacyClineAuth:()=>L7,migrateLegacyProviderSettings:()=>X4});import{existsSync as Jw,readFileSync as Qw}from"node:fs";import{dirname as Zw,join as R7}from"node:path";import*as K9 from"@cline/llms";import{resolveClineDataDir as Ww}from"@cline/shared/storage";var B9="openai",yB=K9.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,NB=128000;function L7(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;let Q=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:Q,accountId:J.userInfo?.id}}catch{return}}function S(f){let $=f?.trim();return $?$:void 0}function qB(f){if(!Jw(f))return;try{let $=Qw(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function jw(f){let $=f.dataDir??Ww(),J=f.globalStatePath??R7($,"globalState.json"),Q=f.secretsPath??R7($,"secrets.json"),Z=qB(J),W=qB(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function D7(f){if(f===B9)return yB;return f}function Hw(f,$,J,Q){let Z=J==="plan"?"planMode":"actMode",W=$===Q?S(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,H={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[$];return(H?S(typeof f[H]==="string"?f[H]:void 0):void 0)??W}function Xw(f,$,J){let Q=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,Z=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,W=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,j=($==="gemini"?Z:void 0)??Q,H=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,X=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!H&&X===void 0)return;return{...H?{effort:H}:{},...X!==void 0?{budgetTokens:X}:{}}}function Aw(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),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 Yw(f){let $=K9.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function Vw(f,$,J,Q){let Z=D7(f),W=S(Q==="plan"?$.planModeApiProvider:$.actModeApiProvider),j=Hw($,f,Q,W)??Yw(Z),H=Xw($,Z,Q),X=typeof $.requestTimeoutMs==="number"&&Number.isInteger($.requestTimeoutMs)&&$.requestTimeoutMs>0?$.requestTimeoutMs:void 0,A={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey},Y={};if(f==="openai-codex")Object.assign(Y,Aw(J));if(f==="cline")try{let F=S(J["cline:clineAccountId"]);if(F)Y.auth={...Y.auth??{},...L7(F)}}catch{}if(f===B9&&$.openAiHeaders)Y.headers=$.openAiHeaders;if(f==="bedrock"){let F=$.awsAuthentication==="profile"||$.awsUseProfile===!0;Y.aws={accessKey:S(J.awsAccessKey),secretKey:S(J.awsSecretKey),sessionToken:S(J.awsSessionToken),region:S($.awsRegion),authentication:$.awsAuthentication,profile:F?S($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:S($.awsBedrockEndpoint),customModelBaseId:S(Q==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)}}if(f==="vertex")Y.gcp={projectId:S($.vertexProjectId),region:S($.vertexRegion)};if(f===B9&&($.azureApiVersion||$.azureIdentity!==void 0))Y.azure={apiVersion:S($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")Y.sap={clientId:S(J.sapAiCoreClientId),clientSecret:S(J.sapAiCoreClientSecret),tokenUrl:S($.sapAiCoreTokenUrl),resourceGroup:S($.sapAiResourceGroup),deploymentId:S(Q==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){Y.oca={mode:$.ocaMode};let F=S(J.ocaRefreshToken);if(F)Y.auth={...Y.auth??{},refreshToken:F}}if(f==="qwen")Y.apiLine=$.qwenApiLine;if(f==="moonshot")Y.apiLine=$.moonshotApiLine;if(f==="zai")Y.apiLine=$.zaiApiLine;if(f==="minimax")Y.apiLine=$.minimaxApiLine;let V={anthropic:$.anthropicBaseUrl,openai:$.openAiBaseUrl,ollama:$.ollamaBaseUrl,lmstudio:$.lmStudioBaseUrl,litellm:$.liteLlmBaseUrl,gemini:$.geminiBaseUrl,requesty:$.requestyBaseUrl,asksage:$.asksageApiUrl,dify:$.difyBaseUrl,oca:$.ocaBaseUrl,aihubmix:$.aihubmixBaseUrl,sapaicore:$.sapAiCoreBaseUrl},B=S(A[f]),K=S(V[f]),P={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...H?{reasoning:H}:{},...X?{timeout:X}:{},...Y},R=_J.safeParse(P);if(!R.success)return;return Object.keys(P).filter((F)=>F!=="provider").length>0?R.data:void 0}function Bw(f,$){if(f!==yB)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model,contextWindow:NB,maxInputTokens:NB,capabilities:["streaming","tools","images"]}}}}function Kw(f,$){let J=new Set;for(let Z of[f.actModeApiProvider,f.planModeApiProvider]){let W=S(Z);if(W)J.add(W)}if(S($.apiKey))J.add("anthropic");if(S($.openRouterApiKey))J.add("openrouter");if(S($.openAiApiKey))J.add(B9);if(S($.openAiNativeApiKey))J.add("openai-native");if(S($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(S($.geminiApiKey))J.add("gemini");if(S($.ollamaApiKey))J.add("ollama");if(S($.awsAccessKey)||S($.awsBedrockApiKey)||f.awsAuthentication!==void 0||f.awsUseProfile===!0||S(f.awsProfile))J.add("bedrock");if(S(f.vertexProjectId)||S(f.vertexRegion))J.add("vertex");if(S($.clineApiKey))J.add("cline");let Q=L7(S($["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)J.add("cline");if(S($.ocaApiKey))J.add("oca");if(S($.sapAiCoreClientId)||S($.sapAiCoreClientSecret)||S(f.sapAiCoreTokenUrl)||S(f.sapAiCoreBaseUrl)||S(f.sapAiResourceGroup)||f.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function X4(f){let $=f.providerSettingsManager.read(),J=jw(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=Kw(Q,Z),H=T$();H.providers={...$.providers},H.lastUsedProvider=$.lastUsedProvider;let X=new Date().toISOString(),A=0,Y=R7(Zw(f.providerSettingsManager.getFilePath()),"models.json"),V=Z7(Y),B=0;for(let R of j){let G=D7(R);if(H.providers[G])continue;let F=Vw(R,Q,Z,W);if(!F)continue;H.providers[G]={settings:F,updatedAt:X,tokenSource:"migration"},A+=1;let U=Bw(G,F);if(U&&!V.providers[G])V.providers[G]=U,B+=1}if(A===0&&B===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let K=S(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),P=K?D7(K):void 0;if(H.lastUsedProvider=$.lastUsedProvider??(P&&H.providers[P]?P:Object.keys(H.providers)[0]),f.providerSettingsManager.write(H),B>0)AB(Y,V);return{migrated:A>0||B>0,providerCount:Object.keys(H.providers).length,lastUsedProvider:H.lastUsedProvider}}O0();t4();var EB={};q(EB,{trimMessagesToCheckpoint:()=>SB,trimMessagesBeforeCheckpoint:()=>_7,readSessionCheckpointHistory:()=>A4,createRestoredCheckpointMetadata:()=>O7,createCheckpointRestorePlan:()=>T7,applyCheckpointToWorktree:()=>z7});import{execFile as Pw}from"node:child_process";import{promisify as Gw}from"node:util";var n2=Gw(Pw);function A4(f){let $=f?.metadata?.checkpoint&&typeof f.metadata.checkpoint==="object"&&!Array.isArray(f.metadata.checkpoint)?f.metadata.checkpoint:void 0;return(Array.isArray($?.history)?$.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let Z=String(Q.ref??"").trim(),W=Number(Q.createdAt??0),j=Number(Q.runCount??0);if(Z.length===0||!Number.isFinite(W)||!Number.isInteger(j)||j<1)return[];let H=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...H?{kind:H}:{}}]})}function O7(f,$){let J=A4(f).filter((Z)=>Z.runCount<=$),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function Fw(f,$){return f.reduce((J,Q)=>{if(Q.runCount>$)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function CB(f,$){let J=0;for(let Q=0;Q<f.length;Q+=1){let Z=f[Q];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===$)return Q}throw Error(`Could not find user message for checkpoint run ${$}`)}function SB(f,$){let J=CB(f,$);return f.slice(0,J+1)}function _7(f,$){let J=CB(f,$);return f.slice(0,J)}function T7(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=Fw(A4(f.session),$);if(!J)throw Error(`No checkpoint found at or before run ${$} in session ${f.session.sessionId}`);let Q=(f.cwd?.trim()||f.session.cwd||f.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...f.restoreMessages!==!1?{messages:SB(f.messages??[],$)}:{}}}async function z7(f,$){if((await n2("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await n2("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await n2("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await n2("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await n2("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await n2("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}var hB={};q(hB,{SessionVersioningService:()=>C$,SessionVersioningError:()=>h0});class h0 extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function Uw(f){let $=f.sessionId.trim();if(!$)throw new h0("invalid_restore","sessionId is required");if(!f.restoreMessages&&!f.restoreWorkspace)throw new h0("invalid_restore","restore.messages or restore.workspace must be true");if(f.restoreMessages&&f.requiresStart)throw new h0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(f.checkpointRunCount)||f.checkpointRunCount<1)throw new h0("invalid_restore","checkpointRunCount must be a positive integer");return $}class C${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,Q=Uw({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),Z=await f.getSession(Q);if(!Z)throw new h0("session_not_found",`Session ${Q} not found`);let W=$?await f.readMessages(Q):void 0;if($&&W?.length===0)throw new h0("session_messages_not_found",`No messages found for session ${Q}`);let j=T7({session:Z,messages:W,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??z7)(j.cwd,j.checkpoint);let H=Pf({session:Z,messages:W});if(!$)return{checkpoint:j.checkpoint,sourceSnapshot:H};let X=O7(Z,f.checkpointRunCount),A=f.restore?.omitCheckpointMessageFromSession?_7(W??[],f.checkpointRunCount):j.messages??[],Y={sourceSession:Z,sourceMessages:W,sourceSnapshot:H,plan:j,restoredCheckpointMetadata:X,initialMessages:A,restoreMessages:$,restoreWorkspace:J,checkpointRunCount:f.checkpointRunCount};if(!f.start||!f.startSession)throw new h0("invalid_restore","start is required when restore.messages is true");let V=f.buildStartInput?await f.buildStartInput(Y,f.start):f.start,B=await f.startSession(V),K=f.getStartedSessionId?.(B);if(K)await(f.retainCheckpointRefs??BA)(j.cwd,K,X?.history??[]);let P=K&&f.readRestoredSession?await f.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:H,...P?{restoredSnapshot:Pf({session:P,messages:A})}:{}}}}var bB={};q(bB,{FileTeamPersistenceStore:()=>P9});import{appendFileSync as Rw,existsSync as M7,mkdirSync as Dw,readFileSync as Lw,renameSync as Ow,unlinkSync as _w,writeFileSync as Tw}from"node:fs";import{join as N7}from"node:path";import{resolveTeamDataDir as zw}from"@cline/shared/storage";function Mw(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class P9{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=Mw(f.teamName),J=f.baseDir?.trim()||zw();this.dirPath=N7(J,$),this.statePath=N7(this.dirPath,"state.json"),this.taskHistoryPath=N7(this.dirPath,"task-history.jsonl")}loadState(){if(!M7(this.statePath))return;try{let f=Lw(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return EV($.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec(f){this.teammateSpecs.set(f.agentId,f)}removeTeammateSpec(f){this.teammateSpecs.delete(f)}persist(f){if(!this.hasPersistableState(f)){this.clearPersistedState();return}this.ensureDir();let $={version:1,updatedAt:new Date().toISOString(),teamState:f.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;Tw(J,`${JSON.stringify($,null,2)}
698
+ `,"utf8"),Ow(J,this.statePath)}appendTaskHistory(f){let $={};switch(f.type){case"team_task_updated":$=f.task;break;case"team_message":$={agentId:f.message.fromAgentId,toAgentId:f.message.toAgentId,subject:f.message.subject,taskId:f.message.taskId};break;case"team_mission_log":$={agentId:f.entry.agentId,kind:f.entry.kind,summary:f.entry.summary,taskId:f.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":$={agentId:f.agentId,message:"message"in f?f.message:void 0};break;case"task_end":$={agentId:f.agentId,finishReason:f.result?.finishReason,error:f.error?.message};break;case"agent_event":$={agentId:f.agentId,eventType:f.event.type};break}this.ensureDir(),Rw(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:f.type,task:$})}
699
+ `,"utf8")}ensureDir(){if(!M7(this.dirPath))Dw(this.dirPath,{recursive:!0})}hasPersistableState(f){let $=f.exportState();if(this.teammateSpecs.size>0)return!0;if($.members.some((J)=>J.role==="teammate"))return!0;return $.tasks.length>0||$.mailbox.length>0||$.missionLog.length>0}clearPersistedState(){if(M7(this.statePath))_w(this.statePath)}}var kB={};q(kB,{ChatViewStateSchema:()=>q7,ChatSummarySchema:()=>D9,ChatSessionStatusSchema:()=>F9,ChatSessionConfigSchema:()=>G9,ChatMessageSchema:()=>R9,ChatMessageRoleSchema:()=>U9});import{z as E}from"zod";var G9=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()}),F9=E.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),U9=E.enum(["user","assistant","tool","system","status","error"]),R9=E.object({id:E.string().min(1),sessionId:E.string().nullable(),role:U9,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()}),D9=E.object({toolCalls:E.number().int().nonnegative(),tokensIn:E.number().int().nonnegative(),tokensOut:E.number().int().nonnegative()}),q7=E.object({sessionId:E.string().nullable(),status:F9,config:G9,messages:E.array(R9),rawTranscript:E.string(),error:E.string().nullable(),summary:D9});var IB={};q(IB,{CORE_BUILD_VERSION:()=>y7});var y7=p3;import{Agent as HC,createAgentRuntime as XC}from"@cline/agents";var gB={};q(gB,{fetchClineRecommendedModels:()=>w7,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>L9});import{getClineEnvironmentConfig as Nw}from"@cline/shared";var qw=5000,L9={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 yw(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function xB(f){if(!f||typeof f!=="object")return null;let $=f;if(typeof $.id!=="string"||$.id.length===0)return null;return{id:$.id,name:typeof $.name==="string"&&$.name.length>0?$.name:$.id,description:typeof $.description==="string"?$.description:"",tags:Array.isArray($.tags)?$.tags.filter((J)=>typeof J==="string"):[]}}function ww(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],Q=Array.isArray($.free)?$.free:[],Z=J.map(xB).filter((j)=>j!==null),W=Q.map(xB).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function Cw(f){let $=f.baseUrl?.trim();if($)return $;let J=Nw().apiBaseUrl;try{return(f.providerSettingsManager??new Lf).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function Sw(f,$,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await f($,{signal:Q.signal})}finally{clearTimeout(Z)}}async function w7(f={}){try{let $=Cw(f),J=f.fetchImpl??fetch,Q=await Sw(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??qw);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=ww(Z);if(W)return W}catch{}return yw(L9)}var mB={};q(mB,{loadLlmsConfigFromFile:()=>S7,defineLlmsConfig:()=>C7});import{readFile as Ew}from"node:fs/promises";import hw from"node:path";function C7(f){return f}async function S7(f){let $=hw.resolve(f),J=await Ew($,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${$}": ${W}`)}return bw(Q,$)}function bw(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let Q=f.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}var pB={};q(pB,{createLlmsSdk:()=>h7,DefaultLlmsSdk:()=>Y4});import{BUILT_IN_PROVIDER_IDS as uB,createHandler as xw,createHandlerAsync as gw,getProviderCollection as mw,hasProvider as dB,registerAsyncHandler as vw,registerHandler as cw,registerModel as uw,registerProvider as lB}from"@cline/llms";function vB(f){return f?{...f}:{}}function kw(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function Iw(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function cB(f){let $=Object.keys(f.collection.models);return{id:f.collection.provider.id,name:f.collection.provider.name,description:f.collection.provider.description,protocol:f.collection.provider.protocol,baseUrl:f.collection.provider.baseUrl,capabilities:f.collection.provider.capabilities,env:f.collection.provider.env,models:$,defaultModel:f.collection.provider.defaultModelId,modelCount:$.length}}class E7{providers=new Map;register(f){Iw(f.id,f.models);let $=f.defaultModel??f.models[0];if(!$)throw Error(`Provider "${f.id}" must define a default model.`);if(!f.models.includes($))throw Error(`Default model "${$}" is not included in configured models for "${f.id}".`);let J=this.providers.get(f.id);this.providers.set(f.id,{id:f.id,models:new Set([...J?.models??[],...f.models]),defaultModel:$,defaults:{...J?.defaults??{},...vB(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:kw(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...vB(f.settings)}})}registerModel(f,$){let J=this.providers.get(f);if(!J){this.providers.set(f,{id:f,models:new Set([$]),defaultModel:$,defaults:{}});return}J.models.add($)}createHandlerConfig(f){let $=this.require(f.providerId),J=f.modelId??$.defaultModel;if(!$.models.has(J))throw Error(`Model "${J}" is not configured for provider "${f.providerId}".`);return{providerId:f.providerId,modelId:J,...$.defaults,...f.overrides}}list(){return Array.from(this.providers.values()).map((f)=>({id:f.id,models:Array.from(f.models),defaultModel:f.defaultModel}))}getModels(f){return Array.from(this.require(f).models)}hasProvider(f){return this.providers.has(f)}hasModel(f,$){return this.providers.get(f)?.models.has($)??!1}require(f){let $=this.providers.get(f);if(!$)throw Error(`Provider "${f}" is not configured in this SDK instance.`);return $}}class Y4{configuredProviders=new E7;constructor(f){this.applyConfig(f)}createHandler(f){return xw(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return gw(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(lB(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)cw(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)vw(f.collection.provider.id,f.asyncHandlerFactory);this.configuredProviders.register({id:f.collection.provider.id,models:f.exposeModels??Object.keys(f.collection.models),defaultModel:f.defaultModel??f.collection.provider.defaultModelId,defaults:f.defaults})}registerBuiltinProvider(f){let $=f.exposeModels??Object.keys(f.models),J=f.defaultModel??$[0];if(!J)throw Error(`Provider "${f.id}" must define a default model.`);lB({provider:{id:f.id,name:f.name??f.id,description:f.description,protocol:f.protocol,baseUrl:f.baseUrl,defaultModelId:J,client:f.client??"openai-compatible",capabilities:f.capabilities,env:f.env,source:"system"},models:f.models}),this.configuredProviders.register({id:f.id,models:$,defaultModel:J,defaults:{routingProviderId:f.builtinProviderId,...f.defaults??{}}})}registerModel(f){uw(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...uB]}async getBuiltInProviders(){return(await Promise.all(uB.map(($)=>mw($)))).filter(($)=>$!==void 0).map(($)=>cB({collection:$}))}getModels(f){return this.configuredProviders.getModels(f)}isProviderConfigured(f){return this.configuredProviders.hasProvider(f)}isModelConfigured(f,$){return this.configuredProviders.hasModel(f,$)}applyConfig(f){for(let $ of f.providers)this.configuredProviders.registerSelectionConfig($);for(let $ of f.models??[])this.registerModel($);for(let $ of f.customProviders??[])this.registerProvider($);for(let $ of this.configuredProviders.list()){let J=dB($.id),Q=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,Z=typeof Q==="string"&&dB(Q);if(!J&&!Z)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function h7(f){return new Y4(f)}l9();async function dw(){return Promise.resolve().then(() => (gW(),lV))}function KC(){return new Date().toISOString()}function PC(f){if(eB(f)!=="providers.json")return;let $=k7(f);if(eB($)!=="settings")return;return k7($)}class Lf{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??BC(),this.dataDir=f.dataDir??PC(this.filePath),this.dataDir||!f.filePath)X4({providerSettingsManager:this,dataDir:this.dataDir});if(FB(this),W9(this.read()),b7(this.filePath))try{oB(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!b7(this.filePath))return T$();try{let f=YC(this.filePath,"utf8"),$=JSON.parse(f),J=O2.safeParse($);if(J.success)return W9(J.data),J.data}catch{}return T$()}write(f){let $=O2.parse(f),J=k7(this.filePath);if(!b7(J))AC(J,{recursive:!0,mode:448});VC(this.filePath,`${JSON.stringify($,null,2)}
700
+ `,"utf8");try{oB(this.filePath,384)}catch{}W9($)}saveProviderSettings(f,$={}){let J=_J.parse(f),Q=this.read(),Z=J.provider,W=$.setLastUsed!==!1,j=Q.providers[Z],H=$.tokenSource??j?.tokenSource??"manual",X={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:KC(),tokenSource:H}},lastUsedProvider:W?Z:Q.lastUsedProvider};return this.write(X),X}getProviderSettings(f){return this.read().providers[f]?.settings}getLastUsedProviderSettings(){let f=this.read(),$=f.lastUsedProvider;if(!$)return;return f.providers[$]?.settings}getProviderConfig(f,$){let J=this.getProviderSettings(f);if(!J)return;return d0(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return d0($,f)}async refreshCatalog(){try{await D2({})}catch{}}}O0();a4();function GC(f,$){let J=f?.expiresAt,Q=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===Q}class _9 extends Error{providerId;constructor(f){super(`OAuth credentials for provider "${f}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=f}}class I7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new Lf,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){let $=B0(f.providerId);if(!$)return null;return this.resolveWithSingleFlight($.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let Q=this.resolveProviderApiKeyInternal(f,$).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,Q),Q}async resolveProviderApiKeyInternal(f,$){let J=B0(f);if(!J)return null;let Q=this.providerSettingsManager.getProviderSettings(J.storageProviderId);if(!Q)return null;let Z=w8(f,Q);if(!Z)return null;let W=await J.refresh({settings:Q,credentials:Z,forceRefresh:$,telemetry:this.telemetry});if(!W)throw new _9(f);let j=l$({manager:this.providerSettingsManager,providerId:f,settings:Q,credentials:W,setLastUsed:!1,save:!1}),H=!GC(Q.auth,j.auth);if(H)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:J.getApiKey(j)??W.access,accountId:W.accountId,refreshed:H}}}import{normalizeUserInput as FC}from"@cline/shared";import{nanoid as UC}from"nanoid";class fK{list(f){return f?n0(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),Q=f.pendingPrompts.findIndex((X)=>X.id===J);if(Q<0)return{sessionId:$.sessionId,prompts:n0(f),updated:!1};let Z=f.pendingPrompts[Q];if(!Z)return{sessionId:$.sessionId,prompts:n0(f),updated:!1};let W=$.prompt===void 0?Z.prompt:FC($.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=$.delivery??Z.delivery,H={...Z,prompt:W,mode:$.mode??Z.mode,delivery:j};return f.pendingPrompts.splice(Q,1),RC(f,H,Q,Z.delivery),{sessionId:$.sessionId,prompts:n0(f),prompt:T9(H),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),Q=f.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:$.sessionId,prompts:n0(f),removed:!1};let[Z]=f.pendingPrompts.splice(Q,1);return{sessionId:$.sessionId,prompts:n0(f),prompt:Z?T9(Z):void 0,removed:!0}}enqueue(f,$){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=$,H=f.pendingPrompts.findIndex((X)=>X.prompt===J);if(H>=0){let[X]=f.pendingPrompts.splice(H,1),A={...X,prompt:J,mode:Q??X.mode,userImages:W??X.userImages,userFiles:j??X.userFiles};if(Z==="steer"||X.delivery==="steer")f.pendingPrompts.unshift({...A,delivery:"steer"});else f.pendingPrompts.push(A)}else{let X={id:`pending_${Date.now()}_${UC(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")f.pendingPrompts.unshift(X);else f.pendingPrompts.push(X)}return n0(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if($<0)return{prompts:n0(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:n0(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:n0(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),n0(f)}clear(f){return f.pendingPrompts.length=0,[]}}class x7{deps;service=new fK;constructor(f){this.deps=f}list(f){return this.service.list(this.deps.getSession(f))}update(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=this.service.update($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}delete(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=this.service.delete($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}enqueue(f,$){let J=this.deps.getSession(f);if(!J||J.aborting)return;this.service.enqueue(J,$),this.emitPrompts(J),this.scheduleDrain(f,J)}consumeSteer(f){let $=this.deps.getSession(f);if(!$)return;let{entry:J}=this.service.consumeSteer($);if(!J)return;return this.emitPrompts($),this.emitSubmitted($,J),J}clearAborted(f){if(f.pendingPrompts.length===0)return;this.service.clear(f),this.emitPrompts(f)}emitPrompts(f){this.deps.emit({type:"pending_prompts",payload:{sessionId:f.sessionId,prompts:n0(f)}})}scheduleDrain(f,$){if($.pendingPrompts.length===0||$.aborting||$.drainingPendingPrompts||!$.agent.canStartRun())return;queueMicrotask(()=>{this.drain(f)})}async drain(f){let $=this.deps.getSession(f);if(!$)return;if($.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront($,J),this.emitPrompts($)}finally{if($.drainingPendingPrompts=!1,Q&&$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=T9($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function T9(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function n0(f){return f.pendingPrompts.map(T9)}function RC(f,$,J,Q){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(Q==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}O0();class m7{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let Q=this.deps.getSession(f),Z={sessionId:f,config:$,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=KZ(J),j=!!Q&&(!W.agentId||W.agentId===g7(Q.agent));PZ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:g7(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(zW(J,$),$.type==="agent_event"){let Q={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};PZ(Q,$.event,{agentId:$.agentId,teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let Q=cf({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:g7(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(Q)$$(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await MW(f,$,this.deps.invokeBackendOptional),J)NW(J,f,$,this.deps.emit)}async handlePluginEvent(f,$,J){if($.name==="plugin_log"){this.handlePluginLog(f,$.payload);return}if($.name==="automation_event"){let X=this.deps.getSession(f)?.config.extensionContext?.automation??J;if(!X)return;let A=$.payload&&typeof $.payload==="object"?$.payload:void 0;if(!A)return;await X.ingestEvent(A);return}if($.name!=="steer_message"&&$.name!=="queue_message"&&$.name!=="pending_prompt")return;let Q=$.payload&&typeof $.payload==="object"?$.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():f,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=$.name==="steer_message"?"steer":$.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:W,delivery:j})}handlePluginLog(f,$,J){let Q=this.deps.getSession(f),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!$||typeof $!=="object")return;let W=$,j=typeof W.message==="string"?W.message:"";if(!j)return;let H=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(H.sessionId??=f,typeof W.pluginName==="string"&&W.pluginName)H.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,H);return}if(W.level==="error"){if(Z.error)Z.error(j,H);else Z.log(j,{...H,severity:"error"});return}Z.log(j,H)}}function g7(f){return f.getAgentId()}function v7(f){return{sessionId:f.sessionId,source:f.source,pid:process.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:U$(f.config),teamName:f.config.teamName?.trim()||void 0,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,parentSessionId:typeof f.sessionMetadata?.parentSessionId==="string"?f.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof f.sessionMetadata?.parentAgentId==="string"?f.sessionMetadata.parentAgentId:void 0,agentId:typeof f.sessionMetadata?.agentId==="string"?f.sessionMetadata.agentId:void 0,conversationId:typeof f.sessionMetadata?.conversationId==="string"?f.sessionMetadata.conversationId:void 0,isSubagent:typeof f.sessionMetadata?.isSubagent==="boolean"?f.sessionMetadata.isSubagent:!1,prompt:f.pendingPrompt,metadata:f.sessionMetadata,messagesPath:f.artifacts?.messagesPath,updatedAt:f.updatedAt??f.endedAt??f.startedAt}}function c7(f,$){let J=f[$];return typeof J==="function"?J:null}async function $K(f,$,...J){let Q=c7(f,$);if(!Q)throw Error(`session service method not available: ${$}`);return Promise.resolve(Q.apply(f,J))}async function JK(f,$,...J){let Q=c7(f,$);if(!Q)return;await Promise.resolve(Q.apply(f,J))}async function QK(f,$,...J){let Q=c7(f,$);if(!Q)return;return await Promise.resolve(Q.apply(f,J))}jf();O0();function u7(f,$,J){return{onSubAgentEvent:(Q)=>f.onAgentEvent(J,$,Q),onSubAgentStart:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime;f.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let W=cf({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(W)$$($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...W});H8($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...W}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,W=f.subAgentStarts.get(Q.subAgentId),j=W?Date.now()-W.startedAt:0,H=Q.result?.text?Q.result.text.split(`
701
+ `).length:0;H8($.telemetry,{event:"ended",ulid:J,durationMs:j,outputLines:H,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...cf({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),f.subAgentStarts.delete(Q.subAgentId),f.invokeBackendOptional("handleSubAgentEnd",J,Q)}}}function d7(f,$,J,Q){let Z=u7(f,$,J);return G$({configProvider:{getRuntimeConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:$.hooks,extensions:$.extensions,logger:$.logger,telemetry:$.telemetry},getConnectionConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let j=$.enableTools?$1({cwd:$.cwd,...c0[mf({mode:$.mode})],executors:Q}):[];if($.enableSpawnAgent)j.push(d7(f,$,J,Q));return x$(j)},...Z})}import{readFile as DC,stat as LC}from"node:fs/promises";var OC=20480000;async function ZK(f){let $=await LC(f);if(!$.isFile())throw Error("Path is not a file");if($.size>OC)throw Error("File is too large to read into context.");let J=await DC(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var WK=5000;function G4(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function wC(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=G4($.inputTokens),Q=G4($.outputTokens),Z=G4($.cacheReadTokens),W=G4($.cacheWriteTokens),j=G4($.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 CC(f,$){return{inputTokens:Math.max(f.inputTokens,$.inputTokens),outputTokens:Math.max(f.outputTokens,$.outputTokens),cacheReadTokens:Math.max(f.cacheReadTokens,$.cacheReadTokens),cacheWriteTokens:Math.max(f.cacheWriteTokens,$.cacheWriteTokens),totalCost:Math.max(f.totalCost,$.totalCost)}}class Df{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new iJ;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new C$;constructor(f){let $=TC();if($)yC($);let J=g$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new l2,this.createAgentInstance=f.createAgent??((Q)=>new B$(Q)),this.defaultCapabilities=L0(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new Lf,this.oauthTokenManager=f.oauthTokenManager??new I7({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new x7({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 m7({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,Z,W)=>{this.invoke("persistSessionMessages",Q,Z,W)},enqueuePendingPrompt:(Q,Z)=>this.pendingPromptsController.enqueue(Q,Z),invokeBackendOptional:(Q,...Z)=>this.invokeOptional(Q,...Z)})}async startSession(f){let $=f.source??U0.CLI,J=s(),Q=f.config.sessionId?.trim()??"",Z=Q||MC(),W=f,j=W.initialMessages??[],H=j.length>0?A2(j):K0(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=l7(X,Z),Y=l7(A,`${Z}.messages.json`),V=l7(A,`${Z}.json`),B=U$(f.config),K=C0.parse({version:1,session_id:Z,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:W.config.cwd,workspace_root:B,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,messages_path:Y}),P;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let w=await this.invokeOptionalValue("readSessionManifest",Z);if(w)K=w,P={manifestPath:V,messagesPath:w.messages_path||Y,manifest:w}}let G=await this.seedAggregateUsageFromArtifacts({initialUsage:H,sessionDir:A,rootMessagesPath:P?.messagesPath??Y,manifest:K});this.usageBySession.set(Z,H),this.aggregateUsageBySession.set(Z,G);let F=L0(this.defaultCapabilities,f.capabilities),U=F?.toolExecutors??this.toolExecutors,_=f.localRuntime,M=_?.extensionContext?.logger??_?.logger,L=_?.extensionContext?.automation,D,y={getSession:(w)=>this.sessions.get(w),subAgentStarts:this.subAgentStarts,onAgentEvent:(w,P0,Q0)=>this.eventBridge.dispatchAgentEvent(w,P0,Q0),invokeBackendOptional:(w,...P0)=>this.invokeOptional(w,...P0)};D=await xA({input:W,localRuntime:f.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(w)=>{if(w.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,w.payload,M);return}this.eventBridge.handlePluginEvent(Z,w,L)},onTeamEvent:(w)=>{this.eventBridge.handleTeamEvent(Z,w),D.config.onTeamEvent?.(w)},createSpawnTool:()=>d7(y,D.config,Z,U),createSubAgentLifecycleCallbacks:(w)=>u7(y,w,Z),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(w)=>{await this.persistSessionMetadata(Z,()=>w)}});let b=await this.runtimeBuilder.build(D.runtimeBuilderInput),I=D.config,o=D.providerConfig;if(b.teamRuntime&&!I.teamName?.trim())I.teamName=b.teamRuntime.getTeamName();let A0=[...b.tools,...I.extraTools??[]],f0=b.extensions??D.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:k8(I),tools:A0,hooks:D.hooks,extensions:f0,hookErrorMode:I.hookErrorMode,initialMessages:D.effectiveInput.initialMessages,userFileContentLoader:ZK,toolPolicies:D.toolPolicies,requestToolApproval:D.requestToolApproval?async(w)=>{let P0=D.requestToolApproval,Q0=this.sessions.get(Z);if(Q0)await this.markTurnPending(Q0);try{if(!P0)return{approved:!1,reason:"Tool approval callback is not configured."};return await P0(w)}finally{let y0=this.sessions.get(Z);if(y0?.status==="pending")await this.markTurnRunning(y0)}}:void 0,telemetry:I.telemetry,onConsecutiveMistakeLimitReached:I.onConsecutiveMistakeLimitReached,completionPolicy:b.completionPolicy,consumePendingUserMessage:()=>{let w=this.pendingPromptsController.consumeSteer(Z);return w?J4(w.prompt,w.mode??I.mode):void 0},logger:b.logger??I.logger,extensionContext:I.extensionContext,onEvent:(w)=>this.eventBridge.dispatchAgentEvent(Z,I,w)};t.hooks={...t.hooks,onEvent:async(w)=>{if(await D.hooks?.onEvent?.(w),w.type!=="assistant-message")return;let P0=this.sessions.get(Z);if(!P0)return;let Q0=P0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,Q0,I.systemPrompt)}catch(y0){I.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:y0}),q1(I.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:y0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:I.providerId,modelId:I.modelId}})}}};let s0=this.createAgentInstance(t);if(t.onEvent)s0.subscribeEvents(t.onEvent);b.registerLeadAgent?.(s0);let E$=cf({agentId:s0.getAgentId(),conversationId:s0.getConversationId(),teamId:b.teamRuntime?.getTeamId(),teamName:b.teamRuntime?.getTeamName(),teamRole:b.teamRuntime?"lead":void 0});if(mA(I,Z,Q.length>0,B,E$),E$)$$(I.telemetry,{ulid:Z,modelId:I.modelId,provider:I.providerId,...E$});if(b.teamRuntime)m4(I.telemetry,{ulid:Z,teamId:b.teamRuntime.getTeamId(),teamName:b.teamRuntime.getTeamName(),leadAgentId:s0.getAgentId(),restoredFromPersistence:b.teamRestoredFromPersistence===!0});let i={sessionId:Z,config:I,sessionMetadata:W.sessionMetadata,...P?{artifacts:P}:{},source:$,startedAt:P?.manifest.started_at??J,updatedAt:P?.manifest.ended_at??P?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:b,agent:s0,started:!1,status:P?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:D.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,i),this.emitStatus(Z,"running"),j.length>0&&!P){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 Of;try{if(W.prompt?.trim())if(Of=await this.executeTurn(i,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!i.interactive)await this.finalizeSingleRun(i,Of.finishReason);else await this.completeInteractiveTurn(i,Of.finishReason)}catch(w){if(i.interactive&&i.aborting)Of=await this.completeAbortedInteractiveTurn(i);else throw q1(i.config.telemetry,{component:"core",operation:"session.start",error:w,severity:"error",handled:!1,context:{sessionId:i.sessionId,providerId:i.config.providerId,modelId:i.config.modelId}}),await this.failSession(i),w}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:Y,result:Of}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let Q=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),Q=f.delivery??($.interactive&&!J?"queue":void 0);if($.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:f.sessionId,promptLength:f.prompt.length,userImageCount:f.userImages?.length??0,userFileCount:f.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,mode:f.mode,delivery:Q,userImages:f.userImages,userFiles:f.userFiles});return}try{let Z=await this.executeTurn($,{prompt:f.prompt,mode:f.mode,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,Z.finishReason);else await this.completeInteractiveTurn($,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),Z}catch(Z){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw q1($.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.failSession($),Z}}async getAccumulatedUsage(f){let $=PW(this.usageBySession.get(f)),J=PW(this.aggregateUsageBySession.get(f));return $||J?{usage:$,aggregateUsage:J}:void 0}async abort(f,$){let J=this.sessions.get(f);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:f}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort($)}async stopSession(f){let $=this.sessions.get(f);if(!$)return;if($.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:f}}),$.interactive&&!J0($.status)){await this.releaseSessionRuntime($,"session_stop");return}if($.interactive&&$.agent.canStartRun()){await this.shutdownSession($,{status:this.resolveInteractiveStopStatus($),exitCode:this.resolveInteractiveStopExitCode($),shutdownReason:"session_stop",endReason:"stopped"});return}$.aborting=!0,$.agent.abort(Error("session_stop")),await this.shutdownSession($,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(f="session_manager_dispose"){let $=[...this.sessions.values()];if($.length===0)return;await Promise.allSettled($.map((J)=>J.interactive&&!J0(J.status)?this.releaseSessionRuntime(J,f):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:f,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:f,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession(f){let $=this.sessions.get(f);if($)return v7($);let J=f.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return ZJ(Q);let Z=await this.readManifest(J);return Z?g5(Z):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(ZJ),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift(v7(Z))}return J.slice(0,f)}async deleteSession(f){if(this.sessions.has(f))await this.stopSession(f);let $=await this.invoke("deleteSession",f);if($.deleted)this.usageBySession.delete(f),this.aggregateUsageBySession.delete(f);return $.deleted}async updateSession(f,$){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:f,prompt:$.prompt,metadata:$.metadata,title:$.title}))?.updated===!0}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.getRow($);if(J?.messagesPath)return N$(J.messagesPath);let Q=await this.readManifest($);return N$(Q?.messages_path)}async dispatchHookEvent(f){await pY(f,{queueSpawnRequest:($)=>this.invokeOptional("queueSpawnRequest",$),upsertSubagentSessionFromHook:($)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",$),appendSubagentHookAudit:($,J)=>this.invokeOptional("appendSubagentHookAudit",$,J),applySubagentStatus:($,J)=>this.invokeOptional("applySubagentStatus",$,J)})}subscribe(f,$){return this.events.subscribe(f,$)}async updateSessionModel(f,$){let J=this.getSessionOrThrow(f);J.config.modelId=$,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:$}),J.agent.updateConnection({modelId:$})}handlePluginEvent(f,$,J){return this.eventBridge.handlePluginEvent(f,$,J)}async executeTurn(f,$){let J=await this.prepareTurnInput(f,$),Q=J.prompt.trim();if(!Q)throw Error("prompt cannot be empty");if(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=Q;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let Z=await this.executeAgentTurn(f,Q,J.userImages,J.userFiles);while(qW(f,Z.finishReason)){let W=await yW(f);if(W.length===0)break;let j=wW(f,W);Z=await this.executeAgentTurn(f,j)}return Z}async completeInteractiveTurn(f,$){if($4(f))return;f.lastInteractiveTurnFinishReason=$,await this.markTurnIdle(f),f.aborting=!1}resolveInteractiveStopStatus(f){let $=f.lastInteractiveTurnFinishReason;if(!$)return"cancelled";switch($){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return $}resolveInteractiveStopExitCode(f){return f.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages(),Q=K0();return f.persistedMessages=J,f.started=f.started||J.length>0,this.eventBridge.dispatchAgentEvent(f.sessionId,f.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,Q){let Z=f.started||f.agent.getMessages().length>0,W=f.persistedMessages??f.agent.getMessages(),j=this.usageBySession.get(f.sessionId)??K0(),H=this.aggregateUsageBySession.get(f.sessionId)??j;f.turnUsageBaseline=j,f.turnAggregateUsageBaseline=H,f.turnPrimaryUsage=K0(),f.turnUsageByAgent=new Map,E4(f.config.telemetry,f.sessionId,f.config.mode),g1(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,model:f.config.modelId,source:"user",mode:f.config.mode,...this.getSessionAgentTelemetryIdentity(f)});try{let X=Z?()=>f.agent.continue($,J,Q):()=>f.agent.run($,J,Q),A=await this.runWithAuthRetry(f,X,W);f.started=!0;let Y=h6(A.messages,A,W);f.persistedMessages=Y;let V=jJ(f.turnUsageByAgent?.values()??[]),B=H0(j,A.usage),K=H0(H0(K0(),A.usage),V),P=H0(H,K);return this.usageBySession.set(f.sessionId,B),this.aggregateUsageBySession.set(f.sessionId,P),await this.persistSessionMetadata(f.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:P.totalCost,usage:B,aggregateUsage:P})),await this.invoke("persistSessionMessages",f.sessionId,Y,f.config.systemPrompt),this.observeTaskCompletionTool(f,A),A}catch(X){throw q1(f.config.telemetry,{component:"core",operation:"session.turn",error:X,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.invoke("persistSessionMessages",f.sessionId,f.agent.getMessages(),f.config.systemPrompt),X}finally{f.turnUsageBaseline=void 0,f.turnAggregateUsageBaseline=void 0,f.turnPrimaryUsage=void 0,f.turnUsageByAgent=void 0}}observeTaskCompletionTool(f,$){if(f.submitAndExitObserved)return;if(!$.toolCalls.some((Q)=>Q.name===Y0.SUBMIT_AND_EXIT&&Q.error===void 0))return;f.submitAndExitObserved=!0,W8(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=U$(f.config),Q=qC($.prompt).trim();if(!Q)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let Z=await e1(Q,J);vA(f.config.telemetry,Z);let W=J4(Z.prompt,$.mode??f.config.mode),j=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),H=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),X=Array.from(new Set([...j,...H]));return{prompt:W,userImages:$.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=U$(f.config);f.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:f.sessionId,source:f.source,pid:process.pid,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:$,teamName:f.config.teamName,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,prompt:f.pendingPrompt,metadata:f.sessionMetadata,startedAt:f.startedAt})}async markTurnRunning(f){if(f.status==="running")return;await this.updateStatus(f,"running",null)}async markTurnPending(f){if(f.status==="pending")return;await this.updateStatus(f,"pending",null)}async markTurnIdle(f){if(f.status==="idle")return;await this.updateStatus(f,"idle",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),Q=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,Z=$(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun(f,$){if($4(f))return;let J=$==="aborted"||f.aborting,Q=$==="error";await this.shutdownSession(f,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)W8(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});p5(f);let J=[],Q=(Z,W)=>{J.push(W),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:Z,error:W,severity:"warn"}),q1(f.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:f.sessionId,stage:Z,status:$.status,shutdownReason:$.shutdownReason,providerId:f.config.providerId,modelId:f.config.modelId}})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(Z){Q("update_status",Z)}try{await f.agent.shutdown($.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await f.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete(f.sessionId),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$.endReason,ts:Date.now()}}),J.length>0&&$.status==="failed")throw J[0]}async releaseSessionRuntime(f,$){let J=[],Q=(Z,W)=>{J.push(W),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:Z,error:W,severity:"warn"}),q1(f.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:f.sessionId,stage:Z,reason:$,providerId:f.config.providerId,modelId:f.config.modelId}})};try{await f.agent.shutdown($)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve(f.runtime.shutdown($))}catch(Z){Q("runtime_shutdown",Z)}try{await f.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let Q=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(Z.status=$,J0($))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=Z,f.status=$,f.updatedAt=Q.endedAt??s(),f.endedAt=J0($)?null:Z.ended_at,f.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,Z),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(Q){if(!d$(f.config.providerId)||!NC(Q))throw Q;return await this.syncOAuthCredentials(f,{forceRefresh:!0}),f.agent.restore(J),$()}}async syncOAuthCredentials(f,$){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:f.config.providerId,forceRefresh:$?.forceRefresh})}catch(Q){if(Q instanceof _9)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!J?.apiKey||f.config.apiKey===J.apiKey)return;f.config.apiKey=J.apiKey,f.agent.updateConnection({apiKey:J.apiKey}),f.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),f.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow(f){let $=this.sessions.get(f);if(!$){let J=new Ef(f);throw q1(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:f,activeSessionCount:this.sessions.size}}),J}return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>zC(Q)?Q:p7(f,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return cf({agentId:f.agent.getAgentId(),conversationId:f.agent.getConversationId(),teamId:f.runtime.teamRuntime?.getTeamId(),teamName:f.runtime.teamRuntime?.getTeamName(),teamRole:f.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts(f){let $=await this.summarizePersistedTeammateUsage(f.sessionDir,f.rootMessagesPath,f.manifest.session_id),J=H0(f.initialUsage,$);return this.withPersistedAggregateUsageFloor(J,f.manifest)}async summarizePersistedTeammateUsage(f,$,J){let Q=p7($),Z=`${J}.messages.json`,W;try{W=_C(f)}catch{return K0()}let j=K0();for(let H of W){if(!H.endsWith(".messages.json"))continue;if(H===Z)continue;let X=p7(f,H);if(X===Q)continue;let A=await N$(X);if(A.length===0)continue;j=H0(j,A2(A))}return j}withPersistedAggregateUsageFloor(f,$){let J=wC($.metadata?.aggregateUsage);if(J)return CC(f,J);let Q=$.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=f.totalCost)return f;return{...f,totalCost:Q}}emitStatus(f,$){this.emitSessionSnapshot(f),this.emit({type:"status",payload:{sessionId:f,status:$}})}async emitSessionSnapshot(f){let $=await this.getSession(f);if(!$)return;this.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:Pf({session:$,messages:await this.readSessionMessages(f),usage:this.usageBySession.get(f),aggregateUsage:this.aggregateUsageBySession.get(f)})}})}emit(f){this.events.emit(f)}async listRows(f){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor(f)),WK))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(WK)).find((Q)=>Q.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return $K(this.sessionService,f,...$)}invokeOptional(f,...$){return JK(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return QK(this.sessionService,f,...$)}}function EC(f){return{text:f.text,usage:f.usage,inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function hC(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function nB(f={}){let $=new Df({sessionService:new Rf(new Ff),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await $.startSession({source:J.source?.trim()||U0.CLI,interactive:!1,config:{providerId:SC(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:hC(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await $.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:EC(Z)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function bC(f){if(typeof f==="string")return f.trim()||void 0;if(!Array.isArray(f))return;return f.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
702
+ `).trim()||void 0}var jK=120,r7="...";function V4(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=jK)return $;let J=jK-Buffer.byteLength(r7,"utf8");if(J<=0)return r7;let Q="";for(let Z of $){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${r7}`}async function HK(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,Z=[...await N$(J)].reverse().find((X)=>X.role==="assistant"),W=Z?bC(Z.content):void 0,j=f?.workspaceRoot?.trim()||"workspace",H=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():j;return{title:`Task completed (${$})`,body:V4(W&&W.length>0?W:H.length>0?H:j),severity:"info"}}import{captureSdkError as q9,createSessionId as AS}from"@cline/shared";import{createSessionId as gC}from"@cline/shared";import{createSessionId as xC}from"@cline/shared";function kC(f){switch(f){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function IC(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):{};if(f.parentSessionId?.trim())$.parentSessionId=f.parentSessionId;if(f.parentAgentId?.trim())$.parentAgentId=f.parentAgentId;if(f.agentId?.trim())$.agentId=f.agentId;if(f.conversationId?.trim())$.conversationId=f.conversationId;if(f.messagesPath?.trim())$.messagesPath=f.messagesPath;if(f.prompt?.trim())$.prompt=f.prompt;if(f.provider?.trim())$.provider=f.provider;if(f.model?.trim())$.model=f.model;if(f.source?.trim())$.source=f.source;if(typeof f.pid==="number")$.pid=f.pid;return Object.keys($).length>0?$:void 0}function z9(f,$,J,Q){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:kC(f.status),participants:$?[...$.participants.values()]:[],metadata:IC(f),runtimeOptions:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,mode:typeof f.metadata?.mode==="string"?f.metadata.mode:void 0,systemPrompt:typeof f.metadata?.systemPrompt==="string"?f.metadata.systemPrompt:void 0},runtimeSession:f.agentId?{agentId:f.agentId,team:f.teamName?{teamId:f.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function d(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function v(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function M9(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function b0(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function y1(f,$,J){return{version:"v1",event:f,eventId:xC("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function a0(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let Q=await f.sessionHost.getAccumulatedUsage?.($);return z9(J,f.sessionState.get($),Q?.usage,Q?.aggregateUsage)}async function t0(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[Q,Z]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return Pf({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function N9(f,$,J,Q,Z={}){let W=f.sessionState.get($);if(W){if(Z.interactive!==void 0)W.interactive=Z.interactive;if(!W.participants.has(J))W.participants.set(J,{clientId:J,attachedAt:Date.now(),role:Q});return W}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:Q}]])};return f.sessionState.set($,j),j}async function i7(f,$){let J=gC("approval_"),Q=$.sessionId;if(f.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((W)=>{f.pendingApprovals.set(J,{sessionId:Q,resolve:W}),f.publish(f.buildEvent("approval.requested",{approvalId:J,sessionId:$.sessionId,agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:JSON.stringify($.input??null),policy:$.policy},Q))})}function n7(f,$,J){let Q=f.pendingApprovals.get($);if(!Q)return;return f.pendingApprovals.delete($),Q.resolve(J),{sessionId:Q.sessionId}}function a7(f,$,J){let Q=0;for(let[Z,W]of[...f.pendingApprovals.entries()]){if(!$({approvalId:Z,sessionId:W.sessionId}))continue;f.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function XK(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return v($,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof $.payload?.reason==="string"?$.payload.reason:$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)&&typeof $.payload.payload.reason==="string"?$.payload.payload.reason:void 0,W=$.payload?.approved===!0,j=n7(f,J,{approved:W,reason:Z});if(!j)return v($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),d($,{approvalId:J,approved:W})}import{createSessionId as cC}from"@cline/shared";function mC(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var AK={debug:10,info:20,warn:30,error:40,silent:50};function vC(){let f=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if(f==="debug"||f==="info"||f==="warn"||f==="error"||f==="silent")return f;return process.env.VITEST?"error":"info"}function c(f,$,J={}){if(AK[f]<AK[vC()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,mC(W)]).filter(([,Z])=>Z!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function t7(f,$){let J=$ instanceof Error?$.stack||$.message:String($);c("error",f,{error:J})}async function YK(f,$,J,Q,Z,W){let j=cC("capreq_"),H=performance.now();return c("info","capability.request.start",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z}),await new Promise((X,A)=>{f.pendingCapabilityRequests.set(j,{sessionId:$,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(Y)=>{if(c(Y.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z,ok:Y.ok,error:Y.error,durationMs:Math.round(performance.now()-H)}),!Y.ok){A(Error(Y.error||`Capability ${J} was rejected by ${Z}.`));return}X(Y.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},$)),c("info","capability.request.published",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z})})}function VK(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",Q=f.pendingCapabilityRequests.get(J);if(!Q)return v($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==Q.targetClientId)return v($,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==Q.sessionId)return v($,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return Q.onProgress?.(W),d($,{requestId:J})}function S$(f,$,J){let Q=0;for(let[Z,W]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:Z,...W}))continue;f.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}),f.publish(f.buildEvent("capability.resolved",{requestId:Z,capabilityName:W.capabilityName,targetClientId:W.targetClientId,ok:!1,cancelled:!0,error:J},W.sessionId)),Q+=1}return Q}async function BK(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",Q=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!Q||!Z)return v($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},j=await f.requestCapability(J,Q,W,Z);return d($,j)}catch(W){return v($,"capability_request_failed",W instanceof Error?W.message:String(W))}}function KK(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",Q=f.pendingCapabilityRequests.get(J);if(!Q)return v($,"capability_not_found",`Unknown capability request: ${J}`);let Z=$.clientId?.trim()||"";if(Z!==Q.targetClientId)return v($,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==Q.sessionId)return v($,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);f.pendingCapabilityRequests.delete(J);let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,j=typeof $.payload?.error==="string"?$.payload.error:void 0,H=$.payload?.ok===!0;return c(H?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:H,error:j}),Q.resolve({ok:H,payload:W,error:j}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:H,payload:W,error:j},Q.sessionId)),d($,{requestId:J,ok:H})}import{createSessionId as uC}from"@cline/shared";function PK(f,$){let J=$.payload,Q=J?.clientId?.trim()||$.clientId?.trim()||uC("client_");return f.clients.set(Q,{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),f.publish(f.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),d($,{clientId:Q})}function GK(f,$){let J=$.clientId?.trim(),Q=J?f.clients.get(J):void 0;if(!J||!Q)return v($,"client_not_found","Client is not registered with this hub.");let Z=M9($.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return d($)}function FK(f,$,J){let Q=$.clientId?.trim();if(Q)f.clients.delete(Q),J(Q),f.publish(f.buildEvent("hub.client.disconnected",{clientId:Q}));return d($)}function UK(f,$){return d($,{clients:[...f.clients.values()]})}var dC=30000;function lC(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function pC(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function rC(f,$,J){let Q=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${$}`;return v(f,m$,Q)}function iC(f){return f?f:void 0}function nC(f){let $=typeof f.timeoutMs==="number"?f.timeoutMs:typeof f.timeout_ms==="number"?f.timeout_ms:void 0;if($&&Number.isFinite($)&&$>0)return Math.floor($);let J=typeof f.timeoutSeconds==="number"?f.timeoutSeconds:typeof f.timeout_seconds==="number"?f.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function aC(f,$,J,Q){let Z=performance.now(),W=!1,j={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:Q},H=setInterval(()=>{if(W)return;let Y=Math.round(performance.now()-Z);c("warn","run.heartbeat",{...j,elapsedMs:Y}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:Y,...Q?{timeoutMs:Q}:{}},J.sessionId))},dC),X=f.sessionHost.runTurn(J);X.then((Y)=>{if(!W)return;c("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:Y?.finishReason})},(Y)=>{if(!W)return;c("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:Y})});let A;try{if(!Q)return await X;return await Promise.race([X,new Promise((Y,V)=>{A=setTimeout(()=>{let B=`Hub run ${$.command} timed out after ${Q}ms.`;W=!0,clearInterval(H),V(Error(B)),c("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),a7(f,(K)=>K.sessionId===J.sessionId,B),S$(f,(K)=>K.sessionId===J.sessionId,B),f.sessionHost.abort(J.sessionId,B).catch((K)=>{c("error","run.timeout_abort_failed",{...j,error:K})})},Q)})])}finally{if(W=!0,clearInterval(H),A)clearTimeout(A)}}async function RK(f,$){let J=b0($),Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return v($,"invalid_session_input","session input requires a prompt string");f.publish(f.buildEvent("run.started",void 0,J));let W=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,j=Array.isArray(W?.userFiles)?W.userFiles.filter((Y)=>typeof Y==="string"):void 0,H=nC(Q);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await aC(f,$,{sessionId:J,prompt:Z,mode:iC(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(W?.userImages)?W.userImages:void 0,userFiles:j,timeoutMs:H},H)}catch(Y){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);if(hf(Y))return rC($,J,Y);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:Y instanceof Error?Y.message:String(Y)},J)),Y}if(X){let Y=await t0(f,J),V=pC(X);if(f.publish(f.buildEvent(lC(X.finishReason),{reason:X.finishReason,...V?{error:V}:{},result:X,...Y?{snapshot:Y}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let A=await t0(f,J);return d($,X||A?{...X?{result:X}:{},...A?{snapshot:A}:{}}:void 0)}async function DK(f,$){let J=b0($),Q=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";a7(f,(Z)=>Z.sessionId===J,Q);try{await f.sessionHost.abort(J,$.payload?.reason)}catch(Z){c("warn","run.abort_failed",{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J,error:Z})}finally{S$(f,(Z)=>Z.sessionId===J,Q)}return d($,{applied:!0})}async function LK(f,$){let J=v2($.payload?.payload);if(!J)return v($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),d($,{applied:!0})}async function OK(f,$){switch($.type){case"chunk":return;case"agent_event":await tC(f,$);return;case"hook":if($.payload.hookEventName==="tool_call")f.publish(f.buildEvent("tool.started",{toolName:$.payload.toolName},$.payload.sessionId));else if($.payload.hookEventName==="tool_result")f.publish(f.buildEvent("tool.finished",{toolName:$.payload.toolName},$.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:$.payload.sessionId,summary:$.payload.summary,lastEvent:$.payload.lifecycle};f.publish(f.buildEvent("team.progress",J,$.payload.sessionId));return}case"pending_prompts":f.publish(f.buildEvent("session.pending_prompts",{sessionId:$.payload.sessionId,prompts:$.payload.prompts},$.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:$.payload.id,prompt:$.payload.prompt,delivery:$.payload.delivery,attachmentCount:$.payload.attachmentCount};f.publish(f.buildEvent("session.pending_prompt_submitted",{sessionId:$.payload.sessionId,prompt:J},$.payload.sessionId));return}case"session_snapshot":f.publish(f.buildEvent("session.updated",{sessionId:$.payload.sessionId,snapshot:$.payload.snapshot},$.payload.sessionId));return;case"status":{let[J,Q]=await Promise.all([a0(f,$.payload.sessionId),t0(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},$.payload.sessionId));return}case"ended":await sC(f,$);return;default:return}}async function tC(f,$){let{sessionId:J,event:Q}=$.payload;if(Q.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){f.publish(f.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},J));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){f.publish(f.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":f.publish(f.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},J));break}return}if(Q.type==="usage"){let Z;try{Z=await f.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}f.publish(f.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:$.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:$.payload.teamAgentId,teamRole:$.payload.teamRole}},J));return}if(Q.type==="done")f.publish(f.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function sC(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),Q=J===$.payload.reason||J==="run.start.reply";if(Q)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[Z,W]=await Promise.all([a0(f,$.payload.sessionId),t0(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let j=await HK(Z);f.publish(f.buildEvent("ui.notify",j,$.payload.sessionId))}if(Q)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...W?{snapshot:W}:{}},$.payload.sessionId))}import{createSessionId as zK,parseRuntimeConfigExtensions as MK}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Ir,HUB_COMPACTION_CAPABILITY as xr,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as gr,HUB_HOOK_CAPABILITY_PREFIX as mr,HUB_MISTAKE_LIMIT_CAPABILITY as vr,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as cr,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ur,isHubToolExecutorName as oC}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as ir,HUB_COMPACTION_CAPABILITY as nr,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ar,HUB_HOOK_CAPABILITY_PREFIX as tr,HUB_MISTAKE_LIMIT_CAPABILITY as sr,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as or,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as er}from"@cline/shared";var eC=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function w1(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function fS(f,$){let J=typeof f.name==="string"?f.name.trim():"",Q=typeof f.description==="string"?f.description:"",Z=typeof f.capabilityName==="string"?f.capabilityName.trim():"",W=w1(f.inputSchema);if(!J||!Q||!W||!Z||$.has(Z))return;return $.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...w1(f.lifecycle)?{lifecycle:w1(f.lifecycle)}:{}}}function o7(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let Q of f){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Z=Q,W=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(W==="tool"){let H=fS(Z,J);if(H)$.push(H);continue}if(W==="toolExecutor"){let H=Z.executor;if(!oC(H))continue;J.add(j),$.push({kind:"toolExecutor",capabilityName:j,executor:H});continue}if(W==="hook"){let H=typeof Z.name==="string"?Z.name.trim():"";if(!H)continue;J.add(j),$.push({kind:"hook",capabilityName:j,name:H});continue}if(W==="compaction"){J.add(j),$.push({kind:"compaction",capabilityName:j,...w1(Z.config)?{config:w1(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),$.push({kind:"checkpoint",capabilityName:j,...w1(Z.config)?{config:w1(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),$.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),$.push({kind:"userInstructionService",capabilityName:j})}return $}function TK(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function $S(f){return Object.hasOwn(f,"update")?f.update:f}function F4(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function JS(f){let $=(f??[]).map(F4).filter(Boolean);return $.length>0?new Set($):void 0}function QS(f,$,J){if(!J)return!0;let Q=F4(f),Z=F4($),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 s7(f,$){let J=JS($);return f.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>QS(Q.id,Q.name,J))}function _K(f,$){let J=async(Q,Z)=>{let W=F4(Q),H=s7(f,$).filter((B)=>B.id===W||F4(B.name)===W||B.id.endsWith(`:${W}`)).filter((B)=>!B.disabled);if(H.length!==1)return H.length>1?`Skill "${Q}" is ambiguous. Use one of: ${H.map((B)=>B.id).join(", ")}`:`Skill "${Q}" not found.`;let X=H[0].skill,A=Z?.trim(),Y=A?`
703
703
  <command-args>${A}</command-args>`:"",V=X.description?.trim()?`Description: ${X.description.trim()}
704
704
 
705
705
  `:"";return`<command-name>${X.name}</command-name>${Y}
706
706
  <command-instructions>
707
707
  ${V}${X.instructions}
708
- </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>C7($,f).map(({skill:W,...Z})=>Z),enumerable:!0}),J}function US($,f,J,W){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},Q=async()=>{let j=await W($,J.capabilityName,{},f);if(j?.snapshot)Z=j.snapshot};return{start:Q,stop:()=>{},refreshType:async()=>{await Q()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let X=j.match(/^\/(\S+)/)?.[1];if(!X)return j;let A=Z.runtimeCommands.find((Y)=>Y.name===X);return A?`${A.instructions}${j.slice(X.length+1)}`:j},hasConfiguredSkills:(j)=>C7(Z,j).some((H)=>!H.disabled),createExtension:(j)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[j.includeRules?"rules":void 0,j.registerSkillsTool?"tools":void 0,j.includeSkills||j.includeWorkflows?"commands":void 0].filter((H)=>Boolean(H))},setup(H){if(j.includeRules)H.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>Nf(Z.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(j.registerSkillsTool)H.registerTool(x1(PS(Z,j.allowedSkillNames)));for(let X of Z.runtimeCommands.filter((A)=>A.kind==="skill"&&j.includeSkills||A.kind==="workflow"&&j.includeWorkflows))H.registerCommand({name:X.name,description:X.description,handler:(A)=>{let Y=A.trim();return Y?`${X.instructions}
708
+ </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>s7(f,$).map(({skill:Q,...Z})=>Z),enumerable:!0}),J}function ZS(f,$,J,Q){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},W=async()=>{let j=await Q(f,J.capabilityName,{},$);if(j?.snapshot)Z=j.snapshot};return{start:W,stop:()=>{},refreshType:async()=>{await W()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let X=j.match(/^\/(\S+)/)?.[1];if(!X)return j;let A=Z.runtimeCommands.find((Y)=>Y.name===X);return A?`${A.instructions}${j.slice(X.length+1)}`:j},hasConfiguredSkills:(j)=>s7(Z,j).some((H)=>!H.disabled),createSkillsExecutor:(j)=>_K(Z,j),createExtension:(j)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[j.includeRules?"rules":void 0,j.registerSkillsTool?"tools":void 0,j.includeSkills||j.includeWorkflows?"commands":void 0].filter((H)=>Boolean(H))},setup(H){if(j.includeRules)H.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>b1(Z.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(j.registerSkillsTool)H.registerTool(i$(_K(Z,j.allowedSkillNames)));for(let X of Z.runtimeCommands.filter((A)=>A.kind==="skill"&&j.includeSkills||A.kind==="workflow"&&j.includeWorkflows))H.registerCommand({name:X.name,description:X.description,handler:(A)=>{let Y=A.trim();return Y?`${X.instructions}
709
709
 
710
- ${Y}`:X.instructions}})}})}}function FS($,f,J,W){let Z=J.map((Q)=>[Q.executor,async(...j)=>{let H=j.at(-1),X=j.slice(0,-1);return(await W($,Q.capabilityName,{executor:Q.executor,args:X,context:eB(H)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function RS($,f,J,W){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(Q,j){return(await W($,Z.capabilityName,{toolName:Z.name,input:Q,context:eB(j)},f,j.emitUpdate?(X)=>{j.emitUpdate?.(BS(X))}:void 0))?.result}}))}function DS($,f,J,W){let Z=new Map(J.map((j)=>[j.name,j])),Q={};for(let j of YS){let H=Z.get(j);if(!H)continue;Q[j]=async(X)=>{return(await W($,H.capabilityName,{context:X},f))?.control}}return Object.keys(Q).length>0?Q:void 0}function b7($){let f=$.contributions.filter((X)=>X.kind==="toolExecutor"),J=$.contributions.filter((X)=>X.kind==="tool"),W=$.contributions.filter((X)=>X.kind==="hook"),Z=$.contributions.find((X)=>X.kind==="compaction"),Q=$.contributions.find((X)=>X.kind==="checkpoint"),j=$.contributions.find((X)=>X.kind==="mistakeLimit"),H=$.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:FS($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...W.length>0?{hooks:DS($.sessionId,$.targetClientId,W,$.requestCapability)}:{},...J.length>0?{extraTools:RS($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(X)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:X},$.targetClientId))?.result}}}:{},...Q?{checkpoint:{...$.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(X)=>{return(await $.requestCapability($.sessionId,Q.capabilityName,{context:X},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(X)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:X},$.targetClientId))?.result}}:{},...H?{userInstructionService:US($.sessionId,$.targetClientId,H,$.requestCapability)}:{}}}}var JK="hubCapabilityOwnerClientId";function WK($,f){$[JK]=f}function LS($){let f=$?.[JK];return typeof f==="string"&&f.trim()?f.trim():void 0}async function ZK($,f,J){let W=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};g("info","session.create.begin",Z);let Q=f.payload&&typeof f.payload==="object"?f.payload:{},j=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},H=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,X=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof H?.mode==="string")j.mode=H.mode;else if(typeof X.mode==="string")j.mode=X.mode;if(typeof H?.systemPrompt==="string")j.systemPrompt=H.systemPrompt;else if(typeof X.systemPrompt==="string")j.systemPrompt=X.systemPrompt;if(H?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)j.checkpointEnabled=!0;let A=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},Y=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!Y)return g("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),m(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let V=f.clientId?.trim()||"hub-client",B=E7(X.clientContributions);if(g("info","session.create.contributions_parsed",{...Z,clientId:V,workspaceRoot:Y,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:B.length}),B.length>0)WK(j,V);let G=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||$K(),R=fK(X.configExtensions);g("info","session.create.runtime_build.begin",{...Z,sessionId:G,configExtensionCount:R?.length??0});let P=b7({sessionId:G,targetClientId:V,contributions:B,sessionConfig:H,requestCapability:$.requestCapability});g("info","session.create.start_session.begin",{...Z,sessionId:G,provider:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),model:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub")});let U=await $.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:G,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub"),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:H?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():Y),workspaceRoot:H?.workspaceRoot??Y,systemPrompt:H?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:H?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:H?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:H?.enableTools??X.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??X.enableTeams!==!1,checkpoint:H?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});g("info","session.create.start_session.end",{...Z,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!U.result}),XW($,U.sessionId,V,"creator",{interactive:j.interactive!==!1}),g("info","session.create.read_records.begin",{...Z,sessionId:U.sessionId});let[F,z]=await Promise.all([r0($,U.sessionId),i0($,U.sessionId)]);if(g("info","session.create.read_records.end",{...Z,sessionId:U.sessionId,hasSession:!!F,hasSnapshot:!!z,elapsedMs:Math.round(performance.now()-W)}),F)$.publish($.buildEvent("session.created",{session:F,...z?{snapshot:z}:{}},U.sessionId));return g("info","session.create.reply",{...Z,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-W)}),u(f,{session:F,...z?{snapshot:z}:{}})}async function QK($,f,J){let W=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof W.sessionId==="string"?W.sessionId.trim():f.sessionId?.trim()||"",Q=W.checkpointRunCount;if(!Z)return m(f,"invalid_restore","session.restore requires a session id");let j=W.restore&&typeof W.restore==="object"?W.restore:{},H=j.messages!==!1;if(typeof Q!=="number")return m(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(H&&!X)return m(f,"invalid_restore","sessionConfig is required when restore.messages is true");let A=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},Y=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof X?.mode==="string")Y.mode=X.mode;else if(typeof A.mode==="string")Y.mode=A.mode;if(typeof X?.systemPrompt==="string")Y.systemPrompt=X.systemPrompt;else if(typeof A.systemPrompt==="string")Y.systemPrompt=A.systemPrompt;if(X?.checkpoint?.enabled===!0)Y.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)Y.checkpointEnabled=!0;let V=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},B=f.clientId?.trim()||"hub-client",K=E7(A.clientContributions);if(K.length>0)WK(Y,B);let R=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||$K(),P=fK(A.configExtensions),U=b7({sessionId:R,targetClientId:B,contributions:K,sessionConfig:X,requestCapability:$.requestCapability}),z=await new z1().restoreCheckpoint({sessionId:Z,checkpointRunCount:Q,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)Y.checkpoint=N.restoredCheckpointMetadata;let q=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof Y.source==="string"?Y.source:void 0,interactive:Y.interactive!==!1,sessionMetadata:{...Y,restoredFromSessionId:Z,restoredCheckpointRunCount:Q},initialMessages:N.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:P,...U.localRuntime},capabilities:{toolExecutors:U.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:R,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:N.sourceSession.provider),modelId:X?.modelId??(typeof V.model==="string"?V.model:N.sourceSession.model),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:""),cwd:X?.cwd??N.plan.cwd,workspaceRoot:X?.workspaceRoot??q,systemPrompt:X?.systemPrompt??(typeof A.systemPrompt==="string"?A.systemPrompt:""),mode:X?.mode??(A.mode==="plan"||A.mode==="yolo"?A.mode:"act"),maxIterations:X?.maxIterations??(typeof A.maxIterations==="number"?A.maxIterations:void 0),enableTools:X?.enableTools??A.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??A.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??A.enableTeams!==!1,checkpoint:X?.checkpoint??(A.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof Y.teamName==="string"?Y.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!H)return u(f,{checkpoint:z.checkpoint});let _=z.startResult;if(!_)return m(f,"restore_failed","Checkpoint restore did not start a session");XW($,_.sessionId,B,"creator",{interactive:Y.interactive!==!1});let[D,O]=await Promise.all([r0($,_.sessionId),i0($,_.sessionId)]);if(D)$.publish($.buildEvent("session.created",{session:D,...O?{snapshot:O}:{}},_.sessionId));return u(f,{session:D,...O?{snapshot:O}:{},messages:z.messages??[],checkpoint:z.checkpoint})}catch(X){if(X instanceof S0)return m(f,X.code,X.code==="session_not_found"?`Unknown session: ${Z}`:X.message);return m(f,"restore_failed",X instanceof Error?X.message:String(X))}}async function jK($,f){let J=h0(f);if(!J)return m(f,"invalid_session_attach","session.attach requires a session id");XW($,J,f.clientId?.trim()||"hub-client","participant");let W=await r0($,J);if(W)$.publish($.buildEvent("session.attached",{session:W},J));return W?u(f,{session:W}):m(f,"session_not_found",`Unknown session: ${J}`)}async function HK($,f){let J=h0(f);if(!J)return m(f,"invalid_session_detach","session.detach requires a session id");let W=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([r0($,J)]),Q=LS(Z?.metadata)??W,j=$.sessionState.get(J);if(j){if(j.participants.delete(W),j.createdByClientId===W)j.createdByClientId=Q;if(j.participants.size===0)$.sessionState.delete(J)}_1($,(A)=>A.sessionId===J&&A.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[H,X]=await Promise.all([r0($,J),i0($,J)]);return $.publish($.buildEvent("session.detached",H?{session:H,...X?{snapshot:X}:{},clientId:W}:{clientId:W},J)),u(f)}async function XK($,f){let J=h0(f),W=f.payload?.includeSnapshot===!0,[Z,Q]=await Promise.all([r0($,J),W?i0($,J):Promise.resolve(void 0)]);return Z?u(f,{session:Z,...Q?{snapshot:Q}:{}}):m(f,"session_not_found",`Unknown session: ${J}`)}async function AK($,f){let J=h0(f);if(!J)return m(f,"invalid_session_id","session.messages requires a session id");if(!await r0($,J))return m(f,"session_not_found",`Unknown session: ${J}`);let Z=await $.sessionHost.readSessionMessages(J);return u(f,{sessionId:J,messages:Z})}async function YK($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((Q)=>jW(Q,$.sessionState.get(Q.sessionId)));return u(f,{sessions:Z})}async function VK($,f){let J=h0(f),W=HW(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:W}),[Q,j]=await Promise.all([r0($,J),i0($,J)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:Q,...j?{snapshot:j}:{}}}}async function BK($,f){let J=h0(f),W=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),u(f,{deleted:W})}async function KK($,f){let J=h0(f),W=$.sessionHost.pendingPrompts;if(!W)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await W.list({sessionId:J});return u(f,{sessionId:J,prompts:Z})}async function GK($,f){let J=h0(f),W=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,Q=f.payload?.delivery==="queue"||f.payload?.delivery==="steer"?f.payload.delivery:void 0,j=$.sessionHost.pendingPrompts;if(!j)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await j.update({sessionId:J,promptId:W,prompt:Z,delivery:Q});return u(f,H)}async function PK($,f){let J=h0(f),W=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=$.sessionHost.pendingPrompts;if(!Z)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Q=await Z.delete({sessionId:J,promptId:W});return u(f,Q)}function UK($){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 zS=new Set(["skills","workflows","rules","tools","mcp"]);function k7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H4($,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 _S($,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 FK($){if($===void 0)return{};if(!k7($))throw Error("settings.list payload must be an object.");return{cwd:H4($,"cwd"),workspaceRoot:H4($,"workspaceRoot"),availabilityContext:k7($.availabilityContext)?$.availabilityContext:void 0}}function TS($){if(!k7($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!zS.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...FK($),type:f,id:H4($,"id"),path:H4($,"path"),name:H4($,"name"),enabled:_S($,"enabled")}}class c2{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=OS("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new F$({sessionService:new U$(new G$),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:Lf,requestCapability:(f,J,W,Z,Q)=>uB(this.ctx,f,J,W,Z,Q)},this.schedules=new qf({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let W=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(Lf(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new Tf(this.schedules),this.settings=$.settingsService??new F1,$.cronOptions)this.cronService=new gJ({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{oB(this.ctx,f).catch((J)=>{h7("session event handling failed",J),AW(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())w7(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(_1(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 AW(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 pB(this.ctx,$);case"client.update":return rB(this.ctx,$);case"client.unregister":return iB(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return nB(this.ctx,$);case"session.create":return await ZK(this.ctx,$,(f)=>q7(this.ctx,f));case"session.restore":return await QK(this.ctx,$,(f)=>q7(this.ctx,f));case"session.attach":return await jK(this.ctx,$);case"session.detach":return await HK(this.ctx,$);case"session.get":return await XK(this.ctx,$);case"session.messages":return await AK(this.ctx,$);case"session.list":return await YK(this.ctx,$);case"session.update":return await VK(this.ctx,$);case"session.pending_prompts":return await KK(this.ctx,$);case"session.update_pending_prompt":return await GK(this.ctx,$);case"session.remove_pending_prompt":return await PK(this.ctx,$);case"session.delete":return await BK(this.ctx,$);case"session.hook":return await sB(this.ctx,$);case"run.start":case"session.send_input":return await aB(this.ctx,$);case"run.abort":return await tB(this.ctx,$);case"capability.request":return await dB(this.ctx,$);case"approval.respond":return await gB(this.ctx,$);case"capability.respond":return lB(this.ctx,$);case"capability.progress":return cB(this.ctx,$);case"ui.notify":return this.publish(Lf("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(Lf("ui.show_window",$.payload??{})),u($);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=UK($.command);if(J)this.publish(Lf(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!NS(f.error.code))return;AW(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(FK($.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(Lf("settings.changed",{types:f.changedTypes,snapshot:f.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f.snapshot,changedTypes:f.changedTypes}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:f instanceof Error?f.message:String(f)}}}}subscribe($,f,J){let W=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return W.add(Z),this.listeners.set($,W),()=>{let Q=this.listeners.get($);if(!Q)return;if(Q.delete(Z),Q.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[f,J]of this.sessionState.entries())if(J.participants.delete($),J.participants.size===0)this.sessionState.delete(f);_1(this.ctx,(f)=>f.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let f of this.listeners.values())for(let J of f){if(J.sessionId&&J.sessionId!==$.sessionId)continue;try{J.listener($)}catch(W){h7(`listener threw while publishing ${$.event}`,W),AW(this.options.telemetry,{component:"core",operation:"hub.publish",error:W,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function NS($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as wS}from"node:crypto";import SS from"node:http";import hS from"node:net";import{URL as LK}from"node:url";import{WebSocketServer as CS}from"ws";import{captureSdkError as RK,HUB_COMMAND_SLOW_LOG_MS as MS,resolveHubCommandTimeoutMs as yS,safeJsonParse as qS}from"@cline/shared";function I7($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function DK($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class J4{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,W=!1,Z=(X)=>{try{$.send(JSON.stringify(X))}catch(A){console.error(`[hub] failed to send websocket frame: ${A instanceof Error?A.stack||A.message:String(A)}`)}},Q=(X)=>{Z({kind:"event",envelope:X})},j=async(X)=>{try{let A=JSON.parse(X.data);switch(A.kind){case"command":{let Y=performance.now(),V=!1,B=I7(A);g("info","command.start",B);let K=setTimeout(()=>{if(V)return;g("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-Y)})},MS),G=this.transport.command(A.envelope);G.then((_)=>{if(!V)return;g(_.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-Y),ok:_.ok,errorCode:_.error?.code,errorMessage:_.error?.message})},(_)=>{if(!V)return;g("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-Y),error:_})});let R=!1,P,U,F=yS(A.envelope.command,A.envelope.timeoutMs);try{U=F===null?await G:await Promise.race([G,new Promise((_)=>{P=setTimeout(()=>{R=!0,RK(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${A.envelope.command} did not complete within ${F}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:F}}),_(DK(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${F}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},F)})])}catch(_){if(clearTimeout(K),P)clearTimeout(P);throw _}if(V=R,clearTimeout(K),P)clearTimeout(P);let z=Math.round(performance.now()-Y);if(R)g("error","command.timeout",{...B,durationMs:z,timeoutMs:F});else g(U.ok?"info":"warn","command.end",{...B,durationMs:z,ok:U.ok,errorCode:U.error?.code,errorMessage:U.error?.message});if(A.envelope.command==="client.register"&&U.ok){let D=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(D)J.add(D)}else if(A.envelope.command==="client.unregister"&&U.ok){let _=A.envelope.clientId?.trim();if(_)J.delete(_)}Z({kind:"reply",envelope:U});break}case"stream.subscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;if(f.has(Y))break;let V=await this.transport.subscribe(A.clientId,Q,{sessionId:A.sessionId});f.set(Y,V);break}case"stream.unsubscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;f.get(Y)?.(),f.delete(Y);break}case"reply":case"event":break}}catch(A){let Y=typeof X.data==="string"?qS(X.data):void 0;if(!Y||Y.kind!=="command"){g("error","rejected malformed websocket frame",{error:A});return}g("error","command.error",{...I7(Y),error:A}),RK(this.telemetry,{component:"core",operation:"hub.websocket_command",error:A,severity:"error",handled:!0,context:I7(Y)}),Z({kind:"reply",envelope:DK(Y,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},H=()=>{if(W)return;W=!0;for(let X of f.values())X();f.clear();for(let X of J)this.transport.command({version:"v1",command:"client.unregister",clientId:X});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",H)};return $.addEventListener("message",j),$.addEventListener("close",H),H}}class W4{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function ES($){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 bS($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(W)=>{J({data:ES(W)})});return}$.on("close",J)},removeEventListener(){}}}function kS($){try{$.write(`HTTP/1.1 400 Bad Request\r
710
+ ${Y}`:X.instructions}})}})}}function WS(f,$,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let H=j.at(-1),X=j.slice(0,-1);return(await Q(f,W.capabilityName,{executor:W.executor,args:X,context:TK(H)},$))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function jS(f,$,J,Q){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(W,j){return(await Q(f,Z.capabilityName,{toolName:Z.name,input:W,context:TK(j)},$,j.emitUpdate?(X)=>{j.emitUpdate?.($S(X))}:void 0))?.result}}))}function HS(f,$,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of eC){let H=Z.get(j);if(!H)continue;W[j]=async(X)=>{return(await Q(f,H.capabilityName,{context:X},$))?.control}}return Object.keys(W).length>0?W:void 0}function e7(f){let $=f.contributions.filter((X)=>X.kind==="toolExecutor"),J=f.contributions.filter((X)=>X.kind==="tool"),Q=f.contributions.filter((X)=>X.kind==="hook"),Z=f.contributions.find((X)=>X.kind==="compaction"),W=f.contributions.find((X)=>X.kind==="checkpoint"),j=f.contributions.find((X)=>X.kind==="mistakeLimit"),H=f.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:WS(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...Q.length>0?{hooks:HS(f.sessionId,f.targetClientId,Q,f.requestCapability)}:{},...J.length>0?{extraTools:jS(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...Z?{compaction:{...f.sessionConfig?.compaction??{},...Z.config,compact:async(X)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...W?{checkpoint:{...f.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(X)=>{return(await f.requestCapability(f.sessionId,W.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(X)=>{return(await f.requestCapability(f.sessionId,j.capabilityName,{context:X},f.targetClientId))?.result}}:{},...H?{userInstructionService:ZS(f.sessionId,f.targetClientId,H,f.requestCapability)}:{}}}}var NK="hubCapabilityOwnerClientId";function qK(f,$){f[NK]=$}function XS(f){let $=f?.[NK];return typeof $==="string"&&$.trim()?$.trim():void 0}async function yK(f,$,J){let Q=performance.now(),Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};c("info","session.create.begin",Z);let W=$.payload&&typeof $.payload==="object"?$.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},H=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,X=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof H?.mode==="string")j.mode=H.mode;else if(typeof X.mode==="string")j.mode=X.mode;if(typeof H?.systemPrompt==="string")j.systemPrompt=H.systemPrompt;else if(typeof X.systemPrompt==="string")j.systemPrompt=X.systemPrompt;if(H?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)j.checkpointEnabled=!0;let A=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},Y=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!Y)return c("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),v($,"invalid_session_create","session.create requires workspaceRoot or cwd");let V=$.clientId?.trim()||"hub-client",B=o7(X.clientContributions);if(c("info","session.create.contributions_parsed",{...Z,clientId:V,workspaceRoot:Y,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:B.length}),B.length>0)qK(j,V);let P=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||zK(),R=MK(X.configExtensions);c("info","session.create.runtime_build.begin",{...Z,sessionId:P,configExtensionCount:R?.length??0});let G=e7({sessionId:P,targetClientId:V,contributions:B,sessionConfig:H,requestCapability:f.requestCapability});c("info","session.create.start_session.begin",{...Z,sessionId:P,provider:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),model:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub")});let F=await f.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(W.initialMessages)?W.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...G.localRuntime},capabilities:{toolExecutors:G.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:P,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub"),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:H?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():Y),workspaceRoot:H?.workspaceRoot??Y,systemPrompt:H?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:H?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:H?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:H?.enableTools??X.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??X.enableTeams!==!1,checkpoint:H?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});c("info","session.create.start_session.end",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!F.result}),N9(f,F.sessionId,V,"creator",{interactive:j.interactive!==!1}),c("info","session.create.read_records.begin",{...Z,sessionId:F.sessionId});let[U,_]=await Promise.all([a0(f,F.sessionId),t0(f,F.sessionId)]);if(c("info","session.create.read_records.end",{...Z,sessionId:F.sessionId,hasSession:!!U,hasSnapshot:!!_,elapsedMs:Math.round(performance.now()-Q)}),U)f.publish(f.buildEvent("session.created",{session:U,..._?{snapshot:_}:{}},F.sessionId));return c("info","session.create.reply",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q)}),d($,{session:U,..._?{snapshot:_}:{}})}async function wK(f,$,J){let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():$.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return v($,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},H=j.messages!==!1;if(typeof W!=="number")return v($,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(H&&!X)return v($,"invalid_restore","sessionConfig is required when restore.messages is true");let A=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},Y=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof X?.mode==="string")Y.mode=X.mode;else if(typeof A.mode==="string")Y.mode=A.mode;if(typeof X?.systemPrompt==="string")Y.systemPrompt=X.systemPrompt;else if(typeof A.systemPrompt==="string")Y.systemPrompt=A.systemPrompt;if(X?.checkpoint?.enabled===!0)Y.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)Y.checkpointEnabled=!0;let V=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},B=$.clientId?.trim()||"hub-client",K=o7(A.clientContributions);if(K.length>0)qK(Y,B);let R=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||zK(),G=MK(A.configExtensions),F=e7({sessionId:R,targetClientId:B,contributions:K,sessionConfig:X,requestCapability:f.requestCapability}),_=await new C$().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(y)=>f.sessionHost.getSession(y),readMessages:(y)=>f.sessionHost.readSessionMessages(y),buildStartInput:(y)=>{if(y.restoredCheckpointMetadata)Y.checkpoint=y.restoredCheckpointMetadata;let b=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():y.sourceSession.workspaceRoot||y.sourceSession.cwd;return{source:typeof Y.source==="string"?Y.source:void 0,interactive:Y.interactive!==!1,sessionMetadata:{...Y,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:y.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:G,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:R,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:y.sourceSession.provider),modelId:X?.modelId??(typeof V.model==="string"?V.model:y.sourceSession.model),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:""),cwd:X?.cwd??y.plan.cwd,workspaceRoot:X?.workspaceRoot??b,systemPrompt:X?.systemPrompt??(typeof A.systemPrompt==="string"?A.systemPrompt:""),mode:X?.mode??(A.mode==="plan"||A.mode==="yolo"?A.mode:"act"),maxIterations:X?.maxIterations??(typeof A.maxIterations==="number"?A.maxIterations:void 0),enableTools:X?.enableTools??A.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??A.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??A.enableTeams!==!1,checkpoint:X?.checkpoint??(A.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof Y.teamName==="string"?Y.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(y)=>f.sessionHost.startSession(y),getStartedSessionId:(y)=>y.sessionId,readRestoredSession:(y)=>f.sessionHost.getSession(y)});if(!H)return d($,{checkpoint:_.checkpoint});let M=_.startResult;if(!M)return v($,"restore_failed","Checkpoint restore did not start a session");N9(f,M.sessionId,B,"creator",{interactive:Y.interactive!==!1});let[L,D]=await Promise.all([a0(f,M.sessionId),t0(f,M.sessionId)]);if(L)f.publish(f.buildEvent("session.created",{session:L,...D?{snapshot:D}:{}},M.sessionId));return d($,{session:L,...D?{snapshot:D}:{},messages:_.messages??[],checkpoint:_.checkpoint})}catch(X){if(X instanceof h0)return v($,X.code,X.code==="session_not_found"?`Unknown session: ${Z}`:X.message);return v($,"restore_failed",X instanceof Error?X.message:String(X))}}async function CK(f,$){let J=b0($);if(!J)return v($,"invalid_session_attach","session.attach requires a session id");N9(f,J,$.clientId?.trim()||"hub-client","participant");let Q=await a0(f,J);if(Q)f.publish(f.buildEvent("session.attached",{session:Q},J));return Q?d($,{session:Q}):v($,"session_not_found",`Unknown session: ${J}`)}async function SK(f,$){let J=b0($);if(!J)return v($,"invalid_session_detach","session.detach requires a session id");let Q=$.clientId?.trim()||"hub-client",[Z]=await Promise.all([a0(f,J)]),W=XS(Z?.metadata)??Q,j=f.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)f.sessionState.delete(J)}S$(f,(A)=>A.sessionId===J&&A.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[H,X]=await Promise.all([a0(f,J),t0(f,J)]);return f.publish(f.buildEvent("session.detached",H?{session:H,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},J)),d($)}async function EK(f,$){let J=b0($),Q=$.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([a0(f,J),Q?t0(f,J):Promise.resolve(void 0)]);return Z?d($,{session:Z,...W?{snapshot:W}:{}}):v($,"session_not_found",`Unknown session: ${J}`)}async function hK(f,$){let J=b0($);if(!J)return v($,"invalid_session_id","session.messages requires a session id");if(!await a0(f,J))return v($,"session_not_found",`Unknown session: ${J}`);let Z=await f.sessionHost.readSessionMessages(J);return d($,{sessionId:J,messages:Z})}async function bK(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,Z=(await f.sessionHost.listSessions(J)).map((W)=>z9(W,f.sessionState.get(W.sessionId)));return d($,{sessions:Z})}async function kK(f,$){let J=b0($),Q=M9($.payload?.metadata),Z=await f.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([a0(f,J),t0(f,J)]);if(W)f.publish(f.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:$.version,requestId:$.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function IK(f,$){let J=b0($),Q=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),d($,{deleted:Q})}async function xK(f,$){let J=b0($),Q=f.sessionHost.pendingPrompts;if(!Q)return v($,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return d($,{sessionId:J,prompts:Z})}async function gK(f,$){let J=b0($),Q=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",Z=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,W=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,j=f.sessionHost.pendingPrompts;if(!j)return v($,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return d($,H)}async function mK(f,$){let J=b0($),Q=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",Z=f.sessionHost.pendingPrompts;if(!Z)return v($,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return d($,W)}function vK(f){switch(f){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var YS=new Set(["skills","workflows","rules","tools","mcp"]);function f3(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function U4(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function VS(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function cK(f){if(f===void 0)return{};if(!f3(f))throw Error("settings.list payload must be an object.");return{cwd:U4(f,"cwd"),workspaceRoot:U4(f,"workspaceRoot"),availabilityContext:f3(f.availabilityContext)?f.availabilityContext:void 0}}function BS(f){if(!f3(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!YS.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...cK(f),type:$,id:U4(f,"id"),path:U4(f,"path"),name:U4(f,"name"),enabled:VS(f,"enabled")}}class a2{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=AS("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new Df({sessionService:new Rf(new Ff),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:f.telemetry,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:y1,requestCapability:($,J,Q,Z,W)=>YK(this.ctx,$,J,Q,Z,W)},this.schedules=new x1({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let Q=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(y1(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new h1(this.schedules),this.settings=f.settingsService??new M$,f.cronOptions)this.cronService=new rJ({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{OK(this.ctx,$).catch((J)=>{t7("session event handling failed",J),q9(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:$.type,sessionId:$.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())n7(this.ctx,f,{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(f){console.error("[hub] cron service stop failed",f)}}async handleCommand(f){try{let $=await this.dispatchCommand(f);return this.captureFailedReply(f,$),$}catch($){throw q9(this.options.telemetry,{component:"core",operation:"hub.command",error:$,severity:"error",handled:!1,context:this.commandTelemetryContext(f)}),$}}async dispatchCommand(f){switch(f.command){case"client.register":return PK(this.ctx,f);case"client.update":return GK(this.ctx,f);case"client.unregister":return FK(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return UK(this.ctx,f);case"session.create":return await yK(this.ctx,f,($)=>i7(this.ctx,$));case"session.restore":return await wK(this.ctx,f,($)=>i7(this.ctx,$));case"session.attach":return await CK(this.ctx,f);case"session.detach":return await SK(this.ctx,f);case"session.get":return await EK(this.ctx,f);case"session.messages":return await hK(this.ctx,f);case"session.list":return await bK(this.ctx,f);case"session.update":return await kK(this.ctx,f);case"session.pending_prompts":return await xK(this.ctx,f);case"session.update_pending_prompt":return await gK(this.ctx,f);case"session.remove_pending_prompt":return await mK(this.ctx,f);case"session.delete":return await IK(this.ctx,f);case"session.hook":return await LK(this.ctx,f);case"run.start":case"session.send_input":return await RK(this.ctx,f);case"run.abort":return await DK(this.ctx,f);case"capability.request":return await BK(this.ctx,f);case"approval.respond":return await XK(this.ctx,f);case"capability.respond":return KK(this.ctx,f);case"capability.progress":return VK(this.ctx,f);case"ui.notify":return this.publish(y1("ui.notify",f.payload??{})),d(f);case"ui.show_window":return this.publish(y1("ui.show_window",f.payload??{})),d(f);case"settings.list":return await this.handleSettingsList(f);case"settings.toggle":return await this.handleSettingsToggle(f);case"settings.get":case"settings.patch":return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"not_implemented",message:`${f.command} is not implemented yet.`}};default:{let $=await this.scheduleCommands.handleCommand(f);if($.ok){let J=vK(f.command);if(J)this.publish(y1(J,$.payload))}return $}}}captureFailedReply(f,$){if($.ok||!$.error||!KS($.error.code))return;q9(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error($.error.message),severity:$.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext(f),errorCode:$.error.code}})}commandTelemetryContext(f){return{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:typeof f.payload?.sessionId==="string"?f.payload.sessionId:f.sessionId}}async handleSettingsList(f){try{let $=await this.settings.list(cK(f.payload));return{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_list_failed",message:$ instanceof Error?$.message:String($)}}}}async handleSettingsToggle(f){try{let $=await this.settings.toggle(BS(f.payload));return this.publish(y1("settings.changed",{types:$.changedTypes,snapshot:$.snapshot})),{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$.snapshot,changedTypes:$.changedTypes}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_toggle_failed",message:$ instanceof Error?$.message:String($)}}}}subscribe(f,$,J){let Q=this.listeners.get(f)??new Set,Z={sessionId:J?.sessionId,listener:$};return Q.add(Z),this.listeners.set(f,Q),()=>{let W=this.listeners.get(f);if(!W)return;if(W.delete(Z),W.size===0)this.listeners.delete(f)}}detachClientFromSessions(f){for(let[$,J]of this.sessionState.entries())if(J.participants.delete(f),J.participants.size===0)this.sessionState.delete($);S$(this.ctx,($)=>$.targetClientId===f,`Capability owner client ${f} disconnected before request was resolved.`)}publish(f){for(let $ of this.listeners.values())for(let J of $){if(J.sessionId&&J.sessionId!==f.sessionId)continue;try{J.listener(f)}catch(Q){t7(`listener threw while publishing ${f.event}`,Q),q9(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:f.event,sessionId:f.sessionId}})}}}}function KS(f){return f==="session_not_found"||f==="session_messages_not_found"||f==="hub_command_timeout"||f.endsWith("_failed")}import{timingSafeEqual as US}from"node:crypto";import RS from"node:http";import DS from"node:net";import{URL as lK}from"node:url";import{WebSocketServer as LS}from"ws";import{captureSdkError as uK,HUB_COMMAND_SLOW_LOG_MS as PS,resolveHubCommandTimeoutMs as GS,safeJsonParse as FS}from"@cline/shared";function $3(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function dK(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class B4{transport;telemetry;constructor(f,$){this.transport=f;this.telemetry=$}attach(f){let $=new Map,J=new Set,Q=!1,Z=(X)=>{try{f.send(JSON.stringify(X))}catch(A){console.error(`[hub] failed to send websocket frame: ${A instanceof Error?A.stack||A.message:String(A)}`)}},W=(X)=>{Z({kind:"event",envelope:X})},j=async(X)=>{try{let A=JSON.parse(X.data);switch(A.kind){case"command":{let Y=performance.now(),V=!1,B=$3(A);c("info","command.start",B);let K=setTimeout(()=>{if(V)return;c("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-Y)})},PS),P=this.transport.command(A.envelope);P.then((M)=>{if(!V)return;c(M.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-Y),ok:M.ok,errorCode:M.error?.code,errorMessage:M.error?.message})},(M)=>{if(!V)return;c("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-Y),error:M})});let R=!1,G,F,U=GS(A.envelope.command,A.envelope.timeoutMs);try{F=U===null?await P:await Promise.race([P,new Promise((M)=>{G=setTimeout(()=>{R=!0,uK(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${A.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:U}}),M(dK(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},U)})])}catch(M){if(clearTimeout(K),G)clearTimeout(G);throw M}if(V=R,clearTimeout(K),G)clearTimeout(G);let _=Math.round(performance.now()-Y);if(R)c("error","command.timeout",{...B,durationMs:_,timeoutMs:U});else c(F.ok?"info":"warn","command.end",{...B,durationMs:_,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(A.envelope.command==="client.register"&&F.ok){let L=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(L)J.add(L)}else if(A.envelope.command==="client.unregister"&&F.ok){let M=A.envelope.clientId?.trim();if(M)J.delete(M)}Z({kind:"reply",envelope:F});break}case"stream.subscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;if($.has(Y))break;let V=await this.transport.subscribe(A.clientId,W,{sessionId:A.sessionId});$.set(Y,V);break}case"stream.unsubscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;$.get(Y)?.(),$.delete(Y);break}case"reply":case"event":break}}catch(A){let Y=typeof X.data==="string"?FS(X.data):void 0;if(!Y||Y.kind!=="command"){c("error","rejected malformed websocket frame",{error:A});return}c("error","command.error",{...$3(Y),error:A}),uK(this.telemetry,{component:"core",operation:"hub.websocket_command",error:A,severity:"error",handled:!0,context:$3(Y)}),Z({kind:"reply",envelope:dK(Y,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},H=()=>{if(Q)return;Q=!0;for(let X of $.values())X();$.clear();for(let X of J)this.transport.command({version:"v1",command:"client.unregister",clientId:X});J.clear(),f.removeEventListener("message",j),f.removeEventListener("close",H)};return f.addEventListener("message",j),f.addEventListener("close",H),H}}class K4{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function OS(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();return String(f)}function _S(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(Q)=>{J({data:OS(Q)})});return}f.on("close",J)},removeEventListener(){}}}function TS(f){try{f.write(`HTTP/1.1 400 Bad Request\r
711
711
  Connection: close\r
712
712
  Content-Length: 0\r
713
713
  \r
714
- `),$.end()}catch{$.destroy()}}function IS($){try{$.write(`HTTP/1.1 401 Unauthorized\r
714
+ `),f.end()}catch{f.destroy()}}function zS(f){try{f.write(`HTTP/1.1 401 Unauthorized\r
715
715
  Connection: close\r
716
716
  Content-Length: 0\r
717
717
  \r
718
- `),$.end()}catch{$.destroy()}}function OK($,f){if(!$||!f)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(f,"utf8");return J.length===W.length&&wS(J,W)}function zK($,f){let J=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,W=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",Z=`Failed to start hub server on ${f.host}:${f.port}${f.pathname}: ${W}`,Q=Error(J?`${Z} (${J})`:Z);if(J)$.code=J,Q.code=J;if($ instanceof Error&&$.stack)Q.stack=`${Q.name}: ${Q.message}
719
- Caused by: ${$.stack}`;return Q}async function xS($){return await new Promise((f,J)=>{let W=hS.createServer();W.once("error",J),W.listen(0,$,()=>{let Z=W.address();if(!Z||typeof Z==="string"){W.close(()=>J(Error("Failed to resolve free port")));return}let Q=Z.port;W.close((j)=>{if(j){J(j);return}f(Q)})})})}function mS($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var x7=new Map,_K="cline-hub-auth.",gS=30000;function TK($){return Array.isArray($)?$.join(","):$??""}function vS($){let f=TK($).trim();return/^Bearer\s+(.+)$/i.exec(f)?.[1]?.trim()||null}function uS($){for(let f of TK($).split(",")){let J=f.trim();if(J.startsWith(_K))return J.slice(_K.length).trim()||null}return null}async function Z4($){let f=$.owner??w$(),J=$.host??"127.0.0.1",W=$.pathname??"/hub",Z=$.port??bf(),Q=Z===0?await xS(J):Z,j=Q,H=t0(J,Q,W),X=t$(),A=g4(),Y=new c2($);await Y.start();let V=new J4(new W4(Y),$.telemetry),B=new Set,K=new Date().toISOString(),G={protocolVersion:"v1",coreVersion:A8.version,buildId:X,pid:process.pid,startedAt:K},R=new Set,P,U,F=async()=>{if(U)return U;return U=(async()=>{if(P)clearInterval(P),P=void 0;for(let O of R)O.terminate?.();R.clear();for(let O of B)O();if(B.clear(),await new Promise((O,N)=>{_.close((q)=>{if(q){N(q);return}O()})}),await new Promise((O,N)=>{z.close((q)=>{if(q){N(q);return}O()})}),await Y.stop(),(await V0(f.discoveryPath))?.url===H)await b0(f.discoveryPath)})(),U},z=SS.createServer((D,O)=>{if((D.url??"/")==="/health"){let q=JSON.stringify({hubId:Y.getHubId(),...G,authToken:"",host:J,port:j,url:H,updatedAt:new Date().toISOString()});O.statusCode=200,O.setHeader("content-type","application/json"),O.end(q);return}if((D.url??"/")==="/version"){O.statusCode=200,O.setHeader("content-type","application/json"),O.end(JSON.stringify(G));return}if(new LK(D.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&D.method==="POST"){if(!OK(vS(D.headers.authorization),A)){O.statusCode=401,O.end("Unauthorized");return}O.statusCode=202,O.setHeader("content-type","application/json"),O.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{F()});return}O.statusCode=404,O.end("Not found")}),_=new CS({noServer:!0});P=setInterval(()=>{for(let D of R){if(D.isAlive===!1){try{D.terminate?.()}catch{}R.delete(D);continue}D.isAlive=!1;try{D.ping?.()}catch{try{D.terminate?.()}catch{}R.delete(D)}}},gS),z.on("upgrade",(D,O,N)=>{if(new LK(D.url??"/",`http://${J}:${j}`).pathname!==W){O.destroy();return}if(!OK(uS(D.headers["sec-websocket-protocol"]),A)){IS(O);return}try{_.handleUpgrade(D,O,N,($0)=>{let A0=$0;A0.isAlive=!0,A0.on("pong",()=>{A0.isAlive=!0}),R.add(A0);let o=V.attach(bS($0));B.add(o),$0.once("close",()=>{R.delete(A0),o(),B.delete(o)})})}catch{kS(O)}});try{await new Promise((D,O)=>{z.once("error",(N)=>{O(zK(N,{host:J,port:Q,pathname:W}))}),z.listen(Q,J,()=>{let N=z.address();if(!N||typeof N==="string"){O(zK(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:W}));return}j=N.port,H=t0(J,j,W),D()})})}catch(D){if(P)clearInterval(P),P=void 0;throw await Y.stop().catch(()=>{return}),D}return await v4(f.discoveryPath,{hubId:Y.getHubId(),protocolVersion:"v1",coreVersion:A8.version,buildId:X,authToken:A,host:J,port:j,url:H,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:H,authToken:A,close:F}}async function WW($){let f=$.owner??w$(),J=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.host??"127.0.0.1",Z=$.port??bf(),Q=$.pathname??"/hub",j=t0(W,Z,Q),H=f.discoveryPath,X=(Y)=>{if(!J)s$(Y.url,Y.authToken);return Y},A=x7.get(H);if(A){let Y=await A;if(Y.url===j)return X({server:Y,url:Y.url,authToken:Y.authToken,action:"reuse"})}return await u4(f.discoveryPath,async()=>{let Y=await V0(f.discoveryPath);if(Y?.url&&(Y.url===j||$.allowPortFallback===!0)){let G=await Q$(Y.url);if(G?.url&&await H$(G.url,{authToken:Y.authToken}))return X({url:G.url,authToken:Y.authToken,action:"reuse"})}if((await Q$(j))?.url||Y?.url)await b0(f.discoveryPath);let K=async(G)=>{let R=Z4({...G,owner:f});x7.set(H,R);try{let P=await R;return X({server:P,url:P.url,authToken:P.authToken,action:"started"})}catch(P){throw x7.delete(H),P}};try{return await K($)}catch(G){if(!$.allowPortFallback||!mS(G))throw G;return await K({...$,port:0})}})}async function MB($){let f=j$({host:$.host,port:$.port,pathname:$.pathname});return await Z4({...$,...f,owner:G0()})}async function yB($){let f=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=j$({host:$.host,port:$.port,pathname:$.pathname});return await WW({...$,...J,allowPortFallback:$.allowPortFallback??!f,owner:G0()})}export{v4 as writeHubDiscovery,u4 as withHubStartupLock,H$ as verifyHubConnection,f4 as truncateNotificationBody,CW as toHubHealthUrl,lW as stopLocalHubServerGracefully,Z4 as startHubWebSocketServer,MB as startHubServer,kf as spawnDetachedHubServerWithRetry,mW as spawnDetachedHubServer,n3 as sendHubCommand,l4 as restartLocalHubIfIdleAfterStartupTimeout,I3 as resolveWorkspaceHubOwnerContext,G0 as resolveSharedHubOwnerContext,pW as resolveHubUrl,w$ as resolveHubOwnerContext,j$ as resolveHubEndpointOptions,t$ as resolveHubBuildId,bf as resolveDefaultHubPort,xW as resolveDefaultHubPathname,IW as resolveDefaultHubHost,G8 as resolveCompatibleLocalHubUrl,C3 as resolveClineDir,Y8 as resolveClineDataDir,K8 as requestHubShutdown,s$ as rememberRecoverableLocalHubUrl,V0 as readHubDiscovery,Q$ as probeHubServer,i3 as probeHubConnection,c4 as prewarmDetachedHubServer,o$ as normalizeHubWebSocketUrl,cW as isHubReconnectableTransportError,d4 as isHubCommandTimeoutError,b3 as isDiscoveryFilePresent,WW as ensureHubWebSocketServer,yB as ensureHubServer,m3 as ensureDetachedHubServer,b1 as ensureCompatibleLocalHubUrl,NB as createLocalHubScheduleRuntimeHandlers,E3 as createInMemoryHubOwnerContext,t0 as createHubServerUrl,g4 as createHubAuthToken,M$ as createConfiguredTelemetryService,Ef as createConfiguredTelemetryHandle,p4 as connectToHub,b0 as clearHubDiscovery,s0 as NodeHubClient,W4 as NativeHubTransportAdapter,nW as HubUIClient,z0 as HubTransportError,iW as HubSessionClient,c2 as HubServerTransport,qf as HubScheduleService,Tf as HubScheduleCommandService,If as HubCommandError,bW as DEFAULT_HUB_PORT,kW as DEFAULT_HUB_PATHNAME,EW as DEFAULT_HUB_HOST,J4 as BrowserWebSocketHubAdapter};
718
+ `),f.end()}catch{f.destroy()}}function pK(f,$){if(!f||!$)return!1;let J=Buffer.from(f,"utf8"),Q=Buffer.from($,"utf8");return J.length===Q.length&&US(J,Q)}function rK(f,$){let J=f&&typeof f==="object"&&"code"in f&&typeof f.code==="string"?f.code:void 0,Q=f instanceof Error?f.message:typeof f==="string"?f:"Unknown startup error",Z=`Failed to start hub server on ${$.host}:${$.port}${$.pathname}: ${Q}`,W=Error(J?`${Z} (${J})`:Z);if(J)f.code=J,W.code=J;if(f instanceof Error&&f.stack)W.stack=`${W.name}: ${W.message}
719
+ Caused by: ${f.stack}`;return W}async function MS(f){return await new Promise(($,J)=>{let Q=DS.createServer();Q.once("error",J),Q.listen(0,f,()=>{let Z=Q.address();if(!Z||typeof Z==="string"){Q.close(()=>J(Error("Failed to resolve free port")));return}let W=Z.port;Q.close((j)=>{if(j){J(j);return}$(W)})})})}function NS(f){return f instanceof Error&&"code"in f&&f.code==="EADDRINUSE"}var J3=new Map,iK="cline-hub-auth.",qS=30000;function nK(f){return Array.isArray(f)?f.join(","):f??""}function yS(f){let $=nK(f).trim();return/^Bearer\s+(.+)$/i.exec($)?.[1]?.trim()||null}function wS(f){for(let $ of nK(f).split(",")){let J=$.trim();if(J.startsWith(iK))return J.slice(iK.length).trim()||null}return null}async function P4(f){let $=f.owner??bf(),J=f.host??"127.0.0.1",Q=f.pathname??"/hub",Z=f.port??d1(),W=Z===0?await MS(J):Z,j=W,H=o0(J,W,Q),X=J$(),A=s4(),Y=new a2(f);await Y.start();let V=new B4(new K4(Y),f.telemetry),B=new Set,K=new Date().toISOString(),P={protocolVersion:"v1",coreVersion:G8.version,buildId:X,pid:process.pid,startedAt:K},R=new Set,G,F,U=async()=>{if(F)return F;return F=(async()=>{if(G)clearInterval(G),G=void 0;for(let D of R)D.terminate?.();R.clear();for(let D of B)D();if(B.clear(),await new Promise((D,y)=>{M.close((b)=>{if(b){y(b);return}D()})}),await new Promise((D,y)=>{_.close((b)=>{if(b){y(b);return}D()})}),await Y.stop(),(await V0($.discoveryPath))?.url===H)await x0($.discoveryPath)})(),F},_=RS.createServer((L,D)=>{if((L.url??"/")==="/health"){let b=JSON.stringify({hubId:Y.getHubId(),...P,authToken:"",host:J,port:j,url:H,updatedAt:new Date().toISOString()});D.statusCode=200,D.setHeader("content-type","application/json"),D.end(b);return}if((L.url??"/")==="/version"){D.statusCode=200,D.setHeader("content-type","application/json"),D.end(JSON.stringify(P));return}if(new lK(L.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&L.method==="POST"){if(!pK(yS(L.headers.authorization),A)){D.statusCode=401,D.end("Unauthorized");return}D.statusCode=202,D.setHeader("content-type","application/json"),D.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{U()});return}D.statusCode=404,D.end("Not found")}),M=new LS({noServer:!0});G=setInterval(()=>{for(let L of R){if(L.isAlive===!1){try{L.terminate?.()}catch{}R.delete(L);continue}L.isAlive=!1;try{L.ping?.()}catch{try{L.terminate?.()}catch{}R.delete(L)}}},qS),_.on("upgrade",(L,D,y)=>{if(new lK(L.url??"/",`http://${J}:${j}`).pathname!==Q){D.destroy();return}if(!pK(wS(L.headers["sec-websocket-protocol"]),A)){zS(D);return}try{M.handleUpgrade(L,D,y,(I)=>{let o=I;o.isAlive=!0,o.on("pong",()=>{o.isAlive=!0}),R.add(o);let A0=V.attach(_S(I));B.add(A0),I.once("close",()=>{R.delete(o),A0(),B.delete(A0)})})}catch{TS(D)}});try{await new Promise((L,D)=>{_.once("error",(y)=>{D(rK(y,{host:J,port:W,pathname:Q}))}),_.listen(W,J,()=>{let y=_.address();if(!y||typeof y==="string"){D(rK(Error("Failed to resolve hub port"),{host:J,port:W,pathname:Q}));return}j=y.port,H=o0(J,j,Q),L()})})}catch(L){if(G)clearInterval(G),G=void 0;throw await Y.stop().catch(()=>{return}),L}return await o4($.discoveryPath,{hubId:Y.getHubId(),protocolVersion:"v1",coreVersion:G8.version,buildId:X,authToken:A,host:J,port:j,url:H,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:H,authToken:A,close:U}}async function O9(f){let $=f.owner??bf(),J=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=f.host??"127.0.0.1",Z=f.port??d1(),W=f.pathname??"/hub",j=o0(Q,Z,W),H=$.discoveryPath,X=(Y)=>{if(!J)Q$(Y.url,Y.authToken);return Y},A=J3.get(H);if(A){let Y=await A;if(Y.url===j)return X({server:Y,url:Y.url,authToken:Y.authToken,action:"reuse"})}return await e4($.discoveryPath,async()=>{let Y=await V0($.discoveryPath);if(Y?.url&&(Y.url===j||f.allowPortFallback===!0)){let P=await Hf(Y.url);if(P?.url&&await Af(P.url,{authToken:Y.authToken}))return X({url:P.url,authToken:Y.authToken,action:"reuse"})}if((await Hf(j))?.url||Y?.url)await x0($.discoveryPath);let K=async(P)=>{let R=P4({...P,owner:$});J3.set(H,R);try{let G=await R;return X({server:G,url:G.url,authToken:G.authToken,action:"started"})}catch(G){throw J3.delete(H),G}};try{return await K(f)}catch(P){if(!f.allowPortFallback||!NS(P))throw P;return await K({...f,port:0})}})}async function aB(f){let $=Xf({host:f.host,port:f.port,pathname:f.pathname});return await P4({...f,...$,owner:F0()})}async function tB(f){let $=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=Xf({host:f.host,port:f.port,pathname:f.pathname});return await O9({...f,...J,allowPortFallback:f.allowPortFallback??!$,owner:F0()})}export{o4 as writeHubDiscovery,e4 as withHubStartupLock,Af as verifyHubConnection,V4 as truncateNotificationBody,t9 as toHubHealthUrl,XQ as stopLocalHubServerGracefully,P4 as startHubWebSocketServer,aB as startHubServer,l1 as spawnDetachedHubServerWithRetry,JQ as spawnDetachedHubServer,Kj as sendHubCommand,J6 as restartLocalHubIfIdleAfterStartupTimeout,$j as resolveWorkspaceHubOwnerContext,F0 as resolveSharedHubOwnerContext,AQ as resolveHubUrl,bf as resolveHubOwnerContext,Xf as resolveHubEndpointOptions,J$ as resolveHubBuildId,d1 as resolveDefaultHubPort,$Q as resolveDefaultHubPathname,fQ as resolveDefaultHubHost,L8 as resolveCompatibleLocalHubUrl,s3 as resolveClineDir,F8 as resolveClineDataDir,D8 as requestHubShutdown,Q$ as rememberRecoverableLocalHubUrl,V0 as readHubDiscovery,Hf as probeHubServer,Bj as probeHubConnection,f6 as prewarmDetachedHubServer,Z$ as normalizeHubWebSocketUrl,jQ as isHubReconnectableTransportError,$6 as isHubCommandTimeoutError,e3 as isDiscoveryFilePresent,O9 as ensureHubWebSocketServer,tB as ensureHubServer,Qj as ensureDetachedHubServer,c$ as ensureCompatibleLocalHubUrl,nB as createLocalHubScheduleRuntimeHandlers,o3 as createInMemoryHubOwnerContext,o0 as createHubServerUrl,s4 as createHubAuthToken,Sf as createConfiguredTelemetryService,u1 as createConfiguredTelemetryHandle,Q6 as connectToHub,x0 as clearHubDiscovery,e0 as NodeHubClient,K4 as NativeHubTransportAdapter,BQ as HubUIClient,T0 as HubTransportError,VQ as HubSessionClient,a2 as HubServerTransport,x1 as HubScheduleService,h1 as HubScheduleCommandService,p1 as HubCommandError,o9 as DEFAULT_HUB_PORT,e9 as DEFAULT_HUB_PATHNAME,s9 as DEFAULT_HUB_HOST,B4 as BrowserWebSocketHubAdapter};